KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > persistence > wizard > library > PersistenceLibrarySupport


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.modules.j2ee.persistence.wizard.library;
21
22 import java.io.IOException JavaDoc;
23 import java.io.OutputStreamWriter JavaDoc;
24 import java.io.PrintWriter JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collections JavaDoc;
28 import java.util.Comparator JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import org.netbeans.api.project.libraries.Library;
32 import org.netbeans.api.project.libraries.LibraryManager;
33 import org.netbeans.modules.j2ee.persistence.dd.persistence.model_1_0.PersistenceUnit;
34 import org.netbeans.modules.j2ee.persistence.provider.Provider;
35 import org.netbeans.modules.j2ee.persistence.provider.ProviderUtil;
36 import org.netbeans.spi.project.libraries.LibraryImplementation;
37 import org.openide.ErrorManager;
38 import org.openide.filesystems.FileLock;
39 import org.openide.filesystems.URLMapper;
40 import org.openide.filesystems.FileObject;
41 import org.openide.filesystems.FileSystem;
42 import org.openide.filesystems.FileUtil;
43 import org.openide.filesystems.Repository;
44 import org.openide.xml.XMLUtil;
45
46 /**
47  * Various stuff copied mostly from org.netbeans.modules.project.libraries,
48  * because it is not possible to add library to Library manager throught some API.
49  */

50 public class PersistenceLibrarySupport {
51     
52     public static final String JavaDoc VOLUME_TYPE_CLASSPATH = "classpath"; //NOI18N
53
public static final String JavaDoc VOLUME_TYPE_SRC = "src"; //NOI18N
54
public static final String JavaDoc VOLUME_TYPE_JAVADOC = "javadoc"; //NOI18N
55
public static final String JavaDoc LIBRARY_TYPE = "j2se"; //NOI18N
56
public static final String JavaDoc[] VOLUME_TYPES = new String JavaDoc[] {
57         VOLUME_TYPE_CLASSPATH,
58         VOLUME_TYPE_SRC,
59         VOLUME_TYPE_JAVADOC,
60     };
61     
62     private static final String JavaDoc LIBRARIES_REPOSITORY = "org-netbeans-api-project-libraries/Libraries"; //NOI18N
63
private static int MAX_DEPTH = 3;
64     
65     private FileObject storage = null;
66     private static PersistenceLibrarySupport instance;
67     
68     private PersistenceLibrarySupport() {
69     }
70     
71     public static PersistenceLibrarySupport getDefault() {
72         if (instance == null) {
73             instance = new PersistenceLibrarySupport();
74         }
75         return instance;
76     }
77     
78     public void addLibrary(LibraryImplementation library) {
79         this.initStorage();
80         assert this.storage != null : "Storage is not initialized";
81         try {
82             writeLibrary(this.storage,library);
83         } catch (IOException JavaDoc ex) {
84             ErrorManager.getDefault().notify(ex);
85         }
86     }
87     
88     private static final FileObject createStorage() {
89         FileSystem storageFS = Repository.getDefault().getDefaultFileSystem();
90         try {
91             return FileUtil.createFolder(storageFS.getRoot(), LIBRARIES_REPOSITORY);
92         } catch (IOException JavaDoc e) {
93             return null;
94         }
95     }
96     
97     private synchronized void initStorage() {
98         if (this.storage == null) {
99             this.storage = createStorage();
100             if (storage == null) {
101                 return;
102             }
103         }
104     }
105     
106     private void writeLibrary(final FileObject storage, final LibraryImplementation library) throws IOException JavaDoc {
107         storage.getFileSystem().runAtomicAction(
108                 new FileSystem.AtomicAction() {
109             public void run() throws IOException JavaDoc {
110                 FileObject fo = storage.createData(library.getName(),"xml"); //NOI18N
111
writeLibraryDefinition(fo, library);
112             }
113         }
114         );
115     }
116     
117     private static void writeLibraryDefinition(final FileObject definitionFile, final LibraryImplementation library) throws IOException JavaDoc {
118         FileLock lock = null;
119         PrintWriter JavaDoc out = null;
120         try {
121             lock = definitionFile.lock();
122             out = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(definitionFile.getOutputStream(lock),"UTF-8"));
123             out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); //NOI18N
124
out.println("<!DOCTYPE library PUBLIC \"-//NetBeans//DTD Library Declaration 1.0//EN\" \"http://www.netbeans.org/dtds/library-declaration-1_0.dtd\">"); //NOI18N
125
out.println("<library version=\"1.0\">"); //NOI18N
126
out.println("\t<name>"+library.getName()+"</name>"); //NOI18N
127
out.println("\t<type>"+library.getType()+"</type>");
128             String JavaDoc description = library.getDescription();
129             if (description != null && description.length() > 0) {
130                 out.println("\t<description>"+description+"</description>"); //NOI18N
131
}
132             String JavaDoc localizingBundle = library.getLocalizingBundle();
133             if (localizingBundle != null && localizingBundle.length() > 0) {
134                 out.println("\t<localizing-bundle>"+XMLUtil.toElementContent(localizingBundle)+"</localizing-bundle>"); //NOI18N
135
}
136             String JavaDoc[] volumeTypes = VOLUME_TYPES;
137             for (int i = 0; i < volumeTypes.length; i++) {
138                 out.println("\t<volume>"); //NOI18N
139
out.println("\t\t<type>"+volumeTypes[i]+"</type>"); //NOI18N
140
List JavaDoc volume = library.getContent(volumeTypes[i]);
141                 if (volume != null) {
142                     //If null -> broken library, repair it.
143
for (Iterator JavaDoc eit = volume.iterator(); eit.hasNext();) {
144                         URL JavaDoc url = (URL JavaDoc) eit.next();
145                         out.println("\t\t<resource>"+XMLUtil.toElementContent(url.toExternalForm())+"</resource>"); //NOI18N
146
}
147                 }
148                 out.println("\t</volume>"); //NOI18N
149
}
150             out.println("</library>"); //NOI18N
151
} finally {
152             if (out != null)
153                 out.close();
154             if (lock != null)
155                 lock.releaseLock();
156         }
157     }
158     
159     // from org.netbeans.modules.java.j2seproject.queries.JavadocForBinaryQueryImpl
160

