KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > core > projects > ValidateLayerConsistencyTest


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

19
20 package org.netbeans.core.projects;
21
22 import java.io.BufferedInputStream JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.text.MessageFormat JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Arrays JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.HashSet JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.Set JavaDoc;
37 import java.util.jar.Manifest JavaDoc;
38 import java.util.logging.Handler JavaDoc;
39 import java.util.logging.Level JavaDoc;
40 import java.util.logging.LogRecord JavaDoc;
41 import java.util.logging.Logger JavaDoc;
42 import junit.framework.Test;
43 import org.netbeans.core.startup.layers.BinaryCacheManager;
44 import org.netbeans.core.startup.layers.ParsingLayerCacheManager;
45 import org.netbeans.junit.NbTestCase;
46 import org.netbeans.junit.NbTestSuite;
47 import org.openide.cookies.InstanceCookie;
48 import org.openide.filesystems.FileObject;
49 import org.openide.filesystems.FileSystem;
50 import org.openide.filesystems.Repository;
51 import org.openide.filesystems.XMLFileSystem;
52 import org.openide.loaders.DataObject;
53 import org.openide.loaders.DataShadow;
54 import org.openide.modules.Dependency;
55 import org.openide.modules.ModuleInfo;
56 import org.openide.util.Lookup;
57 import org.openide.util.Mutex;
58
59 /** Checks consistency of System File System contents.
60  *
61  * @author Jaroslav Tulach
62  */

