KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sync4j > syncclient > spap > AssetManager


1 /**
2  * Copyright (C) 2003-2005 Funambol
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18
19 package sync4j.syncclient.spap;
20
21 import java.sql.Timestamp JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.util.Hashtable JavaDoc;
25 import java.util.Vector JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.net.MalformedURLException JavaDoc;
28
29 import sync4j.syncclient.common.FileSystemTools;
30 import sync4j.syncclient.common.HttpTools;
31 import sync4j.syncclient.common.logging.Logger;
32 import sync4j.syncclient.common.VectorTools;
33 import sync4j.syncclient.common.ZipTools;
34 import sync4j.syncclient.spap.launcher.Launcher;
35 import sync4j.syncclient.spap.launcher.LauncherFactory;
36 import sync4j.syncclient.spap.installer.InstallationContext;
37 import sync4j.syncclient.spdm.DeviceManager;
38 import sync4j.syncclient.spdm.ManagementNode;
39 import sync4j.syncclient.spdm.SimpleDeviceManager;
40
41
42 /**
43  * This class supplies the methods for the management of the <code>Asset</code>.
44  *
45  * <p>Manages the synchronization process, the installation process and the
46  * uninstallation process of the assets.</p>
47  *
48  * <p>Uses <code>AssetDAO</code> for retrieves the information of the asset.</p>
49  *
50  * <p>It's a singleton class and for to get an instance you need to use the
51  * <code>getAssetManager()</code> static method.</p>
52  *
53  * AssetManager is configured with a set of directories where it
54  * stores installation packages, configuration files and so on; they are:
55  * <ul>
56  * <li>installationDirectory - the directory where the assets must be installed</li>
57  * <li>binDirectory - the directory where installation executables are stored</li>
58  * <li>libDirectory - the directory where libraries and classes are stored</li>
59  * <ul>
60  * If these directories are specified as absolute paths, they are used as they
61  * are, otherwise, they are prepended with the base dir returned by the
62  * device manager (calling DeviceManager.getBaseDir).
63  *
64  * @version $id$
65  * @author Stefano Nichele
66  */