161     /**
162      * Tests if the query accepts the root as valid JavadocRoot,
163      * the query accepts the JavaDoc root, if it can find the index-files
164      * or index-all.html in the root.
165      * @param rootURL the javadoc root
166      * @return true if the root is a valid Javadoc root
167      */

168     public static boolean isValidLibraryJavadocRoot(final URL JavaDoc rootURL) {
169         assert rootURL != null && rootURL.toExternalForm().endsWith("/");
170         final FileObject root = URLMapper.findFileObject(rootURL);
171         if (root == null) {
172             return false;
173         }
174         return findIndexFolder(root,1) != null;
175     }
176     
177     private static FileObject findIndexFolder(FileObject fo, int depth) {
178         if (depth > MAX_DEPTH) {
179             return null;
180         }
181         if (fo.getFileObject("index-files",null)!=null || fo.getFileObject("index-all.html",null)!=null) { //NOI18N
182
return fo;
183         }
184         FileObject[] children = fo.getChildren();
185         for (int i=0; i< children.length; i++) {
186             if (children[i].isFolder()) {
187                 FileObject result = findIndexFolder(children[i], depth+1);
188                 if (result != null) {
189                     return result;
190                 }
191             }
192         }
193         return null;
194     }
195     
196     /**
197      *@return true if the given library contains a class with the given name.
198      */

199     public static boolean containsClass(Library library, String JavaDoc className) {
200         String JavaDoc classRelativePath = className.replace('.', '/') + ".class"; //NOI18N
201
return containsPath(library.getContent("classpath"), classRelativePath); //NOI18N
202
}
203     
204     /**
205      *@return true if the given library contains a service with the given name.
206      */

207     public static boolean containsService(Library library, String JavaDoc serviceName) {
208         String JavaDoc serviceRelativePath = "META-INF/services/" + serviceName; //NOI18N
209
return containsPath(library.getContent("classpath"), serviceRelativePath); //NOI18N
210
}
211     
212     /**
213      *@return true if the given library contains a class with the given name.
214      */

