KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > lib > java > storagebuilder > Main


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-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.lib.java.storagebuilder;
21
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileNotFoundException JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.net.MalformedURLException JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.nio.channels.FileChannel JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import javax.jmi.reflect.RefPackage;
32 import org.netbeans.api.mdr.MDRManager;
33 import org.netbeans.api.mdr.MDRepository;
34 import org.netbeans.jmi.javamodel.JavaModelPackage;
35 import org.netbeans.jmi.javamodel.Resource;
36 import org.netbeans.mdr.NBMDRepositoryImpl;
37 import org.netbeans.modules.javacore.classpath.MergedClassPathImplementation;
38 import org.openide.filesystems.FileObject;
39 import org.openide.filesystems.FileUtil;
40 import org.netbeans.modules.javacore.JMManager;
41 import org.netbeans.modules.javacore.CodebasesResolver;
42 import org.netbeans.modules.javacore.internalapi.JavaMetamodel;
43 import org.openide.filesystems.FileStateInvalidException;
44
45 public class Main {
46     
47     static String JavaDoc[] names = new String JavaDoc[0];
48     
49     static {
50         System.setProperty("org.netbeans.javacore.eagerlyParse", ""); // NOI18N
51
// get file names to preparse
52
String JavaDoc s = System.getProperty("preparse.files", "");
53         if (!"".equals(s)) {
54             File JavaDoc f = new File JavaDoc(s);
55             StringBuffer JavaDoc classes = new StringBuffer JavaDoc(1024);
56             FileInputStream JavaDoc is = null;
57             try {
58                 is = new FileInputStream JavaDoc(f);
59                 byte[] c = new byte[1024];
60                 int bytesread;
61                 while ((bytesread=is.read(c)) > 0) {
62                     classes.append(new String JavaDoc(c,0,bytesread));
63                 }
64                 names = classes.toString().split(":"); // NOI18N
65
} catch (FileNotFoundException JavaDoc e) {
66                 System.err.println("File does not exist.");
67                 System.err.println(e);
68             } catch (IOException JavaDoc e) {
69                 System.err.println("File does not exist.");
70                 System.err.println(e);
71             } finally {
72                 try {
73                     if (is != null) {
74                         is.close();
75                     }
76                 } catch (IOException JavaDoc e) {
77                     // ignore this
78
}
79             }
80         }
81     }
82     
83     private static JavaModelPackage javaPckg = null;
84     
85     public static final int OK = 0;
86     public static final int FAILED = 1;
87     
88     /** Creates MDR storage for rt.jar and src.zip in a given list of jdks + scans jars explicitly listed.
89      * @param jdks Path to jdk homes (will scan src.zip and rt.jar for these) and other jars to be scanned.
90      * @param destDir Destination directory of the resulting MDR storage files.
91      * @return Error code (OK or FAILED).
92      */

93     public static int prebuildJDKStorages(String JavaDoc[] jdks, String JavaDoc destDir) {
94         int result;
95         File JavaDoc dir;
96         
97         ArrayList JavaDoc/*<String>*/ jarsList = new ArrayList JavaDoc(jdks.length * 2);
98         ArrayList JavaDoc/*<String[]>*/ resNamesList = new ArrayList JavaDoc(jdks.length * 2);
99         for (int i = 0; i < jdks.length; i++) {
100             if (jdks[i].endsWith(".jar") || jdks[i].endsWith(".zip")) { // NOI18N
101
jarsList.add(jdks[i]);
102                 resNamesList.add(new String JavaDoc[0]);
103             } else {
104                 dir = new File JavaDoc(jdks[i]);
105                 if (!dir.exists()) {
106                     System.out.println("JDK home directory not found: " + jdks[i]); // NOI18N
107
return FAILED;
108                 }
109                 if (!jdks[i].endsWith(File.separator)) {
110                     jdks[i] = jdks[i] + File.separator;
111                 }
112                 jarsList.add(jdks[i] + "jre" + File.separator + "lib" + File.separator + "rt.jar"); // NOI18N
113
String JavaDoc resNames[] = new String JavaDoc[names.length];
114                 for (int j = 0; j < names.length; j++) {
115                     resNames[j] = names[j].concat(".class"); // NOI18N
116
}
117                 resNamesList.add(resNames);
118                 jarsList.add(jdks[i] + "src.zip"); // NOI18N
119
resNames = new String JavaDoc[names.length];
120                 for (int j = 0; j < names.length; j++) {
121                     resNames[j] = names[j].concat(".java"); // NOI18N
122
}
123                 resNamesList.add(resNames);
124             }
125         }
126         String JavaDoc jars[] = (String JavaDoc[]) jarsList.toArray(new String JavaDoc[jarsList.size()]);
127         String JavaDoc resNames[][] = (String JavaDoc[][]) resNamesList.toArray(new String JavaDoc[jarsList.size()][]);
128         return prebuildJars(jars, new boolean[jars.length], resNames, destDir);
129     }
130     
131     /** Creates MDR storage for given jars.
132      * @param jars Array of names of jars to be scanned.
133      * @param deepParse Indicates whether a given jar should be scanned deeply (e.g. pre-parse also the methods, etc., not just classes).
134      * @param names If deepParse == false for a given jar, this parameter may contain an array of names (with paths relative from the jar-root)
135      * of files that should be scanned deeply.
136      * @param destDir Destination directory for the resulting MDR storage files.
137      * @return Error code (OK or FAILED).
138      */

139     public static int prebuildJars(String JavaDoc[] jars, boolean[] deepParse, String JavaDoc[][] names, String JavaDoc destDir) {
140         int result;
141         File JavaDoc dir;
142         
143         dir = new File JavaDoc(destDir);
144         if (!dir.exists()) {
145             System.out.println("Target directory does not exist: " + destDir); // NOI18N
146
return FAILED;
147         }
148         String JavaDoc storagesDir = System.getProperty("mdr.filename"); // NOI18N
149
if (storagesDir == null) {
150             System.out.println("mdr.filename property not specified"); // NOI18N
151
return FAILED;
152         }
153         int index = storagesDir.lastIndexOf(File.separator);
154         if (index > 0) {
155             String JavaDoc dirName = storagesDir.substring(0,index);
156             dir = new File JavaDoc(dirName);
157             if (!dir.exists()) {
158                 System.out.println("mdr storage directory does not exist: " + dirName); // NOI18N
159
return FAILED;
160             }
161         }
162         for (int x = 0; x < jars.length; x++) {
163             dir = new File JavaDoc(jars[x]);
164             if (!dir.exists()) {
165                 System.out.println("Jar not found: " + jars[x]); // NOI18N
166
return FAILED;
167             }
168         }
169         
170         if (!destDir.endsWith(File.separator)) {
171             destDir = destDir + File.separator;
172         }
173         try {
174             String JavaDoc jarSimpleNames[] = new String JavaDoc[jars.length];
175             for (int i = 0; i < jars.length; i++) {
176                 int pos = jars[i].lastIndexOf(File.separator);
177                 jarSimpleNames[i] = pos >= 0 ? jars[i].substring(pos + 1) : jars[i];
178                 pos = jarSimpleNames[i].lastIndexOf('.');
179                 if (pos >= 0) jarSimpleNames[i] = jarSimpleNames[i].substring(0, pos);
180                 result = preparseFile(jars[i], jarSimpleNames[i], deepParse[i]);
181                 if (result != OK)
182                     return result;
183                 if (names[i].length > 0 && javaPckg != null) {
184                     preparseResources(names[i]);
185                 }
186             }
187             MDRepository repository = MDRManager.getDefault().getRepository("org.netbeans.java"); // NOI18N
188
repository.shutdown();
189             for (int i = 0; i < jars.length; i++) {
190                 result = saveFile(jars[i], jarSimpleNames[i], destDir); // NOI18N
191
if (result != OK)
192                     return result;
193             }
194         } catch (FileStateInvalidException e) {
195             System.out.println("process failed: " + e.getMessage()); // NOI18N
196
System.out.flush();
197             return FAILED;
198         } catch (MalformedURLException JavaDoc e) {
199             System.out.println("process failed: " + e.getMessage()); // NOI18N
200
System.out.flush();
201             return FAILED;
202         }
203         return OK;
204     }
205
206     private static int preparseFile(String JavaDoc filename, String JavaDoc type, boolean preparseFeatures) throws FileStateInvalidException, MalformedURLException JavaDoc {
207         System.out.println("preparsing " + filename); // NOI18N
208
File JavaDoc file = new File JavaDoc(filename);
209         FileObject archive = FileUtil.toFileObject(file);
210         if (archive == null) {
211             System.out.println("file not found: " + filename); // NOI18N
212
return FAILED;
213         }
214         FileObject archiveRoot = FileUtil.getArchiveRoot(archive);
215         URL JavaDoc archiveUrl = archiveRoot.getURL();
216         MergedClassPathImplementation.getDefault().addRoot(archiveUrl);
217         CodebasesResolver.resolve();
218         // pre-parse
219
NBMDRepositoryImpl impl = (NBMDRepositoryImpl) JavaMetamodel.getDefaultRepository();
220         javaPckg = JavaMetamodel.getManager().getJavaExtent(archiveRoot);
221         if (preparseFeatures) {
222             Resource[] resources = (Resource[]) javaPckg.getResource().refAllOfClass().toArray(new Resource[0]);
223             int p = 0, closed = 0;
224             impl.beginTrans(true);
225             impl.disableEvents();
226             try {
227                 for (int i = 0; i < resources.length; i++) {
228                     resources[i].getImports();
229                     resources[i] = null;
230                     int newP = i * 100 / resources.length;
231                     long free = Runtime.getRuntime().freeMemory();
232                     long total = Runtime.getRuntime().totalMemory();
233                     if (free < (total / 4)) {
234                         impl.endTrans();
235                         System.gc();
236                         impl.beginTrans(true);
237                         impl.disableEvents();
238                         closed = i;
239                     }
240                     if (newP != p) {
241                         if (newP % 10 == 0) {
242                             System.out.println(newP + "%"); // NOI18N
243
System.out.flush();
244                         }
245                         p = newP;
246                     }
247                 }
248                 System.out.println("100%"); // NOI18N
249
System.out.flush();
250             } catch (Exception JavaDoc e) {
251                 System.out.println(" ... failed: " + e.getMessage()); // NOI18N
252
System.out.flush();
253                 return FAILED;
254             } finally {
255                 impl.endTrans();
256             }
257         }
258         System.out.println(" ... done"); // NOI18N
259
String JavaDoc uri = ((JMManager) JMManager.getManager()).getRootURI(archiveRoot);
260         RefPackage extent = (JavaModelPackage)impl.getExtent("codebase:" + uri); // NOI18N
261
if ((JavaModelPackage)impl.getExtent("codebase:" + type) != null) { // NOI18N
262
System.out.println("Cannot rename extent, there is already one of the same name."); // NOI18N
263
System.out.println("It seems that storage files already existed in the temp mdr directory (specified by mdr.filename property)."); // NOI18N
264
return FAILED;
265         }
266         impl.renameExtent(extent, "codebase:" + type); // NOI18N
267
return OK;
268     }
269
270     private static int saveFile(String JavaDoc filename, String JavaDoc type, String JavaDoc saveToDir) throws FileStateInvalidException, MalformedURLException JavaDoc {
271         System.out.print("copying storages for " + filename); // NOI18N
272
File JavaDoc file = new File JavaDoc(filename);
273         FileObject archive = FileUtil.toFileObject(file);
274         FileObject archiveRoot = FileUtil.getArchiveRoot(archive);
275         URL JavaDoc archiveUrl = archiveRoot.getURL();
276         NBMDRepositoryImpl impl = (NBMDRepositoryImpl) JavaMetamodel.getDefaultRepository();
277         try {
278             String JavaDoc hash = JMManager.computePreparsedHash(file, JMManager.BYTES4MD5);
279             String JavaDoc uri = ((JMManager) JMManager.getManager()).getRootURI(archiveRoot);
280             JMManager m = (JMManager) JMManager.getManager();
281             String JavaDoc strName = m.getFileName(m.getValidName(m.getRootURI(archiveRoot)));
282             if (!JMManager.copyStorage(strName, saveToDir + type + "-" + hash, true)) { // NOI18N
283
return FAILED;
284             }
285             System.out.println(" ... done"); // NOI18N
286
} catch (Exception JavaDoc e) {
287             System.out.println(" ... failed: " + e.getMessage()); // NOI18N
288
return FAILED;
289         }
290         return OK;
291     }
292     
293     private static int preparseResources(String JavaDoc[] names) {
294         NBMDRepositoryImpl impl = (NBMDRepositoryImpl) JavaMetamodel.getDefaultRepository();
295         for (int i = 0; i < names.length; i++) {
296             impl.beginTrans(true);
297             impl.disableEvents();
298             try {
299                 Resource r = javaPckg.getResource().resolveResource(names[i], false);
300                 if (r == null) {
301                     System.out.println("null for name: '" + names[i] + "'."); // NOI18N
302
} else {
303                     System.out.println("name: '" + r.getName() + "'."); // NOI18N
304
r.getImports();
305                 }
306             } catch (Exception JavaDoc e) {
307                 System.out.println(" ... failed: " + e.getMessage()); // NOI18N
308
System.out.flush();
309                 return FAILED;
310             } finally {
311                 impl.endTrans();
312             }
313         }
314         return OK;
315     }
316     
317     public static void main(String JavaDoc[] args) throws IOException JavaDoc {
318         String JavaDoc[] jdks = new String JavaDoc[args.length - 1];
319         for (int x = 1; x < args.length; x++) {
320             jdks[x - 1] = args[x];
321         }
322         System.exit(prebuildJDKStorages(jdks, args[0]));
323     }
324
325 }
326
Popular Tags