KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > updater > UpdateTracking


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.updater;
21
22 import java.io.BufferedInputStream JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileFilter JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.OutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.PrintWriter JavaDoc;
31 import java.util.*;
32 import java.util.zip.CRC32 JavaDoc;
33 import org.w3c.dom.*;
34 import org.xml.sax.InputSource JavaDoc;
35
36 /** This class represents module updates tracking
37  *
38  * @author Ales Kemr
39  */

40 public final class UpdateTracking {
41     private static final String JavaDoc ELEMENT_MODULES = "installed_modules"; // NOI18N
42
private static final String JavaDoc ELEMENT_MODULE = "module"; // NOI18N
43
private static final String JavaDoc ATTR_CODENAMEBASE = "codename"; // NOI18N
44
private static final String JavaDoc ELEMENT_VERSION = "module_version"; // NOI18N
45
private static final String JavaDoc ATTR_VERSION = "specification_version"; // NOI18N
46
private static final String JavaDoc ATTR_ORIGIN = "origin"; // NOI18N
47
private static final String JavaDoc ATTR_LAST = "last"; // NOI18N
48
private static final String JavaDoc ATTR_INSTALL = "install_time"; // NOI18N
49
private static final String JavaDoc ELEMENT_FILE = "file"; // NOI18N
50
private static final String JavaDoc ATTR_FILE_NAME = "name"; // NOI18N
51
private static final String JavaDoc ATTR_CRC = "crc"; // NOI18N
52

53     private static final String JavaDoc NBM_ORIGIN = "nbm"; // NOI18N
54
// XXX: used also in org.netbeans.modules.autoupate.ModuleDeleterImpl
55
private static final String JavaDoc INST_ORIGIN = "updater"; // NOI18N
56

57     /** Platform dependent file name separator */
58     private static final String JavaDoc FILE_SEPARATOR = System.getProperty ("file.separator");
59     private static final String JavaDoc LOCALE_DIR = FILE_SEPARATOR + "locale" + FILE_SEPARATOR; // NOI18N
60

61     /** The name of the install_later file */
62     public static final String JavaDoc TRACKING_FILE_NAME = "update_tracking"; // NOI18N
63
private static final String JavaDoc XML_EXT = ".xml"; // NOI18N
64

65     /** maps root of clusters to tracking files. (File -> UpdateTracking) */
66     private static final Map trackings = new HashMap ();
67     
68     /** Mapping from files defining modules to appropriate modules objects.
69      * (File, Module)
70      */

71     private LinkedHashMap installedModules = new LinkedHashMap ();
72
73     private boolean pError = false;
74     private boolean fromUser = false;
75     private final File JavaDoc directory;
76     private final File JavaDoc trackingFile;
77     private String JavaDoc origin = NBM_ORIGIN;
78
79     
80     public UpdateTracking () {
81         // XXX should be deleted I think
82
this (null);
83     }
84
85     /** Private constructor.
86      */

87     private UpdateTracking( File JavaDoc nbPath ) {
88         assert nbPath != null : "Path cannot be null";
89         
90         trackingFile = new File JavaDoc( nbPath + FILE_SEPARATOR + TRACKING_FILE_NAME);
91         directory = nbPath;
92         origin = INST_ORIGIN;
93     }
94     
95     
96     //
97
// Various factory and utility methods
98
//
99

100     /** Loads update tracking for given location
101      * @param fromuser use netbeans.user or netbeans.home
102      * @return the tracking
103      */

104     static UpdateTracking getTracking( boolean fromuser ) {
105         UpdateTracking ut = getTracking (
106             System.getProperty (fromuser ? "netbeans.user" : "netbeans.home"), // NOI18N
107
fromuser
108         );
109         return ut;
110     }
111
112     /** Loads update tracking for given location
113      * @param cluster the name of the cluster that we want to install to
114      * @param createIfDoesNotExists should new tracking be created if it does not exists
115      * @return the tracking
116      */

117     private static UpdateTracking getTracking(String JavaDoc cluster, boolean createIfDoesNotExists) {
118         File JavaDoc f = new File JavaDoc (cluster);
119         
120         UpdateTracking ut = getTracking (f, createIfDoesNotExists);
121         return ut;
122     }
123     
124     /** Finds update tracking for given cluster root. Automatically creates
125      * the cluster if this is user dir.
126      *
127      * @path root of a cluster
128      * @return the tracking for that cluster
129      */

130     public static UpdateTracking getTracking (File JavaDoc path) {
131         // bugfix #54046: the cluster for install must be normalized
132
path = new File JavaDoc(path.toURI ().normalize ()).getAbsoluteFile ();
133         
134         // bugfix #50242: the property "netbeans.user" can return dir with non-normalized file e.g. duplicate //
135
// and path and value of this property wrongly differs
136
File JavaDoc userDir = new File JavaDoc (System.getProperty ("netbeans.user"));
137         userDir = new File JavaDoc(userDir.toURI ().normalize ()).getAbsoluteFile ();
138
139         return getTracking (path, path.toString().equals (userDir.getPath ()));
140     }
141     
142     /** Finds update tracking for given cluster root.
143      * @path root of a cluster
144      * @param createIfDoesNotExists should new tracking be created if it does not exists
145      * @return the tracking for that cluster
146      */

147     public static UpdateTracking getTracking (File JavaDoc path, boolean createIfDoesNotExists) {
148         try {
149             path = path.getCanonicalFile ();
150         } catch (java.io.IOException JavaDoc ex) {
151             IllegalStateException JavaDoc ill = new IllegalStateException JavaDoc (ex.getMessage ());
152             ill.initCause (ex);
153             throw ill;
154         }
155      
156         synchronized (trackings) {
157             UpdateTracking track = (UpdateTracking)trackings.get (path);
158             if (track == null) {
159                 File JavaDoc utFile = new File JavaDoc (path, TRACKING_FILE_NAME);
160                 if (!createIfDoesNotExists && !utFile.isDirectory ()) {
161                     // if the update_tracking directory is missing
162
// do not allow creation at all (only in userdir)
163
return null;
164                 }
165                 File JavaDoc noAU = new File JavaDoc(path, ".noautoupdate"); // NOI18N
166
if (noAU.exists()) {
167                     // ok, this prevents autoupdate from accessing this
168
// directory completely
169
return null;
170                 }
171                 
172                 
173                 track = new UpdateTracking (path);
174                 trackings.put (path, track);
175                 track.read ();
176                 track.scanDir ();
177             }
178             return track;
179         }
180     }
181     
182
183     /** Returns the platform installatiion directory.
184      * @return the File directory.
185      */

186     public static File JavaDoc getPlatformDir () {
187         return new File JavaDoc (System.getProperty ("netbeans.home")); // NOI18N
188
}
189     
190     /** Returns enumeration of Files that represent each possible install
191      * directory.
192      * @param includeUserDir whether to include also user dir
193      * @return List<File>
194      */

195     public static List clusters (boolean includeUserDir) {
196         ArrayList files = new ArrayList ();
197         
198         if (includeUserDir) {
199             File JavaDoc ud = new File JavaDoc (System.getProperty ("netbeans.user")); // NOI18N
200
files.add (ud);
201         }
202         
203         
204         String JavaDoc dirs = System.getProperty("netbeans.dirs"); // NOI18N
205
if (dirs != null) {
206             Enumeration en = new StringTokenizer (dirs, File.pathSeparator);
207             while (en.hasMoreElements ()) {
208                 File JavaDoc f = new File JavaDoc ((String JavaDoc)en.nextElement ());
209                 files.add (f);
210             }
211         }
212         
213         
214         File JavaDoc id = getPlatformDir ();
215         files.add (id);
216         
217         return java.util.Collections.unmodifiableList (files);
218     }
219     
220     //
221
// Useful search methods
222
//
223

224     /** Returns true if module with given code base is installed here
225      * @param codeBase name of the module
226      * @return true or false
227      */

228     public boolean isModuleInstalled (String JavaDoc codeBase) {
229         Iterator it = installedModules.values ().iterator ();
230         while (it.hasNext ()) {
231             Module m = (Module)it.next ();
232             String JavaDoc mm = m.codenamebase;
233             int indx = mm.indexOf ('/');
234             if (indx >= 0) {
235                 mm = mm.substring (0, indx);
236             }
237             if (codeBase.equals (mm)) {
238                 return true;
239             }
240         }
241         return false;
242     }
243     
244     /** Compute the list of modules that should be installed into this
245      * cluster.
246      * @return List<File> of nbm files
247      */

248     public List getModulesToInstall () {
249         class NbmFilter implements java.io.FilenameFilter JavaDoc {
250             public boolean accept( File JavaDoc dir, String JavaDoc name ) {
251                 return name.endsWith (ModuleUpdater.NBM_EXTENSION);
252             }
253         }
254         
255         File JavaDoc idir = new File JavaDoc (directory, ModuleUpdater.DOWNLOAD_DIR);
256         File JavaDoc[] arr = idir.listFiles (new NbmFilter ());
257         if (arr == null) {
258             return Collections.EMPTY_LIST;
259         } else {
260             return Arrays.asList (arr);
261         }
262     }
263
264     
265     //
266
// Private impls
267
//
268

269     
270     /** Scan through org.w3c.dom.Document document. */
271     private void read() {
272         /** org.w3c.dom.Document document */
273         org.w3c.dom.Document JavaDoc document;
274
275         File JavaDoc file;
276         InputStream JavaDoc is;
277         try {
278             file = trackingFile;
279             
280             if ( ! file.isFile () )
281                 return;
282             
283             is = new FileInputStream JavaDoc( file );
284
285             InputSource JavaDoc xmlInputSource = new InputSource JavaDoc( is );
286             document = XMLUtil.parse( xmlInputSource, false, false, new ErrorCatcher(), XMLUtil.createAUResolver() );
287             if (is != null)
288                 is.close();
289         }
290         catch ( org.xml.sax.SAXException JavaDoc e ) {
291             System.out.println("Bad update_tracking" ); // NOI18N
292
e.printStackTrace ();
293             return;
294         }
295         catch ( java.io.IOException JavaDoc e ) {
296             System.out.println("Missing update_tracking" ); // NOI18N
297
e.printStackTrace ();
298             return;
299         }
300
301         org.w3c.dom.Element JavaDoc element = document.getDocumentElement();
302         if ((element != null) && element.getTagName().equals(ELEMENT_MODULES)) {
303             scanElement_installed_modules(element, fromUser);
304         }
305     }
306     
307     /** Scan through org.w3c.dom.Element named installed_modules. */
308     void scanElement_installed_modules(org.w3c.dom.Element JavaDoc element, boolean fromuser) { // <installed_modules>
309
// element.getValue();
310
org.w3c.dom.NodeList JavaDoc nodes = element.getChildNodes();
311         for (int i = 0; i < nodes.getLength(); i++) {
312             org.w3c.dom.Node JavaDoc node = nodes.item(i);
313             if ( node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE ) {
314                 org.w3c.dom.Element JavaDoc nodeElement = (org.w3c.dom.Element JavaDoc)node;
315                 if (nodeElement.getTagName().equals(ELEMENT_MODULE)) {
316                     if (true) throw new IllegalStateException JavaDoc ("What now!?");
317                     // XXX - should put the module into installedModules but do not know the key
318
// modules.add( scanElement_module(nodeElement, fromuser) );
319
}
320             }
321         }
322     }
323     
324     /** Scan through org.w3c.dom.Element named module. */
325     Module scanElement_module(org.w3c.dom.Element JavaDoc element, boolean fromuser) { // <module>
326
Module module = new Module( fromuser );
327         org.w3c.dom.NamedNodeMap JavaDoc attrs = element.getAttributes();
328         for (int i = 0; i < attrs.getLength(); i++) {
329             org.w3c.dom.Attr JavaDoc attr = (org.w3c.dom.Attr JavaDoc)attrs.item(i);
330             if (attr.getName().startsWith(ATTR_CODENAMEBASE)) {
331                 // <module codename="???"> or old version <module codenamebase="???">
332
module.setCodenamebase( attr.getValue() );
333             }
334         }
335         org.w3c.dom.NodeList JavaDoc nodes = element.getChildNodes();
336         for (int i = 0; i < nodes.getLength(); i++) {
337             org.w3c.dom.Node JavaDoc node = nodes.item(i);
338             if ( node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE ) {
339                 org.w3c.dom.Element JavaDoc nodeElement = (org.w3c.dom.Element JavaDoc)node;
340                 if (nodeElement.getTagName().equals(ELEMENT_VERSION)) {
341                     scanElement_module_version(nodeElement, module);
342                 }
343             }
344         }
345         return module;
346     }
347     
348     /** Scan through org.w3c.dom.Element named module_version. */
349     void scanElement_module_version(org.w3c.dom.Element JavaDoc element, Module module) { // <module_version>
350
Version version = new Version();
351         org.w3c.dom.NamedNodeMap JavaDoc attrs = element.getAttributes();
352         for (int i = 0; i < attrs.getLength(); i++) {
353             org.w3c.dom.Attr JavaDoc attr = (org.w3c.dom.Attr JavaDoc)attrs.item(i);
354             if (attr.getName().equals(ATTR_VERSION)) { // <module_version specification_version="???">
355
version.setVersion( attr.getValue() );
356             }
357             if (attr.getName().equals(ATTR_ORIGIN)) { // <module_version origin="???">
358
version.setOrigin( attr.getValue() );
359             }
360             if (attr.getName().equals(ATTR_LAST)) { // <module_version last="???">
361
version.setLast( Boolean.valueOf(attr.getValue() ).booleanValue());
362             }
363             if (attr.getName().equals(ATTR_INSTALL)) { // <module_version install_time="???">
364
long li = 0;
365                 try {
366                     li = Long.parseLong( attr.getValue() );
367                 } catch ( NumberFormatException JavaDoc nfe ) {
368                 }
369                 version.setInstall_time( li );
370             }
371         }
372         org.w3c.dom.NodeList JavaDoc nodes = element.getChildNodes();
373         for (int i = 0; i < nodes.getLength(); i++) {
374             org.w3c.dom.Node JavaDoc node = nodes.item(i);
375             if ( node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE ) {
376                 org.w3c.dom.Element JavaDoc nodeElement = (org.w3c.dom.Element JavaDoc)node;
377                 if (nodeElement.getTagName().equals(ELEMENT_FILE)) {
378                     scanElement_file(nodeElement, version);
379                 }
380             }
381         }
382         module.addOldVersion( version );
383     }
384     
385     /** Scan through org.w3c.dom.Element named file. */
386     void scanElement_file(org.w3c.dom.Element JavaDoc element, Version version) { // <file>
387
ModuleFile file = new ModuleFile();
388         org.w3c.dom.NamedNodeMap JavaDoc attrs = element.getAttributes();
389         for (int i = 0; i < attrs.getLength(); i++) {
390             org.w3c.dom.Attr JavaDoc attr = (org.w3c.dom.Attr JavaDoc)attrs.item(i);
391             if (attr.getName().equals(ATTR_FILE_NAME)) { // <file name="???">
392
file.setName( attr.getValue() );
393             }
394             if (attr.getName().equals(ATTR_CRC)) { // <file crc="???">
395
file.setCrc( attr.getValue() );
396             }
397             if (attr.getName().equals(ATTR_VERSION)) {
398                 file.setLocaleversion( attr.getValue() );
399             }
400         }
401         version.addFile (file );
402     }
403     
404     Module readModuleTracking( boolean fromuser, String JavaDoc codename, boolean create ) {
405         new File JavaDoc(directory, TRACKING_FILE_NAME).mkdirs();
406         File JavaDoc file = new File JavaDoc (
407             new File JavaDoc(directory, TRACKING_FILE_NAME),
408             getTrackingName( codename ) + XML_EXT
409         );
410         
411         // fix for #34355
412
try {
413             if ( file.exists() && file.length()==0 )
414                 file.delete();
415         } catch (Exception JavaDoc e) {
416             // ignore
417
}
418         
419         if ( ! file.exists() ) {
420             if ( create )
421                 return new Module( codename, file, fromuser );
422             else
423                 return null;
424         }
425
426         return readModuleFromFile( file, codename, fromuser, create );
427     }
428     
429     Version createVersion(String JavaDoc specversion) {
430         Version ver = new Version();
431         ver.setVersion( specversion );
432         return ver;
433     }
434     
435     private Module readModuleFromFile( File JavaDoc file, String JavaDoc codename, boolean fromuser, boolean create ) {
436         
437         /** org.w3c.dom.Document document */
438         org.w3c.dom.Document JavaDoc document;
439         InputStream JavaDoc is;
440         try {
441             is = new FileInputStream JavaDoc( file );
442
443             InputSource JavaDoc xmlInputSource = new InputSource JavaDoc( is );
444             document = XMLUtil.parse( xmlInputSource, false, false, new ErrorCatcher(), XMLUtil.createAUResolver() );
445             if (is != null)
446                 is.close();
447         } catch ( org.xml.sax.SAXException JavaDoc e ) {
448             System.out.println("Bad update_tracking" ); // NOI18N
449
e.printStackTrace ();
450             return null;
451         }
452         catch ( java.io.IOException JavaDoc e ) {
453             if ( create )
454                 return new Module( codename, file, fromuser );
455             else
456                 return null;
457         }
458
459         org.w3c.dom.Element JavaDoc element = document.getDocumentElement();
460         if ((element != null) && element.getTagName().equals(ELEMENT_MODULE)) {
461             
462             Module m = scanElement_module(element, fromuser);
463             m.setFile( file );
464             installedModules.put (file, m);
465             return m;
466         }
467         if ( create )
468             return new Module( codename, file, fromuser );
469         else
470             return null;
471     }
472     
473     private static String JavaDoc getTrackingName(String JavaDoc codename) {
474         String JavaDoc trackingName = codename;
475         int pos = trackingName.indexOf('/'); // NOI18N
476
if ( pos > -1 )
477             trackingName = trackingName.substring( 0, pos );
478         return trackingName.replace( '.', '-' ); // NOI18N
479
}
480     
481     public static void convertOldFormat(File JavaDoc oldfile, String JavaDoc path, boolean fromUserDir) {
482         new File JavaDoc( path + FILE_SEPARATOR + TRACKING_FILE_NAME ).mkdirs();
483         UpdateTracking track = getTracking( fromUserDir );
484         Iterator it = track.installedModules.values ().iterator();
485         while ( it.hasNext() ) {
486             Module mod = (Module)it.next();
487             File JavaDoc newfile = new File JavaDoc( path + FILE_SEPARATOR + TRACKING_FILE_NAME + FILE_SEPARATOR
488                     + getTrackingName( mod.getCodenamebase() ) + XML_EXT );
489             mod.setFile( newfile );
490             mod.write();
491         }
492         oldfile.delete();
493     }
494
495     public String JavaDoc getL10NSpecificationVersion(String JavaDoc codenamebase, boolean fromUserDir, String JavaDoc jarpath) {
496         Module module = readModuleTracking( fromUserDir, codenamebase, false );
497         if ( module == null )
498             return null;
499         
500         return module.getL10NSpecificationVersion( jarpath );
501     }
502     
503     void deleteUnusedFiles() {
504         List newModules = new ArrayList (installedModules.values ());
505         Iterator it = newModules.iterator();
506         while ( it.hasNext() ) {
507             Module mod = (Module)it.next();
508             mod.deleteUnusedFiles();
509         }
510         scanDir ();
511     }
512     
513     public static long getFileCRC(File JavaDoc file) throws IOException JavaDoc {
514         BufferedInputStream JavaDoc bsrc = null;
515         CRC32 JavaDoc crc = new CRC32 JavaDoc();
516         try {
517             bsrc = new BufferedInputStream JavaDoc( new FileInputStream JavaDoc( file ) );
518             byte[] bytes = new byte[1024];
519             int i;
520             while( (i = bsrc.read()) != -1 ) {
521                 crc.update( (byte)i );
522             }
523         }
524         finally {
525             if ( bsrc != null )
526                 bsrc.close();
527         }
528         return crc.getValue();
529     }
530     
531     private void scanDir () {
532         File JavaDoc dir = new File JavaDoc (directory, TRACKING_FILE_NAME);
533         File JavaDoc[] files = dir.listFiles( new FileFilter JavaDoc() {
534                                public boolean accept( File JavaDoc file ) {
535                                    if ( !file.isDirectory() && file.getName().toUpperCase().endsWith(".XML") ) // NOI18N
536
return true;
537                                    else
538                                        return false;
539                                }
540                            } );
541                            
542         if (files == null) {
543             return;
544         }
545                            
546         for ( int i = 0; i < files.length; i++ ) {
547             if (!installedModules.containsKey (files[i])) {
548                 readModuleFromFile( files[i], null, fromUser, true );
549             }
550                 
551         }
552     }
553     
554     class Module extends Object JavaDoc {
555         
556         /** Holds value of property codenamebase. */
557         private String JavaDoc codenamebase;
558         
559         /** Holds value of property versions. */
560         private List versions = new ArrayList();
561         
562         private File JavaDoc file = null;
563         
564         private boolean fromUser = true;
565         
566         public Module() {
567         }
568         
569         public Module(boolean fromUser) {
570             this.fromUser = fromUser;
571         }
572         
573         public Module(String JavaDoc codenamebase, File JavaDoc file, boolean fromUser) {
574             this.codenamebase = codenamebase;
575             this.file = file;
576             this.fromUser = fromUser;
577         }
578         
579         private Version lastVersion = null;
580         private Version newVersion = null;
581         
582         /** Getter for property codenamebase.
583          * @return Value of property codenamebase.
584          */

585         String JavaDoc getCodenamebase() {
586             return codenamebase;
587         }
588         
589         /** Setter for property codenamebase.
590          * @param codenamebase New value of property codenamebase.
591          */

592         void setCodenamebase(String JavaDoc codenamebase) {
593             this.codenamebase = codenamebase;
594         }
595         
596         /** Getter for property versions.
597          * @return Value of property versions.
598          */

599         List getVersions() {
600             return versions;
601         }
602         
603         /** Setter for property versions.
604          * @param versions New value of property versions.
605          */

606         void setVersions(List versions) {
607             this.versions = versions;
608         }
609         
610         boolean isFromUser() {
611             return fromUser;
612         }
613         
614         void setFromUser(boolean fromUser) {
615             this.fromUser = fromUser;
616         }
617         
618         private Version getNewOrLastVersion() {
619             if ( newVersion != null )
620                 return newVersion;
621             else
622                 return lastVersion;
623         }
624         
625         boolean hasNewVersion() {
626             return newVersion != null;
627         }
628         
629         void setFile(File JavaDoc file) {
630             this.file = file;
631         }
632         
633         public Version addNewVersion( String JavaDoc spec_version ) {
634             if ( lastVersion != null )
635                 lastVersion.setLast ( false );
636             Version version = new Version();
637             newVersion = version;
638             version.setVersion( spec_version );
639             version.setOrigin( origin );
640             version.setLast( true );
641             version.setInstall_time( System.currentTimeMillis() );
642             versions.add( version );
643             return version;
644         }
645         
646         void addOldVersion( Version version ) {
647             if ( version.isLast() )
648                 lastVersion = version;
649                     
650             versions.add( version );
651         }
652         
653         void addL10NVersion( Version l_version ) {
654             if ( lastVersion != null )
655                 lastVersion.addL10NFiles( l_version.getFiles() );
656             else {
657                 l_version.setOrigin( origin );
658                 l_version.setLast( true );
659                 l_version.setInstall_time( System.currentTimeMillis() );
660                 versions.add( l_version );
661             }
662         }
663         
664         void writeConfigModuleXMLIfMissing () {
665             File JavaDoc configDir = new File JavaDoc (new File JavaDoc (directory, "config"), "Modules"); // NOI18N
666

667             String JavaDoc candidate = null;
668             String JavaDoc oldCandidate = null;
669             String JavaDoc newCandidate = null;
670             
671             String JavaDoc name = codenamebase;
672             int indx = name.indexOf ('/');
673             if (indx > 0) {
674                 name = name.substring (0, indx);
675             }
676             
677             // check module name from config file
678
String JavaDoc replaced = name.replace ('.', '-'); // NOI18N
679
String JavaDoc searchFor;
680             
681             if (replaced.indexOf ("modules") > 0) { // NOI18N
682
// standard module
683
searchFor = replaced + ".jar"; // NOI18N
684
} else {
685                 // core module
686
searchFor = replaced.substring (replaced.lastIndexOf ('-') > 0 ? replaced.lastIndexOf ('-') + 1 : 0) + ".jar"; // NOI18N
687
}
688             
689             String JavaDoc dash = name.replace ('.', '-');
690
691             File JavaDoc config = new File JavaDoc (configDir, dash + ".xml"); // NOI18N
692
if (config.isFile ()) {
693                 // already written
694
return;
695             }
696             
697             config.getParentFile ().mkdirs ();
698             
699             Boolean JavaDoc isAutoload = null;
700             Boolean JavaDoc isEager = null;
701             
702             java.util.Iterator JavaDoc it = newVersion.getFiles ().iterator ();
703             boolean needToWrite = false;
704             
705             while (it.hasNext ()) {
706                 ModuleFile f = (ModuleFile)it.next ();
707
708                 String JavaDoc n = f.getName ();
709                 String JavaDoc parentDir = new File JavaDoc (f.getName ()).getParentFile ().getName ();
710                 
711                 needToWrite = needToWrite || n.indexOf ("modules") >= 0;
712                 
713                 if (n.endsWith (".jar")) { // NOI18N
714
// ok, module candidate
715
candidate = f.getName ();
716                     
717                     // the correct candidate looks as e.g. org.netbeans.modules.mymodule
718
// if no jar looks as codenamebase then the jar file will be found as module's jar
719
if (searchFor.endsWith (candidate) || candidate.endsWith (searchFor)) {
720                         newCandidate = candidate;
721                         oldCandidate = null;
722                         
723                         // autoload and eager will set by module's jar
724
if ("autoload".equals (parentDir)) { // NOI18N
725
isAutoload = Boolean.TRUE;
726                         } else {
727                             isAutoload = Boolean.FALSE;
728                         }
729                         if ("eager".equals (parentDir)) { // NOI18N
730
isEager = Boolean.TRUE;
731                         } else {
732                             isEager = Boolean.FALSE;
733                         }
734                     } else {
735                         if (newCandidate == null) {
736                             oldCandidate = (oldCandidate == null ? "" : oldCandidate + ", ") + candidate; // NOI18N
737
}
738                     }
739                 }
740                 
741                 // if no correct name found => set autoload/eager by the last jar file
742
if (isAutoload == null && "autoload".equals (parentDir)) { // NOI18N
743
isAutoload = Boolean.TRUE;
744                 }
745                 if (isEager == null && "eager".equals (parentDir)) { // NOI18N
746
isEager = Boolean.TRUE;
747                 }
748             }
749             
750             if (! needToWrite) {
751                 System.out.println("Warning: No config file written for module " + codenamebase + ". No jar file present in \"modules\" directory.");
752                 return ;
753             }
754             
755             assert newCandidate != null || oldCandidate != null : "No jar file present!";
756             if (newCandidate == null) {
757                 // PENDING: should check but some NBM assumed wrong behaviour before bugfix 53316
758
assert oldCandidate.equals (candidate) : "More files look as module: " + oldCandidate;
759                 // only temporary
760
if (!oldCandidate.equals (candidate)) {
761                     System.out.println("NBM Error: More files look as module: " + oldCandidate);
762                     oldCandidate = candidate;
763                 }
764                 // end of temp
765
}
766             
767             String JavaDoc moduleName = newCandidate == null ? oldCandidate : newCandidate;
768             
769             boolean autoload = isAutoload != null && isAutoload.booleanValue ();
770             boolean eager = isEager != null && isEager.booleanValue ();
771             boolean isEnabled = !autoload && !eager;
772             
773             String JavaDoc spec = newVersion.getVersion ();
774             OutputStream JavaDoc os;
775             try {
776                 os = new FileOutputStream JavaDoc(config);
777                 PrintWriter JavaDoc pw = new PrintWriter JavaDoc(new java.io.OutputStreamWriter JavaDoc(os, "UTF-8"));
778                 // Please make sure formatting matches what the IDE actually spits
779
// out; it could matter.
780
pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
781                 pw.println("<!DOCTYPE module PUBLIC \"-//NetBeans//DTD Module Status 1.0//EN\"");
782                 pw.println(" \"http://www.netbeans.org/dtds/module-status-1_0.dtd\">");
783                 pw.println("<module name=\"" + name + "\">");
784                 pw.println(" <param name=\"autoload\">" + autoload + "</param>");
785                 pw.println(" <param name=\"eager\">" + eager + "</param>");
786                 if (isEnabled) {
787                     pw.println(" <param name=\"enabled\">" + isEnabled + "</param>");
788                 }
789                 pw.println(" <param name=\"jar\">" + moduleName + "</param>");
790                 pw.println(" <param name=\"reloadable\">false</param>");
791                 pw.println(" <param name=\"specversion\">" + spec + "</param>");
792                 pw.println("</module>");
793                 pw.flush();
794                 pw.close();
795             } catch (IOException JavaDoc ex) {
796                 ex.printStackTrace();
797             }
798             
799         }
800         
801         void write( ) {
802             Document document = XMLUtil.createDocument(ELEMENT_MODULE);
803             
804             Element e_module = document.getDocumentElement();
805             Element e_version = null;
806             Element e_file = null;
807             
808             e_module.setAttribute(ATTR_CODENAMEBASE, getCodenamebase());
809             Iterator it2 = getVersions().iterator();
810             while ( it2.hasNext() ) {
811                 Version ver = (Version)it2.next();
812                 e_version = document.createElement(ELEMENT_VERSION);
813                 if ( ver.getVersion() != null )
814                     e_version.setAttribute(ATTR_VERSION, ver.getVersion());
815                 e_version.setAttribute(ATTR_ORIGIN, ver.getOrigin());
816                 e_version.setAttribute(ATTR_LAST, new Boolean JavaDoc( ver.isLast() ).toString());
817                 e_version.setAttribute(ATTR_INSTALL, Long.toString(ver.getInstall_time()));
818                 e_module.appendChild( e_version );
819                 Iterator it3 = ver.getFiles().iterator();
820                 while ( it3.hasNext() ) {
821                     ModuleFile file = (ModuleFile)it3.next();
822                     e_file = document.createElement(ELEMENT_FILE);
823                     e_file.setAttribute(ATTR_FILE_NAME, file.getName());
824                     e_file.setAttribute(ATTR_CRC, file.getCrc());
825                     if ( file.getLocaleversion() != null )
826                         e_file.setAttribute(ATTR_VERSION, file.getLocaleversion());
827                     e_version.appendChild( e_file );
828                 }
829             }
830             
831             document.getDocumentElement().normalize();
832
833             try {
834                 OutputStream JavaDoc os = new FileOutputStream JavaDoc( file );
835                 XMLUtil.write(document, os);
836                 os.close();
837             } catch (Exception JavaDoc e) {
838                 e.printStackTrace();
839             }
840         }
841
842         void deleteUnusedFiles() {
843             if ( lastVersion == null || newVersion == null )
844                 return;
845             Iterator it = lastVersion.getFiles().iterator();
846             while ( it.hasNext() ) {
847                 ModuleFile modFile = (ModuleFile)it.next();
848                 if ( ! newVersion.containsFile( modFile ) && modFile.getName().indexOf( LOCALE_DIR ) == -1 )
849                     safeDelete( modFile );
850             }
851         }
852         
853         private void safeDelete(ModuleFile modFile) {
854             // test file existence
855
File JavaDoc f = new File JavaDoc( file.getParentFile().getParent() + FILE_SEPARATOR + modFile.getName() );
856             if ( f.exists() ) {
857                 // test crc
858
try {
859                     if ( ! Long.toString( getFileCRC( f ) ).equals( modFile.getCrc() ) )
860                         return;
861                 } catch ( IOException JavaDoc ioe ) {
862                     return;
863                 }
864
865                 // test if file is referenced from other module
866
scanDir();
867                 boolean found = false;
868                 Iterator it = installedModules.values ().iterator();
869                 while ( !found && it.hasNext() ) {
870                     Module mod = (Module)it.next();
871                     if ( ! mod.equals( this ) ) {
872                         Version v = mod.getNewOrLastVersion();
873                         if ( v != null && v.containsFile( modFile ) )
874                             found = true;
875                     }
876                 }
877                 if ( ! found )
878                     f.delete();
879             }
880         }
881         
882         String JavaDoc getL10NSpecificationVersion(String JavaDoc jarpath) {
883             String JavaDoc localever = null;
884             Collections.sort( versions );
885             Iterator it = versions.iterator();
886             while ( it.hasNext() ) {
887                 Version ver = (Version) it.next();
888                 localever = ver.getLocaleVersion( jarpath );
889                 if ( localever != null )
890                     return localever;
891             }
892             return null;
893         }
894     }
895     
896     public class Version extends Object JavaDoc implements Comparable JavaDoc {
897         
898         /** Holds value of property version. */
899         private String JavaDoc version;
900         
901         /** Holds value of property origin. */
902         private String JavaDoc origin;
903         
904         /** Holds value of property last. */
905         private boolean last;
906         
907         /** Holds value of property install_time. */
908         private long install_time = 0;
909         
910         /** Holds value of property files. */
911         private List files = new ArrayList();
912         
913         /** Getter for property version.
914          * @return Value of property version.
915          */

916         String JavaDoc getVersion() {
917             return version;
918         }
919         
920         /** Setter for property version.
921          * @param version New value of property version.
922          */

923         void setVersion(String JavaDoc version) {
924             this.version = version;
925         }
926         
927         /** Getter for property origin.
928          * @return Value of property origin.
929          */

930         String JavaDoc getOrigin() {
931             return origin;
932         }
933         
934         /** Setter for property origin.
935          * @param origin New value of property origin.
936          */

937         void setOrigin(String JavaDoc origin) {
938             this.origin = origin;
939         }
940         
941         /** Getter for property last.
942          * @return Value of property last.
943          */

944         boolean isLast() {
945             return last;
946         }
947         
948         /** Setter for property last.
949          * @param last New value of property last.
950          */

951         void setLast(boolean last) {
952             this.last = last;
953         }
954         
955         /** Getter for property install_time.
956          * @return Value of property install_time.
957          */

958         long getInstall_time() {
959             return install_time;
960         }
961         
962         /** Setter for property install_time.
963          * @param install_time New value of property install_time.
964          */

965         void setInstall_time(long install_time) {
966             this.install_time = install_time;
967         }
968         
969         /** Getter for property files.
970          * @return Value of property files.
971          */

972         List getFiles() {
973             return files;
974         }
975         
976         /** Setter for property files.
977          * @param files New value of property files.
978          */

979         void addL10NFiles(List l10nfiles) {
980             Iterator it = l10nfiles.iterator();
981             while ( it.hasNext() ) {
982                 ModuleFile lf = (ModuleFile) it.next();
983                 String JavaDoc lname = lf.getName();
984                 for ( int i = files.size() - 1; i >=0; i-- ) {
985                     ModuleFile f = (ModuleFile) files.get( i );
986                     if ( f.getName().equals( lname ) )
987                         files.remove( i );
988                 }
989             }
990             files.addAll( l10nfiles );
991         }
992         
993         void addFile( ModuleFile file ) {
994             files.add( file );
995         }
996         
997         public void addFileWithCrc( String JavaDoc filename, String JavaDoc crc ) {
998             ModuleFile file = new ModuleFile();
999             file.setName( filename );
1000            file.setCrc( crc );
1001            files.add( file );
1002        }
1003        
1004        public void addL10NFileWithCrc( String JavaDoc filename, String JavaDoc crc, String JavaDoc specver ) {
1005            ModuleFile file = new ModuleFile();
1006            file.setName( filename );
1007            file.setCrc( crc );
1008            file.setLocaleversion( specver );
1009            files.add( file );
1010        }
1011        
1012        boolean containsFile( ModuleFile file ) {
1013            Iterator it = files.iterator();
1014            while ( it.hasNext() ) {
1015                ModuleFile f = (ModuleFile)it.next();
1016                if ( f.getName().equals( file.getName() ) )
1017                    return true;
1018            }
1019            return false;
1020        }
1021        
1022        ModuleFile findFile(String JavaDoc filename) {
1023            Iterator it = files.iterator();
1024            while ( it.hasNext() ) {
1025                ModuleFile f = (ModuleFile)it.next();
1026                if ( f.getName().equals( filename ) )
1027                    return f;
1028            }
1029            return null;
1030        }
1031        
1032        String JavaDoc getLocaleVersion(String JavaDoc filename) {
1033            String JavaDoc locver = null;
1034            ModuleFile f = findFile( filename );
1035            if ( f != null ) {
1036                locver = f.getLocaleversion();
1037                if ( locver == null )
1038                    locver = version;
1039            }
1040            return locver;
1041        }
1042        
1043        public int compareTo(Object JavaDoc obj) {
1044            Version oth = (Version)obj;
1045            if ( install_time < oth.getInstall_time() )
1046                return 1;
1047            else if ( install_time > oth.getInstall_time() )
1048                return -1;
1049            else
1050                return 0;
1051        }
1052    }
1053    
1054    class ModuleFile extends Object JavaDoc {
1055        
1056        /** Holds value of property name. */
1057        private String JavaDoc name;
1058        
1059        /** Holds value of property crc. */
1060        private String JavaDoc crc;
1061        
1062        /** Holds value of property localeversion. */
1063        private String JavaDoc localeversion = null;
1064        
1065        /** Getter for property name.
1066         * @return Value of property name.
1067         */

1068        String JavaDoc getName() {
1069            return name;
1070        }
1071        
1072        /** Setter for property name.
1073         * @param name New value of property name.
1074         */

1075        void setName(String JavaDoc name) {
1076            this.name = name;
1077        }
1078        
1079        /** Getter for property crc.
1080         * @return Value of property crc.
1081         */

1082        String JavaDoc getCrc() {
1083            return crc;
1084        }
1085        
1086        /** Setter for property crc.
1087         * @param crc New value of property crc.
1088         */

1089        void setCrc(String JavaDoc crc) {
1090            this.crc = crc;
1091        }
1092        
1093        /** Getter for property localeversion.
1094         * @return Value of property localeversion.
1095         *
1096         */

1097        public String JavaDoc getLocaleversion() {
1098            return this.localeversion;
1099        }
1100        
1101        /** Setter for property localeversion.
1102         * @param localeversion New value of property localeversion.
1103         *
1104         */

1105        public void setLocaleversion(String JavaDoc localeversion) {
1106            this.localeversion = localeversion;
1107        }
1108        
1109    }
1110
1111    class ErrorCatcher implements org.xml.sax.ErrorHandler JavaDoc {
1112        private void message (String JavaDoc level, org.xml.sax.SAXParseException JavaDoc e) {
1113            pError = true;
1114        }
1115
1116        public void error (org.xml.sax.SAXParseException JavaDoc e) {
1117            // normally a validity error
1118
pError = true;
1119        }
1120
1121        public void warning (org.xml.sax.SAXParseException JavaDoc e) {
1122            //parseFailed = true;
1123
}
1124
1125        public void fatalError (org.xml.sax.SAXParseException JavaDoc e) {
1126            pError = true;
1127        }
1128    }
1129    
1130}
1131
Popular Tags