67 public class AssetManager {
68
69     // ---------------------------------------------------------------Constants
70

71     /** Name of the DM node used for read the installationDirectory property */
72     private static final String JavaDoc PROPERTY_INSTALLATION_DIRECTORY = "installationDirectory";
73
74     /** Name of the DM node used for read the binDirectory property */
75     private static final String JavaDoc PROPERTY_BIN_DIRECTORY = "binDirectory";
76
77     /** Name of the DM node used for read the libDirectory property */
78     private static final String JavaDoc PROPERTY_LIB_DIRECTORY = "libDirectory";
79
80     /** Property that defines if the package size should be checked **/
81     private static final String JavaDoc PROPERTY_CHECK_PACKAGE_SIZE = "checkSize";
82
83     /** Directory in which to install asset */
84     private static final String JavaDoc ASSET_CONTENT_DIRECTORY = "assetContent";
85
86     /** Directory in which to save the content file */
87     private static final String JavaDoc ASSET_FILE_DIRECTORY = "assetFile";
88
89     /** Name of the DM node used for initialize the AssetManager */
90     private static final String JavaDoc CONFIG_CONTEXT_NODE = "spap/assetManager";
91
92
93     // -------------------------------------------------------------Properties
94

95     /**
96      * Directory in the which installs the assets
97      */

98     private String JavaDoc installationDirectory = null;
99
100     /**
101      * Sets property
102      * @param installationDirectory
103      * description: directory in the which installs the assets
104      * displayName: installationDirectory
105      */

106     public void setInstallationDirectory(String JavaDoc installationDirectory) {
107         this.installationDirectory = installationDirectory;
108     }
109
110     /**
111      * Returns property installationDirectory
112      */

113     public String JavaDoc getInstallationDirectory() {
114         return installationDirectory;
115     }
116
117     /**
118      * Directory for executables
119      */

120     private String JavaDoc binDirectory = null;
121
122     /**
123      * Sets property
124      * @param binDirectory
125      * description: directory for executables
126      * displayName: binDirectory
127      */

128     public void setBinDirectory(String JavaDoc binDirectory) {
129         this.binDirectory = binDirectory;
130     }
131
132     /**
133      * Returns property installationDirectory
134      */

135     public String JavaDoc getBinDirectory() {
136         return binDirectory;
137     }
138
139     /**
140      * Directory for classes and libraries
141      */

142     private String JavaDoc libDirectory = null;
143
144     /**
145      * Sets property
146      * @param libDirectory
147      * description: directory for classes and libraries
148      * displayName: libDirectory
149      */

150     public void setLibDirectory(String JavaDoc libDirectory) {
151         this.libDirectory = libDirectory;
152     }
153
154     /**
155      * Returns property installationDirectory
156      */

157     public String JavaDoc getLibDirectory() {
158         return libDirectory;
159     }
160
161     /**
162      * Should the package size be checked after downloading?
163      **/

164     private boolean checkPackageSize = false;
165
166     public void setCheckPackageSize(boolean checkPackageSize){
167         this.checkPackageSize = checkPackageSize;
168     }
169
170     public boolean isCheckPackageSize() {
171         return this.checkPackageSize;
172     }
173
174
175     // ------------------------------------------------------------Private data
176

177     /** instance for singleton pattern */
178     private static AssetManager instance = null;
179
180     /** AssetDAO used for get asset's information */
181     private AssetDAO assetDAO = null;
182
183     private Logger logger = new Logger();
184
185     // ------------------------------------------------------------ Constructor
186

187     /**
188      * Constructs a new AssetManager.
189      * Using DM for the initialization
190      *
191      * @throws IllegalStateException if an error occurs during the
192      * initialization process
193      */

194     private AssetManager() throws IllegalStateException JavaDoc {
195         DeviceManager dm = null;
196         ManagementNode managementNode = null;
197         dm = SimpleDeviceManager.getDeviceManager();
198         Hashtable JavaDoc values = null;
199
200         try {
201             values = dm.getManagementTree("").getNodeValues(CONFIG_CONTEXT_NODE);
202
203             installationDirectory = (String JavaDoc)values.get(PROPERTY_INSTALLATION_DIRECTORY);
204             binDirectory = (String JavaDoc)values.get(PROPERTY_BIN_DIRECTORY );
205             libDirectory = (String JavaDoc)values.get(PROPERTY_LIB_DIRECTORY );
206
207             //
208
// If the directories are relative paths, a base directory taken as
209
// described in the class description is prepended to them.
210
//
211
if (!new File JavaDoc(installationDirectory).isAbsolute()) {
212                 installationDirectory =
213                     new File JavaDoc(
214                         dm.getDevice().getBaseDirectory(),
215                         installationDirectory
216                     ).getAbsolutePath();
217             }
218             if (!new File JavaDoc(binDirectory).isAbsolute()) {
219                 binDirectory = new File JavaDoc(
220                                    dm.getDevice().getBaseDirectory(),
221                                    binDirectory
222                                ).getAbsolutePath();
223             }
224             if (!new File JavaDoc(libDirectory).isAbsolute()) {
225                 libDirectory = new File JavaDoc(
226                                    dm.getDevice().getBaseDirectory(),
227                                    libDirectory
228                                ).getAbsolutePath();
229             }
230             // ---
231

232             checkPackageSize = Boolean.getBoolean((String JavaDoc)values.get(PROPERTY_CHECK_PACKAGE_SIZE));
233         }
234         catch (Exception JavaDoc ex) {
235             throw new IllegalStateException JavaDoc(
236                     "Error in AssetManager config (" + ex.getMessage() + ")"
237                     );
238         }
239         assetDAO = new AssetDAO();
240     }
241
242     // ---------------------------------------------------------- Public Methods
243

244     /**
245      * Method used for obtain a instance of a <code>AssetManager</code>
246      *
247      * @return a instance of a <code>AssetManager</code>
248      * @throws IllegalStateException if an error occurs during the initialization
249      * process
250      */

251     public static AssetManager getAssetManager() throws IllegalStateException JavaDoc {
252         instance = new AssetManager();
253         return instance;
254     }
255
256
257
258     /**
259      * Starts the installation process of a asset.
260      * <p>This method is used for to install a new asset and for to update a
261      * asset.</p>
262      *
263      * <p>A asset requires a installation if his state is:
264      * <ui>
265      * <li>{@link sync4j.syncclient.spap.Asset#STATE_NEW
266      * STATE_NEW}</li>
267      * <li>{@link sync4j.syncclient.spap.Asset#STATE_UPDATE
268      * STATE_UPDATE}</li>
269      * <li>{@link sync4j.syncclient.spap.Asset#STATE_FILE_DOWNLOAD
270      * STATE_CONTENT_DOWNLOAD}</li>
271      * <li>{@link sync4j.syncclient.spap.Asset#STATE_FILE_EXTRACTED
272      * STATE_CONTENT_EXTRACTED}</li>
273      * <li>{@link sync4j.syncclient.spap.Asset#STATE_PREVIOUS_VERSION_UNINSTALLED
274      * STATE_PREVIOUS_VERSION_UNINSTALLED}</li>
275      * </ui>
276      * </p>
277      * <p>The installation process is composed by the following task:</p>
278      * <ui>
279      * <li>uninstallation, if required, of the previous version</li>
280      * <li>download the content file for the version to install</li>
281      * <li>extract the content file</li>
282      * <li>launch the installation program</li>
283      * <li>save the dm information</li>
284      * </ui>
285      *
286      * @param idAsset identifier of the asset to install
287      * @throws AssetManagementException if not exists a <i>newVersion</i> or if an error
288      * occurs during installation processs
289      */

290     public void installAsset(String JavaDoc idAsset) throws AssetManagementException {
291
292         if (logger.isLoggable(Logger.DEBUG)) {
293             logger.debug("InstallAsset: " + idAsset);
294         }
295
296         Asset asset = assetDAO.getAsset(idAsset);
297
298         if (logger.isLoggable(Logger.DEBUG)) {
299             logger.debug("Asset's state: " + asset.getState());
300         }
301
302         AssetVersion assetNewVersion = asset.getNewVersion();
303
304         if (assetNewVersion == null) {
305             throw new AssetManagementException(asset, "New version not found");
306         }
307
308         String JavaDoc name = asset.getName().toLowerCase();
309         String JavaDoc manufacturer = asset.getManufacturer().toLowerCase();
310         String JavaDoc state = asset.getState();
311
312         String JavaDoc workingDirectory = this.installationDirectory + "/" + manufacturer + "/" + name;
313
314         AssetVersion assetCurrentVersion = asset.getCurrentVersion();
315
316         byte[] content = null;
317
318         boolean stateRecognized = false;
319
320         if (state.equals(Asset.STATE_UPDATE)) {
321             stateRecognized = true;
322
323             // verify if musts uninstall previous version
324
try {
325                 verifyAndUninstallPreviousVersion(asset);
326             }
327             catch (Exception JavaDoc ex) {
328                 throw new AssetManagementException(asset, "Error during uninstall previous version" , ex);
329             }
330             state = Asset.STATE_PREVIOUS_VERSION_UNINSTALLED;
331             assetDAO.setAssetState(asset, state);
332         }
333
334         if (state.equals(Asset.STATE_NEW) ||
335             state.equals(Asset.STATE_PREVIOUS_VERSION_UNINSTALLED)) {
336
337             stateRecognized = true;
338
339             // download zip file for new version
340
try {
341                 content = downloadContentFileForNewVersion(asset);
342             }
343             catch (IOException JavaDoc ex) {
344                 throw new AssetManagementException(asset, "Error downloading asset file '" +
345                         assetNewVersion.getUrl() + "'", ex);
346             }
347
348             String JavaDoc logMsg = "Size content file: " +
349                             assetNewVersion.getSizeContentFile() +
350                             ", size downloaded file: " +
351                             content.length ;
352
353             if (logger.isLoggable(Logger.DEBUG)) {
354                 logger.debug(logMsg);
355             }
356
357             // verify the dimension of the asset's file
358
if (checkPackageSize &&
359                 (content.length != assetNewVersion.getSizeContentFile())) {
360
361                 if (logger.isLoggable(Logger.DEBUG)) {
362                     logger.debug("Error! Wrong size");
363                 }
364
365                 throw new AssetManagementException(asset,
366                         "Error downloading content file. Wrong size ("
367                         + content.length + ")");
368
369
370             }
371
372             if (logger.isLoggable(Logger.DEBUG)) {
373                 logger.debug("Dimension is correct (or ignored)");
374             }
375
376             // verify the content
377
try {
378                 ZipTools.verifyZip(content);
379                 if (logger.isLoggable(Logger.DEBUG)) {
380                     logger.debug("Zip file is valid");
381                 }
382             }
383             catch (IOException JavaDoc ex) {
384                 // content is not a valid zip file
385
if (logger.isLoggable(Logger.DEBUG)) {
386                     logger.debug("Zip file is not valid");
387                 }
388
389                 throw new AssetManagementException(asset, "Zip file '" +
390                         assetNewVersion.getUrl().toString() +
391                         "' downloaded but not appared be a valid file", ex);
392             }
393
394             // save content file
395
try {
396                 if (logger.isLoggable(Logger.DEBUG)) {
397                     logger.debug("Save the content file");
398                 }
399                 FileSystemTools.createFile(workingDirectory +
400                         File.separator + ASSET_FILE_DIRECTORY,
401                         asset.getName() + "_" + assetNewVersion.getVersion() + ".zip", content);
402
403             }
404             catch (Exception JavaDoc ex) {
405
406                 throw new AssetManagementException(asset,
407                         "Zip file '" + assetNewVersion.getUrl() +
408                         "' verified but fault saving process", ex);
409             }
410
411             state = Asset.STATE_FILE_DOWNLOAD;
412             assetDAO.setAssetState(asset, state);
413
414         }
415
416         if (state.equals(Asset.STATE_FILE_DOWNLOAD)) {
417             stateRecognized = true;
418             if (content == null) {
419                 try {
420                     if (logger.isLoggable(Logger.DEBUG)) {
421                         logger.debug("Load the content file from local system");
422                     }
423                     content = getAssetPackage(asset);
424                 }
425                 catch (Exception JavaDoc ex) {
426                     throw new AssetManagementException(asset,
427                             "Error loading content file '" +
428                             asset.getName() + "_" + assetNewVersion.getVersion() + ".zip" +
429                             "' from local system", ex);
430                 }
431
432             }
433
434
435             // delete asset_content_directory before to extract the new version
436
String JavaDoc msgLog = "Delete directory '" +
437                                  workingDirectory +
438                                  File.separator +
439                                  ASSET_CONTENT_DIRECTORY +
440                                  "'" ;
441
442             if (logger.isLoggable(Logger.DEBUG)) {
443                 logger.debug(msgLog);
444             }
445
446             try {
447               FileSystemTools.removeDirectoryTree(workingDirectory + File.separator +
448                                    ASSET_CONTENT_DIRECTORY);
449             }
450             catch (Exception JavaDoc ex) {
451               throw new AssetManagementException(asset,
452                       "Error during the cancellation of the directory '" +
453                       workingDirectory + File.separator +
454                       ASSET_CONTENT_DIRECTORY + "'", ex);
455             }
456
457
458             // extract new version
459
msgLog = "Extract new version in '" +
460                       workingDirectory +
461                       File.separator +
462                       ASSET_CONTENT_DIRECTORY +
463                       "'" ;
464             if (logger.isLoggable(Logger.DEBUG)) {
465                 logger.debug(msgLog);
466             }
467
468             try {
469                 ZipTools.extract(workingDirectory + File.separator +
470                                  ASSET_CONTENT_DIRECTORY, content);
471             }
472             catch (Exception JavaDoc ex) {
473
474                 throw new AssetManagementException(asset,
475                         "Error during the extraction of the zip file '" +
476                         assetNewVersion.getUrl() + "'", ex);
477
478             }
479
480
481             // after extraction, delete the zip file
482
new File JavaDoc(workingDirectory +
483                      File.separator + ASSET_FILE_DIRECTORY,
484                      asset.getName() + "_" + assetNewVersion.getVersion() + ".zip").delete();
485
486
487             state = Asset.STATE_FILE_EXTRACTED;
488             assetDAO.setAssetState(asset, state);
489         }
490
491
492         if (state.equals(Asset.STATE_FILE_EXTRACTED)) {
493             stateRecognized = true;
494
495             // launch the installation program of the new version
496
String JavaDoc installProgram = assetNewVersion.getInstallProgram();
497             if (installProgram != null && !installProgram.equalsIgnoreCase("")) {
498
499                 if (logger.isLoggable(Logger.DEBUG)) {
500                     logger.debug("Launch the installation program (" + installProgram + ")");
501                 }
502                 int exitState = -1;
503
504                 try {
505                     Launcher launcher = LauncherFactory.getLauncher(installProgram);
506
507                     InstallationContext ctx = new InstallationContext();
508                     ctx.setWorkingDirectory(
509                         workingDirectory +
510                         File.separator +
511                         ASSET_CONTENT_DIRECTORY
512                     );
513                     ctx.setBinDirectory(binDirectory);
514                     ctx.setLibDirectory(libDirectory);
515                     ctx.setAsset(asset);
516
517                     exitState = launcher.execute(installProgram, true, ctx);
518
519                 } catch (AssetInstallationException e) {
520                     throw e;
521                 } catch (AssetManagementException e) {
522                     assetDAO.setAssetAsNotValid(asset, e);
523                     throw e;
524                 } catch (Throwable JavaDoc t) {
525                     assetDAO.setAssetAsNotValid(asset, t);
526
527                     throw new AssetManagementException(asset,
528                             "Error during the execution of the installation program", t);
529                 }
530
531                 if (exitState != 0) {
532                     throw new AssetManagementException("Installation program exit with state: " +exitState);
533                 }
534
535             }
536
537             if (logger.isLoggable(Logger.DEBUG)) {
538                 logger.debug("Save dm information");
539             }
540
541             AssetVersion newVersion = asset.getNewVersion();
542
543             // set the currentVersion with the newVersion
544
asset.setCurrentVersion(newVersion);
545             newVersion = null;
546             asset.setNewVersion(newVersion);
547
548             asset.setState(Asset.STATE_ASSET_INSTALLED);
549             assetDAO.setAsset(asset, asset.getLastUpdate() );
550         }
551
552
553         if (!stateRecognized) {
554
555             throw new AssetManagementException(asset,
556                                      "Asset not required installation process. State is: '"
557                                      + state + "'");
558         }
559
560         if (logger.isLoggable(Logger.DEBUG)) {
561             logger.debug("Installation process finished");
562         }
563     }
564
565
566     /**
567      * Remove a asset.
568      * <p>The state of the asset must be
569      * {@link sync4j.syncclient.spap.Asset#STATE_DELETE STATE_DELETE}
570      *
571      * <p>The remove process is composed by the following task:</p>
572      * <ui>
573      * <li>launch the uninstallation program</li>
574      * <li>delete content directory</li>
575      * <li>delete DM information</li>
576      * </ui>
577      *
578      * @param idAsset identifier of the asset to remove
579      * @throws AssetManagementException if an error occurs or if asset not exists
580      */

581     public void removeAsset(String JavaDoc idAsset) throws AssetManagementException {
582
583         if (logger.isLoggable(Logger.DEBUG)) {
584             logger.debug("removeAsset: " + idAsset);
585         }
586
587         Asset asset = assetDAO.getAsset(idAsset);
588         AssetVersion currentVersion = null;
589
590         String JavaDoc state = asset.getState();
591         currentVersion = asset.getCurrentVersion();
592
593         if (!state.equals(Asset.STATE_DELETE)) {
594             throw new AssetManagementException(asset, "Asset cannot be deleted, state is not '" +
595                                      Asset.STATE_DELETE + "'");
596         }
597         String JavaDoc name = asset.getName().toLowerCase();
598         String JavaDoc manufacturer = asset.getManufacturer().toLowerCase();
599
600         String JavaDoc workingDirectory = this.installationDirectory + "/" + manufacturer + "/" + name;
601
602         if (currentVersion != null) {
603             // launch the uninstall program
604
String JavaDoc uninstallProgram = currentVersion.getUninstallProgram();
605             if (uninstallProgram != null && !uninstallProgram.equalsIgnoreCase("")) {
606
607                 if (logger.isLoggable(Logger.DEBUG)) {
608                     logger.debug("Launch the uninstall program (" + uninstallProgram + ")");
609                 }
610
611                 try {
612                     Launcher launcher = LauncherFactory.getLauncher(uninstallProgram);
613
614                     InstallationContext ctx = new InstallationContext();
615                     ctx.setWorkingDirectory(
616                         workingDirectory +
617                         File.separator +
618                         ASSET_CONTENT_DIRECTORY
619                     );
620                     ctx.setBinDirectory(binDirectory);
621                     ctx.setLibDirectory(libDirectory);
622                     ctx.setAsset(asset);
623
624                     launcher.execute(uninstallProgram, false, ctx);
625                 }
626                 catch (Exception JavaDoc ex) {
627                     throw new AssetManagementException(asset, "Error during uninstall process", ex);
628                 }
629             } else {
630                 if (logger.isLoggable(Logger.DEBUG)) {
631                     logger.debug("Uninstall program is null or empty");
632                 }
633             }
634         } else {
635             if (logger.isLoggable(Logger.DEBUG)) {
636                 logger.debug("Current version not found");
637             }
638         }
639
640
641         // remove asset's information from DM
642
assetDAO.removeAsset(asset);
643
644
645         // remove asset's directory
646
if (logger.isLoggable(Logger.DEBUG)) {
647             logger.debug("Remove the asset directory (" + workingDirectory + ")");
648         }
649
650         try {
651             FileSystemTools.removeDirectoryTree(workingDirectory);
652         }
653         catch (Exception JavaDoc ex) {
654             // ignore this error because the asset is already removed
655
}
656
657         // if manufacturer's directory is empty will must removed
658
File JavaDoc file = new File JavaDoc(this.installationDirectory + "/" + manufacturer);
659         file.delete();
660
661         if (logger.isLoggable(Logger.DEBUG)) {
662             logger.debug("Asset removed");
663         }
664
665     }
666
667
668     /**
669      * Return list of asset that require the installation process
670      *
671      * <p>A asset requires a installation if his state is:
672      * <ui>
673      * <li>{@link sync4j.syncclient.spap.Asset#STATE_NEW
674      * STATE_NEW}</li>
675      * <li>{@link sync4j.syncclient.spap.Asset#STATE_UPDATE
676      * STATE_UPDATE}</li>
677      * <li>{@link sync4j.syncclient.spap.Asset#STATE_FILE_DOWNLOAD
678      * STATE_FILE_DOWNLOAD}</li>
679      * <li>{@link sync4j.syncclient.spap.Asset#STATE_FILE_EXTRACTED
680      * STATE_FILE_EXTRACTED}</li>
681      * <li>{@link sync4j.syncclient.spap.Asset#STATE_PREVIOUS_VERSION_UNINSTALLED
682      * STATE_PREVIOUS_VERSION_UNINSTALLED}</li>
683      * </ui>
684      *
685      * @return list of asset that require the installation process
686      */

687     public Vector JavaDoc listAssetsForInstallation() {
688
689         String JavaDoc[] states = {
690             Asset.STATE_NEW,
691             Asset.STATE_UPDATE,
692             Asset.STATE_FILE_DOWNLOAD,
693             Asset.STATE_FILE_EXTRACTED,
694             Asset.STATE_PREVIOUS_VERSION_UNINSTALLED,
695         };
696
697         return listAssets(states);
698     }
699
700     /**
701      * Return list of asset that require the uninstallation process
702      *
703      * <p>A asset requires a uninstallation if its state is:
704      * <ui>
705      * <li>{@link sync4j.syncclient.spap.Asset#STATE_DELETE
706      * STATE_DELETE}</li>
707      *
708      * @return list of asset that require the uninstallation process
709      */

710     public Vector JavaDoc listAssetsForRemoving() {
711         return listAssets(Asset.STATE_DELETE);
712     }
713
714     /**
715      * Returns the list of the asset with the given states
716      *
717      * @param states array of the state
718      * @return list of the asset with the given states
719      */

720     public Vector JavaDoc listAssets(String JavaDoc[] states) {
721         Vector JavaDoc assetsList = new Vector JavaDoc();
722         Vector JavaDoc temp = null;
723         if (states==null || states.length==0) {
724             assetsList = assetDAO.getAllAsset();
725         } else {
726             int numState = states.length;
727             for (int i=0; i<numState; i++) {
728                 temp = listAssets(states[i]);
729                 VectorTools.add(assetsList,temp);
730             }
731         }
732         return assetsList;
733     }
734
735
736     /**
737      * Returns the list of the asset with the given state.
738      * <p>If the given state is <code>null</code> returns the all assets
739      *
740      * @param state array of the state. If <code>null</code> returns the all assets
741      * @return list of the asset with the given states
742      */

743     public Vector JavaDoc listAssets(String JavaDoc state) {
744         Vector JavaDoc assetsList = null;
745         if (state==null || state.equals("")) {
746             assetsList = assetDAO.getAllAsset();
747         } else {
748             assetsList = assetDAO.listAsset(state);
749         }
750
751         return assetsList;
752     }
753
754
755     /**
756      * Returns the state of the asset identified from the given id
757      * @param idAsset identifier of the asset
758      *
759      * @return the state of the asset
760      * @throws AssetManagementException if asset not exists
761      */

762     public String JavaDoc getAssetState(String JavaDoc idAsset) throws AssetManagementException {
763         return assetDAO.getAssetState(idAsset);
764     }
765
766     /**
767      * Set the state of the given asset.
768      *
769      * @param asset the asset to be set
770      * @param state the new state
771      *
772      * @throws AssetManagementException in case of errors
773      */

774     public void setAssetState(Asset asset, String JavaDoc state)
775     throws AssetManagementException {
776         assetDAO.setAssetState(asset, state);
777     }
778
779
780     /**
781      * Returns the asset with the given identifier
782      *
783      * @param idAsset the identifier of the asset
784      * @return the Asset with the given identifier
785      * @throws AssetManagementException if Asset not exist
786      */

787     public Asset getAsset(String JavaDoc idAsset) throws AssetManagementException {
788         return assetDAO.getAsset(idAsset);
789     }
790
791     /**
792      * Sets asset's state to <i>Asset.STATE_NEW_VERSION_NOT_WISHED</i>
793      *
794      * @param idAsset identifier of the asset
795      * @throws AssetManagementException if an error occurs
796      */

797     public void setAssetAsNotWanted(String JavaDoc idAsset) throws AssetManagementException {
798         Asset asset = assetDAO.getAsset(idAsset);
799         String JavaDoc state = asset.getState();
800
801         if (!state.equals(Asset.STATE_NEW) &&
802             !state.equals(Asset.STATE_UPDATE) &&
803             !state.equals(Asset.STATE_FILE_DOWNLOAD) &&
804             !state.equals(Asset.STATE_FILE_EXTRACTED) &&
805             !state.equals(Asset.STATE_PREVIOUS_VERSION_UNINSTALLED)) {
806
807             throw new AssetManagementException(asset, "Impossible setting like NOT WISHED" +
808                                      " (state: " + state + ")");
809         }
810
811
812         assetDAO.setAssetState(idAsset, Asset.STATE_NEW_VERSION_NOT_WANTED);
813     }
814
815
816     /**
817      * Adds the given asset.
818      *
819      * @param asset the asset to add
820      *
821      * @throws AssetManagementException in case of errors
822      */

823     public void addAsset(Asset asset) throws AssetManagementException {
824         assetDAO.setAsset(asset, new Timestamp JavaDoc(System.currentTimeMillis()));
825     }
826
827     // --------------------------------------------------------- Private Methods
828

829     /**
830      * Verification if it is necessary launch the uninstall program of the
831      * previous version.
832      * <p>It's necessary launch the uninstallation program if:
833      * <ui>
834      * <li>the current version exists</li>
835      * <li>the current version has a uninstall program</li>
836      * <li>the new version has <i>needUninstallPrev</i>='Y'</li>
837      *
838      * @param asset
839      *
840      * @throws Exception if an error occurs
841      */

842     private void verifyAndUninstallPreviousVersion(Asset asset)
843             throws AssetInstallationException {
844
845
846         String JavaDoc name = asset.getName().toLowerCase();
847         String JavaDoc manufacturer = asset.getManufacturer().toLowerCase();
848
849         String JavaDoc workingDirectory = this.installationDirectory + "/" + manufacturer + "/" + name;
850
851         AssetVersion assetCurrentVersion = asset.getCurrentVersion();
852         AssetVersion assetNewVersion = asset.getNewVersion();
853
854         if (assetCurrentVersion != null) {
855             String JavaDoc uninstallProgram = assetCurrentVersion.getUninstallProgram();
856             if (uninstallProgram != null && !uninstallProgram.equals("")) {
857                 if (assetNewVersion.getNeedUninstallPrev().equalsIgnoreCase("Y")) {
858
859                     String JavaDoc msgLog = "Uninstall previous version (Uninstall program: " +
860                                     uninstallProgram +
861                                     ")" ;
862
863                     if (logger.isLoggable(Logger.DEBUG)) {
864                         logger.debug(msgLog);
865                     }
866
867                     // devo lanciare il programma di disinstallazione
868

869                     Launcher launcher = LauncherFactory.getLauncher(uninstallProgram);
870
871                     InstallationContext ctx = new InstallationContext();
872                     ctx.setWorkingDirectory(
873                         workingDirectory +
874                         File.separator +
875                         ASSET_CONTENT_DIRECTORY
876                     );
877                     ctx.setBinDirectory(binDirectory);
878                     ctx.setLibDirectory(libDirectory);
879                     ctx.setAsset(asset);
880
881                     int exitState = launcher.execute(uninstallProgram, false, ctx);
882                     if (exitState != 0) {
883                         throw new AssetInstallationException("Uninstallation program exit with state: " +exitState);
884                     }
885                 }
886             }
887         }
888     }
889
890
891     /**
892      * Download content file for the new version of the given Asset.
893      *
894      * <p>The file is downloaded from the url:<br>
895      * <i>http://hostServer:portServer/baseUrl/&#60;manufacturer&#62;/
896      * &#60;name&#62;/&#60;version&#62;/&#60;contentFile&#62;</i>
897      *
898      * @param asset asset of the which download the content file
899      * @return the byte array downloaded
900      * @throws IOException if an error occurs
901      */

902     private byte[] downloadContentFileForNewVersion(Asset asset) throws IOException JavaDoc {
903         byte[] content = null;
904         AssetVersion newVersion = asset.getNewVersion();
905
906         String JavaDoc name = asset.getName();
907         String JavaDoc manufacturer = asset.getManufacturer();
908
909         String JavaDoc version = newVersion.getVersion();
910         String JavaDoc assetUrl = newVersion.getUrl();
911
912         if (logger.isLoggable(Logger.DEBUG)) {
913             logger.debug("Download asset file: " + assetUrl.toString());
914         }
915
916         if (HttpTools.isHTTPURL(assetUrl)) {
917             content = HttpTools.downloadPackage(assetUrl);
918         } else {
919             if (assetUrl.startsWith("file:/")) {
920                 try {
921                     assetUrl = new URL JavaDoc(assetUrl).getFile();
922                 } catch (MalformedURLException JavaDoc e) {
923                     // we ignore it so that we treat it as a normal file
924
}
925             }
926             content = FileSystemTools.getFile(assetUrl);
927         }
928
929         return content;
930     }
931
932     /**
933      * Read the content file prevoiusly saved for the given asset
934      *
935      * @param asset
936      * @return the byte array of the content file of the asset
937      * @throws Exception if an error occurs
938      */

939     private byte[] getAssetPackage(Asset asset) throws Exception JavaDoc {
940
941         AssetVersion assetNewVersion = asset.getNewVersion();
942
943         if (assetNewVersion == null) {
944             throw new AssetManagementException(asset, "New version not found");
945         }
946
947         String JavaDoc name = asset.getName().toLowerCase();
948         String JavaDoc manufacturer = asset.getManufacturer().toLowerCase();
949
950         String JavaDoc workingDirectory = this.installationDirectory + File.separator +
951                                   manufacturer + File.separator + name +
952                                   File.separator + ASSET_FILE_DIRECTORY;
953
954
955         String JavaDoc contentFile = workingDirectory + File.separator +
956                              asset.getName() + "_" + assetNewVersion.getVersion() + ".zip";
957
958         return FileSystemTools.getFile(contentFile);
959
960     }
961
962
963 }
Popular Tags