Main Page | Packages | Class Hierarchy | Class List | Directories | File List | Class Members | Related Pages

OpenMSPDBSyncListener.java

00001 /*
00002  * OpenMobileIS - a free Java(TM) Framework for mobile applications Java(TM)
00003  * Copyright (C) 2004-2005 Philippe Delrieu
00004  * All rights reserved.
00005  * Contact: openmobileis@e-care.fr
00006  *
00007  * This library is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or any later version.
00011  *
00012  * This library is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with this library; if not, write to the Free Software
00019  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
00020  * USA
00021  *
00022  *  Author : Philippe Delrieu
00023  * 
00024  */
00025 package org.openmobileis.synchro.openmsp.client;
00026 
00027 import java.io.ByteArrayOutputStream;
00028 import java.io.OutputStreamWriter;
00029 
00030 import org.openmobileis.common.intl.IntlResourceManager;
00031 import org.openmobileis.common.util.codec.GeneralCoder;
00032 import org.openmobileis.common.util.exception.SynchroException;
00033 import org.openmobileis.common.util.log.LogManager;
00034 import org.openmobileis.database.DatabaseException;
00035 import org.openmobileis.synchro.client.SynchroDescriptor;
00036 import org.openmobileis.synchro.journal.JournalEntry;
00037 import org.openmobileis.synchro.journal.JournalManager;
00038 import org.openmobileis.synchro.openmsp.OpenMSPException;
00039 import org.openmobileis.synchro.openmsp.client.core.NumSyncManagerDB;
00040 import org.openmobileis.synchro.openmsp.client.db.ActionDB;
00041 import org.openmobileis.synchro.openmsp.client.db.DBImportFileCoder;
00042 import org.openmobileis.synchro.openmsp.client.db.ImportQueryManager;
00043 import org.openmobileis.synchro.openmsp.client.db.SyncActionDBManager;
00044 import org.openmobileis.synchro.openmsp.protocol.AbstractCommand;
00045 import org.openmobileis.synchro.openmsp.protocol.Command;
00046 import org.openmobileis.synchro.openmsp.protocol.ContainerMessage;
00047 import org.openmobileis.synchro.openmsp.protocol.DataItem;
00048 import org.openmobileis.synchro.openmsp.protocol.Element;
00049 import org.openmobileis.synchro.openmsp.protocol.Item;
00050 import org.openmobileis.synchro.openmsp.protocol.Message;
00051 import org.openmobileis.synchro.openmsp.protocol.RequestCommand;
00052 import org.openmobileis.synchro.openmsp.protocol.Result;
00053 import org.openmobileis.synchro.openmsp.protocol.Status;
00054 import org.openmobileis.synchro.security.auth.Credential;
00055 
00063 public abstract class OpenMSPDBSyncListener extends DefaultOpenMSPSyncListener  {
00064 
00065   private boolean syncGoOn = false;
00066   protected static String ADD_ERROR_MESSAGE;
00067   protected static String UPDATE_ERROR_MESSAGE;
00068   protected static String DELETE_ERROR_MESSAGE;
00069   protected static String ITEM_ERROR_MESSAGE;
00070   protected static String SYNC_ERROR_MESSAGE;
00071   protected static String SYNC_UNAUTHORIZED_MESSAGE;
00072   protected String installPath;
00073 
00077   public OpenMSPDBSyncListener() {
00078     super();
00079     IntlResourceManager resourceManager = IntlResourceManager.getManager();
00080     SYNC_UNAUTHORIZED_MESSAGE = resourceManager.getLocalizedProperty("OpenMSPDbSyncListener.SYNC_UNAUTHORIZED_MESSAGE", "Erreur accès non authorisé, mauvaise authentification.");
00081     SYNC_ERROR_MESSAGE = resourceManager.getLocalizedProperty("OpenMSPDbSyncListener.SYNC_ERROR_MESSAGE", "Erreur générale de la synchronisation sur le serveur distant.");
00082     ITEM_ERROR_MESSAGE = resourceManager.getLocalizedProperty("OpenMSPDbSyncListener.ITEM_ERROR_MESSAGE", "Erreur pendant la récupération des données du serveur distant.");
00083     DELETE_ERROR_MESSAGE = resourceManager.getLocalizedProperty("OpenMSPDbSyncListener.DELETE_ERROR_MESSAGE", "Erreur pendant la suppression d'une donnée sur le serveur distant.");
00084     UPDATE_ERROR_MESSAGE = resourceManager.getLocalizedProperty("OpenMSPDbSyncListener.UPDATE_ERROR_MESSAGE", "Erreur pendant la mise à jour d'une donnée sur le serveur distant.");
00085     ADD_ERROR_MESSAGE = resourceManager.getLocalizedProperty("OpenMSPDbSyncListener.ADD_ERROR_MESSAGE", "Erreur pendant l'ajout d'une donnée sur le serveur distant.");
00086   }
00087 
00088   public void startSync(Credential cred, SynchroDescriptor synchrodescriptor) throws OpenMSPException {
00089     super.startSync(cred, synchrodescriptor);
00090     this.syncGoOn = true;
00091     installPath = synchrodescriptor.getSynchroConduit().getIntallPath();
00092   }
00093 
00094   /* (non-Javadoc)
00095    * @see org.openmobileis.synchro.openmsp.client.OpenMSPSyncListener#sendData(org.openmobileis.synchro.openmsp.protocol.Message)
00096    */
00097   public void sendData(Message message) throws OpenMSPException {
00098     if (!this.isSyncOK()) {
00099       return; // return if an error occurs during synchro.
00100     }
00101 
00102     if (!syncGoOn) { // synchronize data only for the first call.
00103     return;
00104     }
00105     syncGoOn = false;
00106     // construct Atomic Object action list and resolve conflicts
00107     ActionDB[] actionArray = SyncActionDBManager.getManager().getActionsForService(this.getSyncName());
00108      // genererate sync message.
00109     try {
00110       Command syncCommand = new Command(Element.SYNC, this.getSyncName(), this.getSynchroTarget());
00111       long ns = NumSyncManagerDB.getManager().getSyncNumberForService(this.getSyncName());
00112       syncCommand.setSourceSessionID(ns);
00113       String commandMetadata = this.getSendCommandMetaData();
00114       if (commandMetadata != null)  {
00115         syncCommand.setMetaInformation(commandMetadata);
00116       }
00117       Credential cred = this.getSyncroCredential();
00118       if (cred != null) {
00119         DefaultOpenMSPSyncListener.addCredentialToCommand(cred, syncCommand);
00120       }
00121       ContainerMessage syncContainer = new ContainerMessage(syncCommand);
00122 
00123       Item newItem = null;
00124       byte[] actionData = null;
00125       RequestCommand newCommand = null;
00126       ContainerMessage newContainer = null;
00127       for (int i=0; i<actionArray.length; i++) {
00128         if (actionArray[i].getActionType() == ActionDB.ADD_ACTION) { // ADD
00129           actionData = this.getSyncDataForAtomicObjectUID(actionArray[i].getActionObjectUID(), ActionDB.ADD_ACTION);
00130           if (actionData != null) {
00131             newCommand = new RequestCommand(Element.ADD);
00132             newCommand.setMetaInformation(new String(GeneralCoder.encodeBase64(actionArray[i].getActionObjectUID().getBytes())));
00133             newContainer = new ContainerMessage(newCommand);
00134             newItem = new DataItem(
00135                         Element.ITEM
00136                         , new String(GeneralCoder.encodeBase64(("AOUID:"+actionArray[i].getActionObjectUID()).getBytes()))
00137                         , new String(GeneralCoder.encodeBase64(actionData))
00138                         , null
00139                         , null
00140                     );
00141             newContainer.add(newItem);
00142             syncContainer.add(newContainer);
00143           }
00144         } else if (actionArray[i].getActionType() ==ActionDB.UPDATE_ACTION)  { // REPLACE
00145           actionData = this.getSyncDataForAtomicObjectUID(actionArray[i].getActionObjectUID(), ActionDB.UPDATE_ACTION);
00146           if (actionData != null) {
00147             String serverID = this.getServerUIDForAOUID(actionArray[i].getActionObjectUID());
00148             if (serverID != null) {
00149               newCommand = new RequestCommand(Element.REPLACE);
00150               newCommand.setMetaInformation(new String(GeneralCoder.encodeBase64(actionArray[i].getActionObjectUID().getBytes())));
00151               newContainer = new ContainerMessage(newCommand);
00152               newItem = new DataItem(
00153                           Element.ITEM
00154                           , new String(GeneralCoder.encodeBase64(("AOUID:"+serverID).getBytes()))
00155                           , new String(GeneralCoder.encodeBase64(actionData))
00156                           , null
00157                           , null
00158                       );
00159                newContainer.add(newItem);
00160               syncContainer.add(newContainer);
00161             }
00162           }
00163         } else if (actionArray[i].getActionType() ==ActionDB.DELETE_ACTION)  { // DELETE
00164           String serverID = this.getServerUIDForAOUID(actionArray[i].getActionObjectUID());
00165           if (serverID != null) {
00166             newCommand = new RequestCommand(Element.DELETE);
00167             newContainer = new ContainerMessage(newCommand);
00168             newCommand.setMetaInformation(new String(GeneralCoder.encodeBase64(actionArray[i].getActionObjectUID().getBytes())));
00169             newItem = new DataItem(
00170                         Element.ITEM
00171                         , new String(GeneralCoder.encodeBase64(("AOUID:"+serverID).getBytes()))
00172                         , ""
00173                         , null
00174                         , null
00175                     );
00176             newContainer.add(newItem);
00177             syncContainer.add(newContainer);
00178           }
00179         } // REMOVE action nothing done.
00180       }
00181 
00182       // add GET command to make synchro
00183       newCommand = new RequestCommand(Element.GET);
00184       newContainer = new ContainerMessage(newCommand);
00185   //    newCommand.setMetaInformation(new String(GeneralCoder.encodeBase64(actionArray[i].getActionObjectUID().getBytes())));
00186       newItem = new DataItem(
00187                   Element.ITEM
00188                   , ""
00189                   , ""
00190                   , null
00191                   , null
00192               );
00193       newContainer.add(newItem);
00194       syncContainer.add(newContainer);
00195       message.add(syncContainer);
00196     } catch (Throwable ex)  {
00197       this.setSynchroStatus(Status.STATUS_FAILED);
00198       LogManager.traceError(0, ex);
00199     }
00200 
00201   }
00202 
00203   /* (non-Javadoc)
00204    * @see org.openmobileis.synchro.openmsp.client.OpenMSPSyncListener#receiveMapCommand(org.openmobileis.synchro.openmsp.protocol.ContainerMessage, long)
00205    */
00206   public void receiveMapCommand(ContainerMessage mapContainer) throws OpenMSPException {
00207     mapContainer.resetCursor();
00208     try {
00209       while (mapContainer.hasMoreMessage()) {;
00210         Item map = (Item)mapContainer.nextMessage().getElement();
00211         String PDAUID = new String(GeneralCoder.decodeBase64(map.getTarget().getBytes()));
00212         String serverUID = new String(GeneralCoder.decodeBase64(map.getSource().getBytes()));
00213         this.notifyMAPofUID(PDAUID, serverUID);
00214       }
00215     } catch (java.io.IOException ex)  {
00216       this.setSynchroStatus(Status.STATUS_FAILED);
00217       LogManager.trace(new SynchroException(ex));
00218     }
00219   }
00220 
00221   /* (non-Javadoc)
00222    * @see org.openmobileis.synchro.openmsp.client.OpenMSPSyncListener#receiveResultCommand(org.openmobileis.synchro.openmsp.protocol.ContainerMessage, long)
00223    */
00224   public void receiveResultCommand(ContainerMessage resultContainer, ContainerMessage initialCommand) throws OpenMSPException {
00225     Result resultCommand = (Result)resultContainer.getElement(); //result
00226     try {
00227       long newSessionID = Long.parseLong(resultCommand.getMetaInformation());
00228       while (resultContainer.hasMoreMessage())  {
00229         DataItem item = (DataItem) resultContainer.nextMessage().getElement();
00230         String meta = item.getMetaInformation();
00231         String file = item.getData();
00232         if (meta.equals("ImportDataFile"))  {
00233           String importFileName = this.installPath+file;
00234           this.getImportQueryManager().importDataFile(importFileName);
00235         } else if (meta.equals("DatabaseFile"))  {
00236           String importFileName = this.installPath+file;
00237           this.importCompletSynchroDatabaseFile(importFileName);
00238         }
00239       }
00240       
00241       NumSyncManagerDB.getManager().saveSyncNumberForService(newSessionID, this.getSyncName());
00242     } catch (Throwable ex)  {
00243       throw new OpenMSPException(ex);
00244     }
00245   }
00246 
00247   /* (non-Javadoc)
00248    * @see org.openmobileis.synchro.openmsp.client.OpenMSPSyncListener#receiveStatusCommand(org.openmobileis.synchro.openmsp.protocol.Status, long)
00249    */
00250   public void receiveStatusCommand(Status statusCommande, ContainerMessage initialContenaire) throws OpenMSPException {
00251     try {
00252 //      int cmlRef = statusCommande.getCmdRef();
00253       int status = statusCommande.getStatus();
00254       if (initialContenaire != null)  {
00255         AbstractCommand command = (AbstractCommand)initialContenaire.getElement();
00256         this.manageReturnStatusLog(status, command.getElementType(), initialContenaire);
00257         if (status == Status.STATUS_OK)  {
00258           if ((command instanceof RequestCommand) && (command.getElementType() != Element.GET) && (command.getElementType() != Element.SYNC)) {
00259             String pdaID = new String(GeneralCoder.decodeBase64(((RequestCommand)command).getMetaInformation().getBytes()));
00260             if (pdaID != null)  {
00261               SyncActionDBManager.getManager().deleteActionDB(this.getSyncName(), pdaID);
00262               int actionType = ActionDB.UPDATE_ACTION;
00263               if (command.getElementType() == Element.DELETE) {
00264                 actionType = ActionDB.DELETE_ACTION;
00265                 this.removeServerUIDForAOUID(pdaID);
00266              }
00267              this.notifySyncDataDone(pdaID, actionType);
00268             }
00269           }
00270         } else {
00271           //set sync in error
00272           this.notifySynchroFailure();
00273         }
00274       } 
00275     }catch (Exception ex) {
00276       this.setSynchroStatus(Status.STATUS_FAILED);
00277       LogManager.trace(new SynchroException(ex));      
00278     }
00279   }
00280 
00285   protected void manageReturnStatusLog(int statusCode, int cmlType, ContainerMessage container) {
00286     this.setSynchroStatus(statusCode);
00287     if (statusCode != Status.STATUS_OK) {
00288       String message = null;
00289       short journalEntryType = 0;
00290       if (cmlType == Element.ADD)  {
00291         journalEntryType = JournalEntry.ERROR_ADD;
00292         message = OpenMSPDBSyncListener.ADD_ERROR_MESSAGE;
00293       } else if (cmlType == Element.REPLACE)  {
00294         journalEntryType = JournalEntry.ERROR_REPLACE;
00295         message = OpenMSPDBSyncListener.UPDATE_ERROR_MESSAGE;
00296       } else if (cmlType == Element.DELETE)  {
00297         journalEntryType = JournalEntry.ERROR_DELETE;
00298         message = OpenMSPDBSyncListener.DELETE_ERROR_MESSAGE;
00299       } else if (cmlType == Element.ITEM)  {
00300         journalEntryType = JournalEntry.ERROR_SYNC;
00301         message = OpenMSPDBSyncListener.ITEM_ERROR_MESSAGE;
00302       } else if (cmlType == Element.SYNC)  {
00303         journalEntryType = JournalEntry.ERROR_SYNC_MOBILE;
00304         if (statusCode == Status.STATUS_UNAUTHORIZED) {
00305           message = OpenMSPDBSyncListener.SYNC_UNAUTHORIZED_MESSAGE;
00306         } else  {
00307           message = OpenMSPDBSyncListener.SYNC_ERROR_MESSAGE;
00308         }
00309       }
00310       if (message != null)  {
00311         JournalManager.getManager().saveJournalEntry(
00312 
00313            this.getSyncName()
00314 
00315           , journalEntryType
00316 
00317           , message
00318 
00319           , statusCode
00320 
00321         );
00322       }
00323     }
00324 
00325   }
00326 
00327   protected void receiveSyncItem( Credential cred, Item item , long newSyncNumber) {
00328   }
00329 
00335   protected byte[] getSyncDataForAtomicObjectUID(String pdaUID, int action) throws OpenMSPException {
00336     byte[] aoData = null;
00337     char[] charData = null;
00338     if (action == ActionDB.ADD_ACTION)  {
00339       String[] ret  = this.getDBDataForAdd(pdaUID);
00340       if (ret != null)  {
00341        charData = DBImportFileCoder.getCoder().encodeData(DBImportFileCoder.ADDAction, ret);
00342       } else  {
00343         //remove action because not use
00344         SyncActionDBManager.getManager().deleteActionDB(this.getSyncName(), pdaUID);
00345       }
00346     } else if (action == ActionDB.UPDATE_ACTION) {
00347       String[] ret  = this.getDBDataForReplace(pdaUID);
00348       if (ret != null)  {
00349         charData = DBImportFileCoder.getCoder().encodeData(DBImportFileCoder.REPLACEAction, ret);
00350       } else  {
00351         //remove action because not use
00352         SyncActionDBManager.getManager().deleteActionDB(this.getSyncName(), pdaUID);
00353       }
00354     }
00355     if (charData != null) {
00356       ByteArrayOutputStream out = new ByteArrayOutputStream();
00357       OutputStreamWriter writer = new OutputStreamWriter(out);
00358       try {
00359         writer.write(charData);
00360         writer.flush();
00361         writer.close();
00362         aoData = out.toByteArray();
00363       } catch (Exception ex)  {
00364         LogManager.trace(new SynchroException(ex));
00365       }
00366     }
00367     return aoData;
00368   }
00369   
00370   protected String getSendCommandMetaData() {
00371     return null;
00372   }
00373 
00379   protected String getServerUIDForAOUID(String pdaUID)  {
00380     return pdaUID;
00381   }
00382   
00390   public void notifySyncDataDone(String pdaID, int actionType) throws OpenMSPException {
00391   }
00392 
00393   protected void notifyMAPofUID(String pdauid, String serveruid) throws OpenMSPException  {
00394     
00395   }
00396   
00402   protected void removeServerUIDForAOUID(String pdaUID) throws OpenMSPException {
00403   }
00404   
00410   protected void importCompletSynchroDatabaseFile(String importFile) throws DatabaseException {
00411   }
00412 
00417   protected abstract String[] getDBDataForAdd(String pdaUID) throws OpenMSPException;
00422   protected abstract String[] getDBDataForReplace(String pdaUID) throws OpenMSPException;
00423 
00427   protected abstract String getSynchroTarget();
00428 
00433   protected abstract Credential getSyncroCredential();
00434 
00438   protected abstract ImportQueryManager getImportQueryManager();
00439 
00440 }

Generated on Wed Dec 14 21:05:34 2005 for OpenMobileIS by  doxygen 1.4.4