FODBOpenMSPSynchroTargetWrapper.java

00001 /*
00002  * OpenMobileIS - a free Java(TM) Framework for mobile applications Java(TM)
00003  * Copyright (C) 2004-2006 Philippe Delrieu
00004  * All rights reserved.
00005  * Contact: pdelrieu@openmobileis.org
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.database.fastobjectdb.synchro.server;
00026 
00027 import java.io.BufferedInputStream;
00028 import java.io.ByteArrayInputStream;
00029 import java.io.File;
00030 import java.io.FileInputStream;
00031 import java.io.FilenameFilter;
00032 import java.io.IOException;
00033 import java.io.InputStream;
00034 import java.io.ObjectInputStream;
00035 import java.util.StringTokenizer;
00036 
00037 import org.openmobileis.common.context.SessionContext;
00038 import org.openmobileis.common.context.SessionContextManager;
00039 import org.openmobileis.common.user.UserNotFoundException;
00040 import org.openmobileis.common.util.PropertiesManager;
00041 import org.openmobileis.common.util.UniqueIdGenerator;
00042 import org.openmobileis.common.util.codec.GeneralCoder;
00043 import org.openmobileis.common.util.collection.Array;
00044 import org.openmobileis.common.util.exception.ServiceException;
00045 import org.openmobileis.database.fastobjectdb.FODBCollectionDescriptor;
00046 import org.openmobileis.database.fastobjectdb.FODBIndexDescriptor;
00047 import org.openmobileis.database.fastobjectdb.FastObjectDB;
00048 import org.openmobileis.database.fastobjectdb.db.FODBCollection;
00049 import org.openmobileis.database.fastobjectdb.db.crypto.FODBCypher;
00050 import org.openmobileis.synchro.algo.replication.SynchroAtomicObject;
00051 import org.openmobileis.synchro.algo.replication.SynchroConflicResolver;
00052 import org.openmobileis.synchro.openmsp.OpenMSPException;
00053 import org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener;
00054 import org.openmobileis.synchro.openmsp.server.util.OpenMISFile;
00055 import org.openmobileis.synchro.openmsp.server.util.ZipEntryMemoryFile;
00056 import org.openmobileis.synchro.security.auth.Credential;
00057 
00068 public final class FODBOpenMSPSynchroTargetWrapper extends OpenMSPDBSynchroTargetListener {
00069   private FODBSyncTarget syncService;
00070 
00071   private String pregenerateddbpath;
00072 
00078   public FODBOpenMSPSynchroTargetWrapper(FODBSyncTarget syncService, String pregenerateddbpath) {
00079     this(syncService);
00080     this.pregenerateddbpath = pregenerateddbpath;
00081   }
00082 
00087   public FODBOpenMSPSynchroTargetWrapper(FODBSyncTarget syncService) {
00088     super();
00089     // init service data
00090     this.syncService = syncService;
00091   }
00092 
00093   /*
00094    * (non-Javadoc)
00095    *
00096    * @see org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener#getTargetName()
00097    */
00098   public String getTargetName() {
00099     return syncService.getCollectionName();
00100   }
00101 
00102   /*
00103    * (non-Javadoc)
00104    *
00105    * @see org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener#connect(org.openmobileis.synchro.security.auth.Credential)
00106    */
00107   protected void connect(Credential cred) throws UserNotFoundException, ServiceException {
00108     syncService.connect(cred);
00109 
00110   }
00111 
00112   /*
00113    * (non-Javadoc)
00114    *
00115    * @see org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener#disconnect()
00116    */
00117   protected void disconnect() {
00118     syncService.disconnect();
00119 
00120   }
00121 
00122   /*
00123    * (non-Javadoc)
00124    *
00125    * @see org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener#getSynchroConflicResolver()
00126    */
00127   protected SynchroConflicResolver getSynchroConflicResolver() {
00128     return syncService.getConflicResolver();
00129   }
00130 
00131   /*
00132    * (non-Javadoc)
00133    *
00134    * @see org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener#getAllModifiedAtomicObjectSince(long)
00135    */
00136   protected SynchroAtomicObject[] getAllModifiedAtomicObjectSince(long syncNumber) throws OpenMSPException {
00137     return syncService.getAllModifiedAtomicObjectSince(syncNumber);
00138   }
00139 
00140   /*
00141    * (non-Javadoc)
00142    *
00143    * @see org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener#updateTargetWithSynchroObject(java.lang.Object)
00144    */
00145   protected void updateTargetWithSynchroObject(Object syncObject) throws OpenMSPException {
00146     syncService.updateCollectionObject(syncObject);
00147   }
00148 
00149   /*
00150    * (non-Javadoc)
00151    *
00152    * @see org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener#deleteTargetForSynchroObjectId(java.lang.String)
00153    */
00154   protected void deleteTargetForSynchroObjectId(String uid) throws OpenMSPException {
00155     syncService.deleteCollectionObject(uid);
00156 
00157   }
00158 
00159   /*
00160    * (non-Javadoc)
00161    *
00162    * @see org.openmobileis.synchro.openmsp.server.synctarget.OpenMSPDBSynchroTargetListener#getTargetObjectWithId(java.lang.String)
00163    */
00164   protected Object getTargetObjectWithId(String uid) throws OpenMSPException {
00165     return syncService.getCollectionObjectWithId(uid);
00166   }
00167 
00174   protected int getUpdateMaxNbRow() {
00175     return syncService.getUpdateMaxNbRow();
00176   }
00177 
00181   protected void processSyncActionMetaData(String metadata) throws ServiceException {
00182     try {
00183     //manage user metadata
00184     int index  = metadata.indexOf('%');
00185     if (index != -1)    {
00186       String userdata = metadata.substring(0, index);
00187       if (!userdata.startsWith("no-metadata"))  {
00188         Object userdataok = this.unserializeData(userdata);
00189         this.syncService.setSendSynchroMetaData(userdataok);
00190       }
00191       if (index+1 < metadata.length())
00192         metadata = metadata.substring(index+1, metadata.length());
00193     }
00194 
00195     StringTokenizer token = new StringTokenizer(metadata, ":");
00196     if (token.hasMoreTokens()) {
00197       String collectionName = token.nextToken();
00198       SessionContext context = SessionContextManager.getManager().getSessionContext();
00199       context.setAttribute("FODBSyncServiceWrapper%class", collectionName);
00200 
00201       // manage cypher
00202       String encodedcypher = token.nextToken();
00203       if (encodedcypher.equals("nocypher")) {
00204         context.removeAttribute("FODBSyncServiceWrapper%cypher");
00205       } else {
00206           FODBCypher cypher = (FODBCypher) this.unserializeData(encodedcypher);
00207           context.setAttribute("FODBSyncServiceWrapper%cypher", cypher);
00208       }
00209 
00210       // manage collection descriptor
00211       String coldess = token.nextToken();
00212         FODBCollectionDescriptor coldesc = (FODBCollectionDescriptor) this.unserializeData(coldess);
00213         context.setAttribute("FODBSyncServiceWrapper%coldesc", coldesc);
00214 
00215       int nbToken = token.countTokens();
00216       FODBIndexDescriptor[] descList = new FODBIndexDescriptor[nbToken];
00217       int i = 0;
00218       while (token.hasMoreTokens()) {
00219         String descriptor = token.nextToken();
00220           FODBIndexDescriptor desc = (FODBIndexDescriptor) this.unserializeData(descriptor);
00221           descList[i] = desc;
00222         i++;
00223       }
00224       context.setAttribute("FODBSyncServiceWrapper%desclist", descList);
00225     }
00226     } catch (Throwable ex) {
00227       throw new ServiceException(ex);
00228     }
00229 
00230   }
00231 
00232   private Object unserializeData(String data) throws IOException, ClassNotFoundException  {
00233     byte[] b = GeneralCoder.decodeBase64(data.getBytes());
00234     ByteArrayInputStream bstr = new ByteArrayInputStream(b);
00235     try {
00236       ObjectInputStream ostr = new ObjectInputStream(bstr);
00237       return  ostr.readObject();
00238     } finally   {
00239       bstr.close();
00240     }
00241   }
00242 
00243   /*
00244    * (non-Javadoc)
00245    *
00246    * @see org.openmobileis.server.synchro.safeserver.services.DefaultDBService#getDatabaseImportFiles()
00247    */
00248   protected OpenMISFile[] getDatabaseImportFiles() throws ServiceException {
00249     if (this.pregenerateddbpath == null) {
00250       return this.generateImportDatabaseFiles();
00251     } else {
00252       return this.getPregenerateDatabaseFiles();
00253     }
00254   }
00255 
00256   private synchronized OpenMISFile[] getPregenerateDatabaseFiles() throws ServiceException {
00257     try {
00258       // get database name
00259       /*
00260        * int index = this.pregenerateddbpath.indexOf(File.separatorChar); String
00261        * databasename = null; if (index != -1) { to do that db must temporary
00262        * copied. databasename = this.pregenerateddbpath.substring(index+1,
00263        * this.pregenerateddbpath.length()); String dbRootPath =
00264        * this.pregenerateddbpath.substring(0, index); FastObjectDB db =
00265        * FastObjectDB.open(dbRootPath, "databasename");
00266        * syncService.updateSynchroDB(db); }
00267        */
00268 
00269       // get db collection files
00270       File dbFiles = new File(this.pregenerateddbpath);
00271       File[] colFiles = dbFiles.listFiles(new FilenameFilter() {
00272         public boolean accept(File arg0, String arg1) {
00273           return arg1.endsWith(".col");
00274         }
00275       });
00276       OpenMISFile[] retDbFiles = new OpenMISFile[colFiles.length];
00277       String dbPath = this.pregenerateddbpath + File.separatorChar;
00278       String filePath = null;
00279       for (int i = 0; i < retDbFiles.length; i++) {
00280         String fileColName = colFiles[i].getName();
00281         filePath = dbPath + fileColName;
00282         InputStream file = new BufferedInputStream(new FileInputStream(filePath));
00283         retDbFiles[i] = new ZipEntryMemoryFile("/" + fileColName, file);
00284         ((ZipEntryMemoryFile) retDbFiles[i]).setZipFileName("/dbfiles/" + this.getTargetName() + ".zip");
00285         file.close();
00286       }
00287 
00288       return retDbFiles;
00289     } catch (Throwable ex) {
00290       throw new ServiceException(ex);
00291     }
00292   }
00293 
00294   private OpenMISFile[] generateImportDatabaseFiles() throws ServiceException {
00295     try {
00296       String installPath = PropertiesManager.getManager().getProperty("org.openmobileis.database.fastobjectdb.synchro.server.generateddb.installpath");
00297       if (installPath == null) {
00298         installPath = System.getProperty("user.dir") + File.separator + "fodbgen"; // default
00299                                                                                     // Path
00300       }
00301       SessionContext context = SessionContextManager.getManager().getSessionContext();
00302  //     String userId = context.getUserId();
00303       String newis = Long.toString(UniqueIdGenerator.getManager().getNewID());
00304       StringBuffer buff = new StringBuffer(installPath).append(File.separatorChar);
00305       buff.append("temp").append(File.separatorChar).append(newis);
00306       String dirPath = buff.toString();
00307       String dbRootPath = buff.toString();
00308       buff.append(File.separatorChar).append("fodb");
00309       String dbPath = buff.toString();
00310       buff.append(File.separatorChar).append(syncService.getCollectionName()).append(".col");
00311       String filePath = buff.toString();
00312       File toDelFile = new File(filePath);
00313       if (toDelFile.exists()) {
00314         toDelFile.delete();
00315         toDelFile = new File(dbPath + File.separatorChar + "fodb.db");
00316         toDelFile.delete();
00317       }
00318       FastObjectDB db = FastObjectDB.open(dbRootPath, "fodb");
00319       try {
00320         // create collection index
00321         FODBCollectionDescriptor coldesc = (FODBCollectionDescriptor) context.getAttribute("FODBSyncServiceWrapper%coldesc");
00322         db.createCollection(coldesc);
00323 
00324         // manage cypher
00325         FODBCypher cypher = (FODBCypher) context.getAttribute("FODBSyncServiceWrapper%cypher");
00326         if (cypher != null) {
00327           FODBCollection col = db.getCollection(syncService.getCollectionName());
00328           col.setCollectionCypher(cypher);
00329         }
00330         FODBIndexDescriptor[] descList = (FODBIndexDescriptor[]) context.getAttribute("FODBSyncServiceWrapper%desclist");
00331         for (int i = 0; i < descList.length; i++) {
00332           if (descList[i] != null) {
00333             db.addIndex(syncService.getCollectionName(), descList[i]);
00334           }
00335         }
00336 
00337         Array objList = syncService.getAllCollectionObject();
00338         for (int i = 0; i < objList.size(); i++) {
00339           db.add(syncService.getCollectionName(), objList.get(i));
00340         }
00341         syncService.updateSynchroDB(db);
00342 
00343         FODBCollection[] colList = db.getDatabaseCollectionArray();
00344         OpenMISFile[] retDbFiles = new OpenMISFile[colList.length];
00345         dbPath = dbPath + File.separatorChar;
00346         for (int i = 0; i < retDbFiles.length; i++) {
00347           String fileColName = colList[i].getName() + ".col";
00348           filePath = dbPath + fileColName;
00349           InputStream file = new BufferedInputStream(new FileInputStream(filePath));
00350           retDbFiles[i] = new ZipEntryMemoryFile("/" + fileColName, file);
00351           ((ZipEntryMemoryFile) retDbFiles[i]).setZipFileName("/dbfiles/" + this.getTargetName() + ".zip");
00352           file.close();
00353         }
00354         return retDbFiles;
00355       } finally { // delete all db files
00356         toDelFile = new File(dbPath);
00357         File[] files = toDelFile.listFiles();
00358         for (int i = 0; i < files.length; i++) {
00359           files[i].delete();
00360         }
00361         
00362         File todeldir = new File(dirPath+"/fodb");      
00363         todeldir.delete();
00364         todeldir = new File(dirPath);      
00365         todeldir.delete();
00366       }
00367     } catch (Throwable ex) {
00368       throw new ServiceException(ex);
00369     }
00370   }
00371 
00372 }

Generated on Tue May 22 23:01:09 2007 for OpenMobileIS by  doxygen 1.5.1-p1