63 public class ValidateLayerConsistencyTest extends NbTestCase {
64     
65     private ClassLoader JavaDoc contextClassLoader;
66     
67     public ValidateLayerConsistencyTest(String JavaDoc name) {
68         super (name);
69     }
70     
71     public static Test suite() {
72         return new NbTestSuite(ValidateLayerConsistencyTest.class);
73     }
74
75     public void setUp() throws Exception JavaDoc {
76         clearWorkDir();
77         Mutex.EVENT.readAccess(new Mutex.Action<Void JavaDoc>() {
78             public Void JavaDoc run() {
79                 contextClassLoader = Thread.currentThread().getContextClassLoader();
80                 Thread.currentThread().setContextClassLoader((ClassLoader JavaDoc)Lookup.getDefault().lookup(ClassLoader JavaDoc.class));
81                 return null;
82             }
83         });
84     }
85     
86     public void tearDown() {
87         Mutex.EVENT.readAccess(new Mutex.Action<Void JavaDoc>() {
88             public Void JavaDoc run() {
89                 Thread.currentThread().setContextClassLoader(contextClassLoader);
90                 return null;
91             }
92         });
93     }
94     
95     protected boolean runInEQ() {
96         return true;
97     }
98     
99     public void testAreAttributesFine () {
100         List JavaDoc<String JavaDoc> errors = new ArrayList JavaDoc<String JavaDoc>();
101         
102         Enumeration JavaDoc<? extends FileObject> files = Repository.getDefault().getDefaultFileSystem().getRoot().getChildren(true);
103         while (files.hasMoreElements()) {
104             FileObject fo = files.nextElement();
105             
106             // XXX #16761 Removing attr in MFO causes storing special-null value even in unneeded cases.
107
// When the issue is fixed remove this hack.
108
if("Windows2/Modes/debugger".equals(fo.getPath()) // NOI18N
109
|| "Windows2/Modes/explorer".equals(fo.getPath())) { // NOI18N
110
continue;
111             }
112             
113             if (
114                 "Keymaps/NetBeans/D-BACK_QUOTE.shadow".equals(fo.getPath()) ||
115                 "Keymaps/Emacs/D-BACK_QUOTE.shadow".equals(fo.getPath())
116             ) {
117                 // #46753
118
continue;
119             }
120             
121             Enumeration JavaDoc<String JavaDoc> attrs = fo.getAttributes();
122             while (attrs.hasMoreElements()) {
123                 String JavaDoc name = attrs.nextElement();
124                 
125                 if (fo.getAttribute(name) == null) {
126                     errors.add ("\n File " + fo + " attribute name " + name);
127                 }
128             }
129         }
130         
131         if (!errors.isEmpty()) {
132             fail ("Some attributes in files are unreadable" + errors);
133         }
134     }
135     
136     public void testValidShadows () {
137         // might be better to move into editor/options tests as it is valid only if there are options
138
List JavaDoc<String JavaDoc> errors = new ArrayList JavaDoc<String JavaDoc>();
139         
140         FileObject root = Repository.getDefault().getDefaultFileSystem().getRoot();
141         
142         Enumeration JavaDoc<? extends FileObject> en = root.getChildren(true);
143         int cnt = 0;
144         while (en.hasMoreElements()) {
145             FileObject fo = en.nextElement();
146             cnt++;
147             
148             // XXX #16761 Removing attr in MFO causes storing special-null value even in unneeded cases.
149
// When the issue is fixed remove this hack.
150
if("Windows2/Modes/debugger".equals(fo.getPath()) // NOI18N
151
|| "Windows2/Modes/explorer".equals(fo.getPath())) { // NOI18N
152
continue;
153             }
154             
155             if (
156                 "Keymaps/NetBeans/D-BACK_QUOTE.shadow".equals(fo.getPath()) ||
157                 "Keymaps/Emacs/D-BACK_QUOTE.shadow".equals(fo.getPath())
158             ) {
159                 // #46753
160
continue;
161             }
162             
163             try {
164                 DataObject obj = DataObject.find (fo);
165                 DataShadow ds = obj.getCookie(DataShadow.class);
166                 if (ds != null) {
167                     Object JavaDoc o = ds.getOriginal();
168                     if (o == null) {
169                         errors.add("\nFile " + fo + " has no original.");
170                     }
171                 }
172                 else if ("shadow".equals(fo.getExt())) {
173                     errors.add("\nFile " + fo + " is not a valid DataShadow.");
174                 }
175             } catch (Exception JavaDoc ex) {
176                 ex.printStackTrace();
177                 errors.add ("\n File " + fo + " thrown exception " + ex);
178             }
179         }
180         
181         if (!errors.isEmpty()) {
182             fail ("Some shadow files in NetBeans profile are broken:" + errors);
183         }
184         
185         if (ValidateLayerConsistencyTest.class.getClassLoader() == ClassLoader.getSystemClassLoader()) {
186             // do not check the count as this probably means we are running
187
// plain Unit test and not inside the IDE mode
188
return;
189         }
190         
191         
192         if (cnt == 0) {
193             fail("No file objects on system file system!");
194         }
195     }
196     
197     
198     public void testContentCanBeRead () {
199         List JavaDoc<String JavaDoc> errors = new ArrayList JavaDoc<String JavaDoc>();
200         byte[] buffer = new byte[4096];
201         
202         Enumeration JavaDoc<? extends FileObject> files = Repository.getDefault().getDefaultFileSystem().getRoot().getChildren(true);
203         while (files.hasMoreElements()) {
204             FileObject fo = files.nextElement();
205             
206             if (!fo.isData ()) {
207                 continue;
208             }
209             long size = fo.getSize();
210             
211             try {
212                 long read = 0;
213                 InputStream JavaDoc is = fo.getInputStream();
214                 try {
215                     for (;;) {
216                         int len = is.read (buffer);
217                         if (len == -1) break;
218                         read += len;
219                     }
220                 } finally {
221                     is.close ();
222                 }
223                 
224                 if (size != -1) {
225                     assertEquals ("The amount of data in stream is the same as the length", size, read);
226                 }
227                 
228             } catch (IOException JavaDoc ex) {
229                 errors.add ("\n File " + fo + " cannot be read " + ex);
230             }
231         }
232         
233         if (!errors.isEmpty()) {
234             fail ("Some files are unreadable" + errors);
235         }
236     }
237     
238     public void testInstantiateAllInstances () {
239         List JavaDoc<String JavaDoc> errors = new ArrayList JavaDoc<String JavaDoc>();
240         
241         Enumeration JavaDoc<? extends FileObject> files = Repository.getDefault().getDefaultFileSystem().getRoot().getChildren(true);
242         while (files.hasMoreElements()) {
243             FileObject fo = files.nextElement();
244             
245             if (skipFile(fo.getPath())) {
246                 continue;
247             }
248             
249             try {
250                 DataObject obj = DataObject.find (fo);
251                 InstanceCookie ic = obj.getCookie(InstanceCookie.class);
252                 if (ic != null) {
253                     Object JavaDoc o = ic.instanceCreate ();
254                 }
255             } catch (Exception JavaDoc ex) {
256                 ex.printStackTrace();
257                 errors.add ("\n File " + fo + " thrown exception " + ex);
258             }
259         }
260         
261         if (!errors.isEmpty()) {
262             fail ("Some instances cannot be created " + errors);
263         }
264     }
265     
266     public void testIfOneFileIsDefinedTwiceByDifferentModulesTheyNeedToHaveMutualDependency() throws Exception JavaDoc {
267         ClassLoader JavaDoc l = Lookup.getDefault().lookup(ClassLoader JavaDoc.class);
268         assertNotNull ("In the IDE mode, there always should be a classloader", l);
269         
270         // String -> List<Modules>
271
Map JavaDoc<String JavaDoc,List JavaDoc<String JavaDoc>> files = new HashMap JavaDoc<String JavaDoc,List JavaDoc<String JavaDoc>>();
272         class ContentAndAttrs {
273             final byte[] contents;
274             final Map JavaDoc<String JavaDoc,Object JavaDoc> attrs;
275             ContentAndAttrs(byte[] contents, Map JavaDoc<String JavaDoc,Object JavaDoc> attrs) {
276                 this.contents = contents;
277                 this.attrs = attrs;
278             }
279         }
280         /* < FO path , { content, attributes } > */
281         Map JavaDoc<String JavaDoc,ContentAndAttrs> contents = new HashMap JavaDoc<String JavaDoc,ContentAndAttrs>();
282         /* < FO path , < module name, { content, attributes } > > */
283         Map JavaDoc<String JavaDoc,Map JavaDoc<String JavaDoc,ContentAndAttrs>> differentContents = new HashMap JavaDoc<String JavaDoc,Map JavaDoc<String JavaDoc,ContentAndAttrs>>();
284         
285         boolean atLeastOne = false;
286         Enumeration JavaDoc<URL JavaDoc> en = l.getResources("META-INF/MANIFEST.MF");
287         while (en.hasMoreElements ()) {
288             URL JavaDoc u = en.nextElement();
289             InputStream JavaDoc is = u.openStream();
290             Manifest JavaDoc mf;
291             try {
292                 mf = new Manifest JavaDoc(is);
293             } finally {
294                 is.close();
295             }
296             String JavaDoc module = mf.getMainAttributes ().getValue ("OpenIDE-Module");
297             if (module == null) continue;
298             String JavaDoc layer = mf.getMainAttributes ().getValue ("OpenIDE-Module-Layer");
299             if (layer == null) continue;
300             
301             atLeastOne = true;
302             URL JavaDoc layerURL = new URL JavaDoc(u, "../" + layer);
303             java.net.URLConnection JavaDoc connect = layerURL.openConnection ();
304             connect.setDefaultUseCaches (false);
305             FileSystem fs = new XMLFileSystem(layerURL);
306             
307             Enumeration JavaDoc<? extends FileObject> all = fs.getRoot().getChildren(true);
308             while (all.hasMoreElements ()) {
309                 FileObject fo = all.nextElement ();
310                 if (!fo.isData ()) continue;
311                 
312                 String JavaDoc path = fo.getPath();
313                 List JavaDoc<String JavaDoc> list = files.get(path);
314                 if (list == null) {
315                     list = new ArrayList JavaDoc<String JavaDoc>();
316                     files.put (path, list);
317                     list.add (module);
318                     contents.put(path, new ContentAndAttrs(getFileContent(fo), getAttributes(fo)));
319                 } else {
320                     ContentAndAttrs contentAttrs = contents.get(path);
321                     byte[] foc = getFileContent(fo);
322                     Map JavaDoc<String JavaDoc,Object JavaDoc> foa = getAttributes(fo);
323                     if (!Arrays.equals(foc, contentAttrs.contents) || !foa.equals(contentAttrs.attrs)) {
324                         Map JavaDoc<String JavaDoc,ContentAndAttrs> diffs = differentContents.get(path);
325                         if (diffs == null) {
326                             diffs = new HashMap JavaDoc<String JavaDoc,ContentAndAttrs>();
327                             differentContents.put(path, diffs);
328                             diffs.put(list.get(0), contentAttrs);
329                         }
330                         diffs.put(module, new ContentAndAttrs(foc, foa));
331                         list.add (module);
332                     }
333                 }
334             }
335             // make sure the filesystem closes the stream
336
connect.getInputStream ().close ();
337         }
338         contents = null; // Not needed any more
339

340         StringBuffer JavaDoc sb = new StringBuffer JavaDoc ();
341         for (Map.Entry JavaDoc<String JavaDoc,List JavaDoc<String JavaDoc>> e : files.entrySet()) {
342             List JavaDoc<String JavaDoc> list = e.getValue();
343             if (list.size () == 1) continue;
344             
345             Collection JavaDoc<? extends ModuleInfo> res = Lookup.getDefault().lookupAll(ModuleInfo.class);
346             assertFalse("Some modules found", res.isEmpty());
347             
348             for (String JavaDoc name : new ArrayList JavaDoc<String JavaDoc>(list)) {
349                 for (ModuleInfo info : res) {
350                     if (name.equals (info.getCodeName ())) {
351                         // remove dependencies
352
for (Dependency d : info.getDependencies()) {
353                             list.remove (d.getName ());
354                         }
355                     }
356                 }
357             }
358             // ok, modules depend on each other
359
if (list.size () <= 1) continue;
360             
361             sb.append (e.getKey ()).append( " is provided by: " ).append(list).append('\n');
362             Map JavaDoc<String JavaDoc,ContentAndAttrs> diffList = differentContents.get(e.getKey());
363             if (diffList != null) {
364                 if (list.size() == 2) {
365                     String JavaDoc module1 = list.get(0);
366                     String JavaDoc module2 = list.get(1);
367                     ContentAndAttrs contentAttrs1 = diffList.get(module1);
368                     ContentAndAttrs contentAttrs2 = diffList.get(module2);
369                     if (!Arrays.equals(contentAttrs1.contents, contentAttrs2.contents)) {
370                         sb.append(' ').append(module1).append(": content = '").append(new String JavaDoc(contentAttrs1.contents)).append('\n');
371                         sb.append(' ').append(module2).append(": content = '").append(new String JavaDoc(contentAttrs2.contents)).append('\n');
372                     }
373                     if (!contentAttrs1.attrs.equals(contentAttrs2.attrs)) {
374                         Map JavaDoc<String JavaDoc,Object JavaDoc> attr1 = contentAttrs1.attrs;
375                         Map JavaDoc<String JavaDoc,Object JavaDoc> attr2 = contentAttrs2.attrs;
376                         Set JavaDoc<String JavaDoc> keys = new HashSet JavaDoc<String JavaDoc>(attr1.keySet());
377                         keys.retainAll(attr2.keySet());
378                         for (String JavaDoc attribute : keys) {
379                             Object JavaDoc value1 = attr1.get(attribute);
380                             Object JavaDoc value2 = attr2.get(attribute);
381                             if (value1 == value2 || (value1 != null && value1.equals(value2))) {
382                                 // Remove the common attributes so that just the differences show up
383
attr1.remove(attribute);
384                                 attr2.remove(attribute);
385                             }
386                         }
387                         sb.append(' ').append(module1).append(": different attributes = '").append(contentAttrs1.attrs).append('\n');
388                         sb.append(' ').append(module2).append(": different attributes = '").append(contentAttrs2.attrs).append('\n');
389                     }
390                 } else {
391                     for (String JavaDoc module : list) {
392                         ContentAndAttrs contentAttrs = diffList.get(module);
393                         sb.append(" " + module + ": content = '" + new String JavaDoc(contentAttrs.contents) + "', attributes = " + contentAttrs.attrs + "\n");
394                     }
395                 }
396             }
397         }
398         
399         assertTrue ("At least one layer file is usually used", atLeastOne);
400         
401         if (sb.length () > 0) {
402             fail ("Some modules override their files and do not depend on each other\n" + sb);
403         }
404     }
405     
406     public void testNoWarningsFromLayerParsing() throws Exception JavaDoc {
407         ClassLoader JavaDoc l = Lookup.getDefault().lookup(ClassLoader JavaDoc.class);
408         assertNotNull ("In the IDE mode, there always should be a classloader", l);
409         
410         List JavaDoc<URL JavaDoc> urls = new ArrayList JavaDoc<URL JavaDoc>();
411         boolean atLeastOne = false;
412         Enumeration JavaDoc<URL JavaDoc> en = l.getResources("META-INF/MANIFEST.MF");
413         while (en.hasMoreElements ()) {
414             URL JavaDoc u = en.nextElement();
415             InputStream JavaDoc is = u.openStream();
416             Manifest JavaDoc mf;
417             try {
418                 mf = new Manifest JavaDoc(is);
419             } finally {
420                 is.close();
421             }
422             String JavaDoc module = mf.getMainAttributes ().getValue ("OpenIDE-Module");
423             if (module == null) continue;
424             String JavaDoc layer = mf.getMainAttributes ().getValue ("OpenIDE-Module-Layer");
425             if (layer == null) continue;
426             
427             atLeastOne = true;
428             URL JavaDoc layerURL = new URL JavaDoc(u, "../" + layer);
429             urls.add(layerURL);
430         }
431         
432         File JavaDoc cacheDir;
433         File JavaDoc workDir = getWorkDir();
434         int i = 0;
435         do {
436             cacheDir = new File JavaDoc(workDir, "layercache"+i);
437             i++;
438         } while (!cacheDir.mkdir());
439
440         BinaryCacheManager bcm = new BinaryCacheManager(cacheDir);
441         Logger JavaDoc err = Logger.getLogger("org.netbeans.core.projects.cache");
442         LayerParsehandler h = new LayerParsehandler();
443         err.addHandler(h);
444         bcm.store(urls);
445         assertEquals("No errors or warnings during layer parsing: "+h.errors().toString(), 0, h.errors().size());
446     }
447     
448     private static class LayerParsehandler extends Handler JavaDoc {
449         List JavaDoc<String JavaDoc> errors = new ArrayList JavaDoc<String JavaDoc>();
450         
451         LayerParsehandler () {}
452         
453         public void publish(LogRecord JavaDoc rec) {
454             if (Level.WARNING.equals(rec.getLevel()) || Level.SEVERE.equals(rec.getLevel())) {
455                 errors.add(MessageFormat.format(rec.getMessage(), rec.getParameters()));
456             }
457         }
458         
459         List JavaDoc<String JavaDoc> errors() {
460             return errors;
461         }
462
463         public void flush() {
464         }
465
466         public void close() throws SecurityException JavaDoc {
467         }
468     }
469     
470     private static byte[] getFileContent(FileObject fo) throws IOException JavaDoc {
471         BufferedInputStream JavaDoc in = new BufferedInputStream JavaDoc(fo.getInputStream());
472         int size = (int) fo.getSize();
473         byte[] content = new byte[size];
474         int length = 0;
475         while(length < size) {
476             int readLength = in.read(content, length, size - length);
477             if (readLength <= 0) {
478                 throw new IOException JavaDoc("Bad size for "+fo+", size = "+size+", but actual length is "+length);
479             }
480             length +=readLength;
481         }
482         return content;
483     }
484     
485     private static Map JavaDoc<String JavaDoc,Object JavaDoc> getAttributes(FileObject fo) {
486         Map JavaDoc<String JavaDoc,Object JavaDoc> attrs = new HashMap JavaDoc<String JavaDoc,Object JavaDoc>();
487         Enumeration JavaDoc<String JavaDoc> en = fo.getAttributes();
488         while (en.hasMoreElements()) {
489             String JavaDoc attrName = en.nextElement();
490             Object JavaDoc attr = fo.getAttribute(attrName);
491             attrs.put(attrName, attr);
492         }
493         return attrs;
494     }
495     
496     private boolean skipFile (String JavaDoc s) {
497         if (s.startsWith ("Templates/") && !s.startsWith ("Templates/Services")) {
498             if (s.endsWith (".shadow") || s.endsWith (".java")) {
499                 return true;
500             }
501         }
502         
503         if (s.startsWith ("Templates/GUIForms")) return true;
504         if (s.startsWith ("Palette/Borders/javax-swing-border-")) return true;
505         if (s.startsWith ("Palette/Layouts/javax-swing-BoxLayout")) return true;
506         if (s.startsWith ("Templates/Beans/")) return true;
507         if (s.startsWith ("PaletteUI/org-netbeans-modules-form-palette-CPComponent")) return true;
508         if (s.startsWith ("Templates/Ant/CustomTask.java")) return true;
509         if (s.startsWith ("Templates/Privileged/Main.shadow")) return true;
510         if (s.startsWith ("Templates/Privileged/JFrame.shadow")) return true;
511         if (s.startsWith ("Templates/Privileged/Class.shadow")) return true;
512         if (s.startsWith ("Templates/Classes")) return true;
513         if (s.startsWith ("Templates/JSP_Servlet")) return true;
514         if (s.startsWith ("EnvironmentProviders/ProfileTypes/Execution/nb-j2ee-deployment.instance")) return true;
515         if (s.startsWith ("Shortcuts/D-BACK_QUOTE.shadow")) return true;
516         
517         return false;
518     }
519 }
520
Popular Tags