215     public static boolean containsClass(LibraryImplementation library, String JavaDoc className) {
216         String JavaDoc classRelativePath = className.replace('.', '/') + ".class"; //NOI18N
217
return containsPath(library.getContent("classpath"), classRelativePath); //NOI18N
218
}
219     
220     /**
221      *@return true if the given library contains a service with the given name.
222      */

223     public static boolean containsService(LibraryImplementation library, String JavaDoc serviceName) {
224         String JavaDoc serviceRelativePath = "META-INF/services/" + serviceName; //NOI18N
225
return containsPath(library.getContent("classpath"), serviceRelativePath); //NO18N
226
}
227     
228     private static boolean containsPath(List JavaDoc<URL JavaDoc> roots, String JavaDoc relativePath) {
229         for (URL JavaDoc each :roots){
230             FileObject root = URLMapper.findFileObject(each);
231             if (root != null && "jar".equals(each.getProtocol())) { //NOI18N
232
FileObject archiveRoot = FileUtil.getArchiveRoot(FileUtil.getArchiveFile(root));
233                 if (archiveRoot.getFileObject(relativePath) != null) {
234                     return true;
235                 }
236             }
237         }
238         return false;
239     }
240     
241     /**
242      * @return the library in which given persistence unit's provider
243      * is defined, or null none could be found.
244      */

245     public static Library getLibrary(PersistenceUnit pu) {
246         return getLibrary(ProviderUtil.getProvider(pu));
247     }
248     
249     /**
250      * @return the library in which given provider
251      * is defined, or null none could be found.
252      */

253     public static Library getLibrary(Provider provider){
254         List JavaDoc<Library> libraries = createLibraries();
255         for (Library each : libraries){
256             if (provider.getProviderClass().equals(extractProvider(each))) {
257                 return each;
258             }
259         }
260         return null;
261     }
262     
263     private static List JavaDoc<Library> createLibraries() {
264         List JavaDoc<Library> providerLibs = new ArrayList JavaDoc<Library>();
265         for (Library each : LibraryManager.getDefault().getLibraries()){
266             if (PersistenceLibrarySupport.containsClass(each, "javax.persistence.EntityManager") && extractProvider(each) != null) {
267                 providerLibs.add(each);
268             }
269         }
270         Collections.sort(providerLibs, new Comparator JavaDoc() {
271             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
272                 assert (o1 instanceof Library) && (o2 instanceof Library);
273                 String JavaDoc name1 = ((Library)o1).getDisplayName();
274                 String JavaDoc name2 = ((Library)o2).getDisplayName();
275                 return name1.compareToIgnoreCase(name2);
276             }
277         });
278         return providerLibs;
279     }
280   
281     /**
282      * Gets the persistence providers that are defined in the libraries
283      * of the IDE.
284      *
285      * @return list of the providers that are defined in the IDE's libraries.
286      */

287     public static List JavaDoc<Provider> getProvidersFromLibraries() {
288         List JavaDoc<Provider> providerLibs = new ArrayList JavaDoc<Provider>();
289         Library[] libs = LibraryManager.getDefault().getLibraries();
290         for (Library each : libs){
291             Provider provider = extractProvider(each);
292             if (PersistenceLibrarySupport.containsClass(each, "javax.persistence.EntityManager") && provider != null) {
293                 providerLibs.add(provider);
294             }
295         }
296         Collections.sort(providerLibs, new Comparator JavaDoc() {
297             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
298                 String JavaDoc name1 = ((Provider)o1).getDisplayName();
299                 String JavaDoc name2 = ((Provider)o2).getDisplayName();
300                 return name1.compareToIgnoreCase(name2);
301             }
302         });
303         
304         return providerLibs;
305     }
306     
307     /**
308      * @return the first library in the IDE's libraries which contains
309      * a persistence provider.
310      */

311     public static Library getFirstProviderLibrary() {
312         List JavaDoc<Library> libraries = createLibraries();
313         if (libraries.size() > 0) {
314             return libraries.iterator().next();
315         }
316         return null;
317     }
318     
319     
320     private static Provider extractProvider(Library library) {
321         for (Provider each : ProviderUtil.getAllProviders()){
322             if (PersistenceLibrarySupport.containsClass(library, each.getProviderClass())){
323                 return each;
324             }
325         }
326         return null;
327     }
328     
329 }
330
Popular Tags