KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > xml > retriever > catalog > Utilities


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.xml.retriever.catalog;
21
22 import java.io.BufferedInputStream JavaDoc;
23 import java.io.BufferedOutputStream JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26 import java.io.FileNotFoundException JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.UnsupportedEncodingException JavaDoc;
31 import java.lang.management.ManagementFactory JavaDoc;
32 import java.net.MalformedURLException JavaDoc;
33 import java.net.Proxy JavaDoc;
34 import java.net.URI JavaDoc;
35 import java.net.URISyntaxException JavaDoc;
36 import java.net.URL JavaDoc;
37 import java.net.URLConnection JavaDoc;
38 import java.net.UnknownHostException JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.Collections JavaDoc;
41 import java.util.HashMap JavaDoc;
42 import java.util.Iterator JavaDoc;
43 import java.util.List JavaDoc;
44 import java.util.Map JavaDoc;
45 import java.util.Map.Entry;
46 import java.util.Set JavaDoc;
47 import java.util.StringTokenizer JavaDoc;
48 import java.util.logging.Level JavaDoc;
49 import java.util.logging.Logger JavaDoc;
50 import javax.swing.text.Document JavaDoc;
51 import javax.xml.namespace.NamespaceContext JavaDoc;
52 import javax.xml.xpath.XPath JavaDoc;
53 import javax.xml.xpath.XPathConstants JavaDoc;
54 import javax.xml.xpath.XPathFactory JavaDoc;
55 import org.netbeans.api.project.FileOwnerQuery;
56 import org.netbeans.api.project.Project;
57 import org.netbeans.api.project.ProjectUtils;
58 import org.netbeans.api.project.SourceGroup;
59 import org.netbeans.editor.BaseDocument;
60 import org.netbeans.modules.xml.retriever.Retriever;
61 import org.netbeans.modules.xml.retriever.RetrieverImpl;
62 import org.netbeans.modules.xml.retriever.XMLCatalogProvider;
63 import org.netbeans.modules.xml.retriever.catalog.impl.*;
64 import org.netbeans.modules.xml.xam.ModelSource;
65 import org.netbeans.modules.xml.xam.locator.CatalogModel;
66 import org.netbeans.modules.xml.xam.locator.CatalogModelException;
67 import org.netbeans.modules.xml.xam.locator.CatalogModelFactory;
68 import org.netbeans.spi.project.CacheDirectoryProvider;
69 import org.netbeans.spi.xml.cookies.DataObjectAdapters;
70 import org.openide.cookies.EditorCookie;
71 import org.openide.filesystems.FileObject;
72 import org.openide.filesystems.FileUtil;
73 import org.openide.loaders.DataObject;
74 import org.openide.loaders.DataObjectNotFoundException;
75 import org.openide.util.Lookup;
76 import org.openide.util.UserQuestionException;
77 import org.openide.util.lookup.Lookups;
78 import org.w3c.dom.Node JavaDoc;
79 import org.w3c.dom.NodeList JavaDoc;
80 import org.xml.sax.InputSource JavaDoc;
81
82 /**
83  *
84  * @author girix
85  */

86 public class Utilities {
87     public static final String JavaDoc NO_NAME_SPACE = "NO_NAME_SPACE"; //NOI18N
88
private static final Logger JavaDoc logger = getLogger();
89     
90     public static URL JavaDoc appendURL(URL JavaDoc prefixURL, String JavaDoc suffixStr){
91         String JavaDoc str = prefixURL.toString();
92         String JavaDoc newurl = null;
93         if(str.endsWith("/"))
94             newurl = str+suffixStr;
95         else
96             newurl = str+"/"+suffixStr;
97         try {
98             return new URL JavaDoc(newurl);
99         } catch (MalformedURLException JavaDoc ex) {
100         }
101         return null;
102     }
103     
104     public static boolean localResourceExists(URL JavaDoc localURL){
105         File JavaDoc locaFile = null;
106         try {
107             locaFile = new File JavaDoc(localURL.toURI());
108             return locaFile.exists();
109         } catch (URISyntaxException JavaDoc ex) {
110         }
111         return false;
112         
113     }
114     
115     public static File JavaDoc toFile(URL JavaDoc url){
116         URI JavaDoc uri;
117         try {
118             uri = url.toURI();
119         } catch (URISyntaxException JavaDoc ex) {
120             return null;
121         }
122         return new File JavaDoc(uri);
123     }
124     
125     public static void deleteRecursively(File JavaDoc aDir){
126         if(aDir.isDirectory()){
127             //get all children and delete them too
128
File JavaDoc[] children = aDir.listFiles();
129             for(File JavaDoc file: children)
130                 deleteRecursively(file);
131             //System.out.printf("Deleting: %s (%s)\n", aDir.getAbsolutePath(), (aDir.isFile())?"File":"Dir");
132
aDir.delete();
133         }else{
134             //normal file just delete
135
//System.out.printf("Deleting: %s (%s)\n", aDir.getAbsolutePath(), (aDir.isFile())?"File":"Dir");
136
aDir.delete();
137         }
138     }
139     
140     public static String JavaDoc normalizeURI(String JavaDoc uriref) {
141         StringBuilder JavaDoc newRef = new StringBuilder JavaDoc();
142         byte[] bytes;
143         
144         if (uriref == null) {
145             return null;
146         }
147         
148         try {
149             bytes = uriref.getBytes("UTF-8");
150         } catch (UnsupportedEncodingException JavaDoc uee) {
151             // this can't happen
152
return uriref;
153         }
154         
155         for (int count = 0; count < bytes.length; count++) {
156             int ch = bytes[count] & 0xFF;
157             
158             if ((ch <= 0x20) // ctrl
159
|| (ch > 0x7F) // high ascii
160
|| (ch == 0x22) // "
161
|| (ch == 0x3C) // <
162
|| (ch == 0x3E) // >
163
|| (ch == 0x5C) // \
164
|| (ch == 0x5E) // ^
165
|| (ch == 0x60) // `
166
|| (ch == 0x7B) // {
167
|| (ch == 0x7C) // |
168
|| (ch == 0x7D) // }
169
|| (ch == 0x7F)) {
170                 newRef.append(encodedByte(ch));
171             } else {
172                 newRef.append((char) bytes[count]);
173             }
174         }
175         
176         return newRef.toString();
177     }
178     
179     public static String JavaDoc encodedByte(int b) {
180         String JavaDoc hex = Integer.toHexString(b).toUpperCase();
181         if (hex.length() < 2) {
182             return "%0" + hex;
183         } else {
184             return "%" + hex;
185         }
186     }
187     
188     /**
189      * This method will work ONLY for the files that are there in the local file system and
190      * that have common URI up to server level.
191      * Result is a relative URI of the slave file WRT the master file
192      */

193     public static String JavaDoc relativize(URI JavaDoc master, URI JavaDoc slave) {
194         String JavaDoc masterStr = master.toString();
195         String JavaDoc slaveStr = slave.toString();
196         StringTokenizer JavaDoc masterTok = new StringTokenizer JavaDoc(masterStr, "/");
197         StringTokenizer JavaDoc slaveTok = new StringTokenizer JavaDoc(slaveStr, "/");
198         String JavaDoc masterLast = null;
199         String JavaDoc slaveLast = null;
200         int iteration = -1;
201         while(true){
202             iteration++;
203             if(masterTok.hasMoreTokens() && slaveTok.hasMoreTokens()){
204                 masterLast = masterTok.nextToken();
205                 slaveLast = slaveTok.nextToken();
206                 if(masterLast.equals(slaveLast))
207                     continue;
208                 else
209                     break;
210             }
211             break;
212         }
213         //if even the server part is changing then just return the slave totally as absoulte URI
214
if(iteration < 2)
215             return slave.toString();
216         //count number of ../'es
217
int dirCount = masterTok.countTokens();
218         //generate prefix
219
String JavaDoc pathPrefix = "";
220         StringBuffer JavaDoc pathPrefixBuff = new StringBuffer JavaDoc("");
221         for(int i=0; i<dirCount;i++){
222             pathPrefixBuff.append("../");
223         }
224         pathPrefix = pathPrefixBuff.toString();
225         //collect rest of slave tokens
226
StringBuilder JavaDoc slaveResult = masterLast.equals(slaveLast)?
227             new StringBuilder JavaDoc():new StringBuilder JavaDoc(slaveLast);
228         while(slaveTok.hasMoreTokens()) {
229             if(slaveResult.length() != 0)
230                 slaveResult.append('/');
231             slaveResult.append(slaveTok.nextToken());
232         }
233         //add prefix to slaveStr
234
return pathPrefix + slaveResult.toString();
235     }
236     
237     /**
238      * Convenience method that returns a logger for this module.
239      * Returned logger object must be used in the implementation for debuggin purpose
240      * Client code can get this logger and set the level by calling logger.setLevel(level);
241      * By default, this logger does not have any Handlers and it has default Level set.
242      * Feel free to set handlers and level for this object.
243      * To route messages to IDE log/console window, use the following code snip
244      * <pre>
245      * Logger logger = DepResolverFactoryImpl.getDefaultNSRLogger();
246      * logger.setLevel(Level.<your Level>);
247      * StreamHandler sh = new StreamHandler(System.out, new SimpleFormatter());
248      * sh.setLevel(logger.getLevel());
249      * logger.addHandler(sh);
250      * </pre>
251      *
252      * @return Logger
253      */

254     public static Logger JavaDoc getLogger(){
255         return Logger.getLogger(Utilities.class.getName());
256     }
257     
258     public static List JavaDoc<FileObject> getFilesOfNSInProj(Project prj, DocumentTypesEnum docType, String JavaDoc nameSpace, List JavaDoc<String JavaDoc> sourceGroupTypeList){
259         List JavaDoc<FileObject> result = new ArrayList JavaDoc<FileObject>();
260         Map JavaDoc<FileObject, String JavaDoc> fobj2nsMap = getFiles2NSMappingInProj(prj, docType, sourceGroupTypeList);
261         Set JavaDoc<FileObject> fileList = fobj2nsMap.keySet();
262         for(FileObject fobj: fileList){
263             if(Thread.currentThread().isInterrupted())
264                 //if interrupted by the client dump the result and immediately return
265
break;
266             if(fobj2nsMap.get(fobj).equals(nameSpace))
267                 result.add(fobj);
268         }
269         return result;
270     }
271     
272     public static List JavaDoc<FileObject> getFilesOfNoNSInProj(Project prj, DocumentTypesEnum docType, List JavaDoc<String JavaDoc> sourceGroupTypeList){
273         return getFilesOfNSInProj(prj, docType, NO_NAME_SPACE, sourceGroupTypeList);
274     }
275     
276     
277     public static Map JavaDoc<FileObject, String JavaDoc> getFiles2NSMappingInProj(Project prj, DocumentTypesEnum docType, List JavaDoc<String JavaDoc> sourceGroupTypeList){
278         Map JavaDoc<FileObject, String JavaDoc> result = new HashMap JavaDoc<FileObject, String JavaDoc>();
279         List JavaDoc<FileObject> rootList = getAllSourceRoots(prj, sourceGroupTypeList);
280         for(FileObject fob : rootList){
281             result.putAll(getFiles2NSMappingInProj(FileUtil.toFile(fob), docType));
282         }
283         return result;
284     }
285     
286     private static List JavaDoc<FileObject> getAllSourceRoots(Project prj, List JavaDoc<String JavaDoc> sourceGroupTypeList){
287         List JavaDoc<FileObject> result = new ArrayList JavaDoc<FileObject>();
288         for(String JavaDoc type: sourceGroupTypeList){
289             SourceGroup[] srcGrps = ProjectUtils.getSources(prj).getSourceGroups(type);
290             if(srcGrps != null){
291                 for(SourceGroup srcGrp : srcGrps)
292                     result.add(srcGrp.getRootFolder());
293             }
294         }
295         return result;
296     }
297     
298     public static Map JavaDoc<FileObject, String JavaDoc> getFiles2NSMappingInProj(File JavaDoc rootFile, DocumentTypesEnum docType){
299         List JavaDoc<File JavaDoc> fileList = getFilesWithExtension(rootFile, docType.toString(), new ArrayList JavaDoc<File JavaDoc>());
300         Map JavaDoc<FileObject, String JavaDoc> result = new HashMap JavaDoc<FileObject, String JavaDoc>();
301         String JavaDoc xpathQuery = null;
302         if(docType == docType.schema)
303             xpathQuery = "//xsd:schema/@targetNamespace";
304         else
305             xpathQuery = "//wsdl:definitions/@targetNamespace";
306         
307         for(File JavaDoc file: fileList){
308             if(Thread.currentThread().isInterrupted())
309                 //if interrupted by the client dump the result and immediately return
310
break;
311             List JavaDoc<String JavaDoc> targetNSList = null;
312             try {
313                 targetNSList = runXPathQuery(file, xpathQuery);
314                 String JavaDoc targetNS = null;
315                 FileObject fobj = FileUtil.toFileObject(file);
316                 if(targetNSList.size() > 0){
317                     //just take the first and ignore rest
318
targetNS = targetNSList.get(0);
319                 } else{
320                     targetNS = NO_NAME_SPACE;
321                 }
322                 if((docType == docType.wsdl) && (targetNS == NO_NAME_SPACE))
323                     //this is wsdl and it must have NS so ignore this file
324
continue;
325                 result.put(fobj, targetNS);
326             } catch (Exception JavaDoc ex) {
327                 //ex.printStackTrace();
328
//ignore this route
329
}
330         }
331         return result;
332     }
333     
334     
335     
336     public static List JavaDoc<File JavaDoc> getFilesWithExtension(File JavaDoc startFile, String JavaDoc fileExtension, List JavaDoc<File JavaDoc> curList) {
337         if(Thread.currentThread().isInterrupted())
338             //if interrupted by the client dump the result and immediately return
339
return curList;
340         if(curList == null)
341             curList = new ArrayList JavaDoc<File JavaDoc>();
342         if(startFile.isFile()){
343             int index = startFile.getName().lastIndexOf(".");
344             if(index != -1){
345                 String JavaDoc extn = startFile.getName().substring(index+1);
346                 if((extn != null) && (extn.equalsIgnoreCase(fileExtension)))
347                     curList.add(startFile);
348             }
349         }
350         if(startFile.isDirectory()){
351             File JavaDoc[] children = startFile.listFiles();
352             if(children != null){
353                 for(File JavaDoc child: children){
354                     getFilesWithExtension(child, fileExtension, curList);
355                 }
356             }
357         }
358         return curList;
359     }
360     
361     public static List JavaDoc<String JavaDoc> runXPathQuery(File JavaDoc parsedFile, String JavaDoc xpathExpr) throws Exception JavaDoc{
362         List JavaDoc<String JavaDoc> result = new ArrayList JavaDoc<String JavaDoc>();
363         XPath JavaDoc xpath = XPathFactory.newInstance().newXPath();
364         xpath.setNamespaceContext(getNamespaceContext());
365         
366         InputSource JavaDoc inputSource = new InputSource JavaDoc(new FileInputStream JavaDoc(parsedFile));
367         NodeList JavaDoc nodes = (NodeList JavaDoc) xpath.evaluate(xpathExpr, inputSource, XPathConstants.NODESET);
368         if((nodes != null) && (nodes.getLength() > 0)){
369             for(int i=0; i<nodes.getLength();i++){
370                 Node JavaDoc node = nodes.item(i);
371                 result.add(node.getNodeValue());
372             }
373         }
374         return result;
375     }
376     
377     private static Map JavaDoc<String JavaDoc, String JavaDoc> namespaces = new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
378     private static Map JavaDoc<String JavaDoc, String JavaDoc> prefixes = new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
379     
380     private static NamespaceContext JavaDoc getNamespaceContext() {
381         //schema related
382
namespaces.put("xsd","http://www.w3.org/2001/XMLSchema");
383         prefixes.put("http://www.w3.org/2001/XMLSchema", "xsd");
384         
385         //wsdl related
386
namespaces.put("wsdl", "http://schemas.xmlsoap.org/wsdl/");
387         prefixes.put("http://schemas.xmlsoap.org/wsdl/", "wsdl");
388         return new HashNamespaceResolver(namespaces, prefixes);
389     }
390     
391     public static int countPushdownFolders(URI JavaDoc master, URI JavaDoc slave) {
392         String JavaDoc masterStr = master.toString();
393         String JavaDoc slaveStr = slave.toString();
394         StringTokenizer JavaDoc masterTok = new StringTokenizer JavaDoc(masterStr, "/");
395         StringTokenizer JavaDoc slaveTok = new StringTokenizer JavaDoc(slaveStr, "/");
396         String JavaDoc masterLast = null;
397         String JavaDoc slaveLast = null;
398         while(true){
399             if(masterTok.hasMoreTokens() && slaveTok.hasMoreTokens()){
400                 masterLast = masterTok.nextToken();
401                 slaveLast = slaveTok.nextToken();
402                 if(masterLast.equals(slaveLast))
403                     continue;
404                 else
405                     break;
406             }
407             break;
408         }
409         //count number of ../'es
410
return slaveTok.countTokens()+1;
411     }
412     
413     public static File JavaDoc downloadURLAndSave(URL JavaDoc downloadURL, File JavaDoc saveFile) throws IOException JavaDoc{
414         return downloadURLUsingProxyAndSave(downloadURL, null, saveFile);
415     }
416     
417     
418     public static File JavaDoc downloadURLUsingProxyAndSave(URL JavaDoc downloadURL, Proxy JavaDoc proxy, File JavaDoc saveFile) throws IOException JavaDoc{
419         IOException JavaDoc expn = null;
420         URLConnection JavaDoc ucn = null;
421         
422         if(Thread.currentThread().isInterrupted())
423             return null;
424         if(proxy != null)
425             ucn = downloadURL.openConnection(proxy);
426         else
427             ucn = downloadURL.openConnection();
428         
429         if(Thread.currentThread().isInterrupted())
430             return null;
431         ucn.connect();
432         
433         int fileLen = ucn.getContentLength();
434         byte buffer[] = new byte[1024];
435         BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(ucn.getInputStream());
436         saveFile.getParentFile().mkdirs();
437         BufferedOutputStream JavaDoc bos = null;
438         try {
439             bos = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(saveFile));
440         } catch (FileNotFoundException JavaDoc ex) {
441             bis.close();
442             throw ex;
443         }
444         int curLen = 0;
445         while( curLen < fileLen){
446             try {
447                 if(Thread.currentThread().isInterrupted())
448                     break;
449                 Thread.sleep(100);
450             } catch (InterruptedException JavaDoc ex) {}
451             try{
452                 int readLen = bis.available();
453                 int len = bis.read(buffer, 0, (readLen>buffer.length)?buffer.length:readLen);
454                 bos.write(buffer, 0, len);
455                 curLen += len;
456             }catch (IOException JavaDoc e){
457                 expn = e;
458                 break;
459             }
460         }
461         try {
462             bis.close();
463         } catch (IOException JavaDoc ex) {
464             //cant do much: ignore
465
}
466         try {
467             bos.close();
468         } catch (IOException JavaDoc ex) {
469             //cant do much: ignore
470
}
471         if(expn != null)
472             throw expn;
473         return saveFile;
474     }
475     
476     public static InputStream JavaDoc getInputStreamOfURL(URL JavaDoc downloadURL, Proxy JavaDoc proxy) throws IOException JavaDoc {
477         
478         URLConnection JavaDoc ucn = null;
479         
480         if(Thread.currentThread().isInterrupted())
481             return null;
482         if(proxy != null)
483             ucn = downloadURL.openConnection(proxy);
484         else
485             ucn = downloadURL.openConnection();
486         
487         if(Thread.currentThread().isInterrupted())
488             return null;
489         ucn.connect();
490         
491         return ucn.getInputStream();
492         
493     }
494     
495     public static Document JavaDoc getDocument(FileObject modelSourceFileObject){
496         Document JavaDoc result = null;
497         try {
498             DataObject dObject = DataObject.find(modelSourceFileObject);
499             EditorCookie ec = (EditorCookie)dObject.getCookie(EditorCookie.class);
500             Document JavaDoc doc = ec.openDocument();
501             if(doc instanceof BaseDocument)
502                 return doc;
503             
504             
505             result = new org.netbeans.editor.BaseDocument(
506                     org.netbeans.modules.xml.text.syntax.XMLKit.class, false);
507             String JavaDoc str = doc.getText(0, doc.getLength());
508             result.insertString(0,str,null);
509             
510         } catch (Exception JavaDoc dObjEx) {
511             return null;
512         }
513         return result;
514     }
515     
516     private static Document JavaDoc _getDocument(DataObject modelSourceDataObject)
517             throws IOException JavaDoc {
518         Document JavaDoc result = null;
519         if (modelSourceDataObject != null && modelSourceDataObject.isValid()) {
520             EditorCookie ec = (EditorCookie)
521             modelSourceDataObject.getCookie(EditorCookie.class);
522             assert ec != null : "Data object "+modelSourceDataObject.getPrimaryFile().getPath()+" has no editor cookies.";
523             Document JavaDoc doc = null;
524             try {
525                 doc = ec.openDocument();
526             } catch (UserQuestionException uce) {
527                 // this exception is thrown if the document is to large
528
// lets just confirm that it is ok
529
uce.confirmed();
530                 doc = ec.openDocument();
531             }
532             assert(doc instanceof BaseDocument);
533             result = doc;
534         }
535         return result;
536     }
537     
538     /**
539      * This method must be overridden by the Unit testcase to return a special
540      * Document object for a FileObject.
541      */

542     protected static Document JavaDoc _getDocument(FileObject modelSourceFileObject)
543     throws DataObjectNotFoundException, IOException JavaDoc {
544     DataObject dObject = DataObject.find(modelSourceFileObject);
545     return _getDocument(dObject);
546     }
547     
548     private static CatalogWriteModel testCatalogModel = null;
549     public static CatalogWriteModel getTestCatalogWriteModel() throws IOException JavaDoc{
550         if(testCatalogModel == null){
551             CatalogWriteModel cm = new CatalogWriteModelImpl(new File JavaDoc(System.getProperty("java.io.tmpdir")));
552             File JavaDoc file = FileUtil.toFile(cm.getCatalogFileObject());
553             file.deleteOnExit();
554             return cm;
555         }
556         return testCatalogModel;
557     }
558     
559     
560     public static FileObject getProjectCatalogFileObject(Project prj) throws IOException JavaDoc {
561         if(prj == null)
562             return null;
563         
564         FileObject result = null;
565         FileObject myProjectRootFileObject = prj.getProjectDirectory();
566        
567         //see if this prj has XMLCatalogProvider. If yes use it.
568
XMLCatalogProvider catProv = (XMLCatalogProvider) prj.getLookup().
569                 lookup(XMLCatalogProvider.class);
570         if(catProv != null){
571             URI JavaDoc caturi = catProv.getProjectWideCatalog();
572             if(caturi != null){
573                 caturi = FileUtil.toFile(myProjectRootFileObject).toURI().resolve(caturi);
574                 File JavaDoc catFile = new File JavaDoc(caturi);
575                 if(!catFile.isFile()){
576                     catFile.createNewFile();
577                 }
578                 result = FileUtil.toFileObject(FileUtil.normalizeFile(catFile));
579             }
580         }
581         
582         if(result == null){
583             String JavaDoc fileName = CatalogWriteModel.PUBLIC_CATALOG_FILE_NAME+CatalogWriteModel.CATALOG_FILE_EXTENSION;
584             result = myProjectRootFileObject.getFileObject(fileName);
585             if(result == null){
586                 result = myProjectRootFileObject.createData(fileName);
587             }
588         }
589         return result;
590     }
591     
592     public static FileObject getFileObject(ModelSource ms){
593         return (FileObject) ms.getLookup().lookup(FileObject.class);
594     }
595     
596     public static CatalogModel getCatalogModel(ModelSource ms) throws CatalogModelException{
597         return CatalogModelFactory.getDefault().getCatalogModel(ms);
598     }
599     
600     public static ModelSource getModelSource(FileObject bindingHandlerFO, boolean editable){
601         try {
602             return createModelSource(bindingHandlerFO, editable);
603         } catch (CatalogModelException ex) {
604             return null;
605         }
606     }
607     
608     /**
609      * This method could be overridden by the Unit testcase to return a special
610      * ModelSource object for a FileObject with custom impl of classes added to the lookup.
611      * This is optional if both getDocument(FO) and createCatalogModel(FO) are overridden.
612      */

613     public static ModelSource createModelSource(FileObject thisFileObj,
614             boolean editable) throws CatalogModelException{
615         assert thisFileObj != null : "Null file object.";
616         final CatalogModel catalogModel = createCatalogModel(thisFileObj);
617         final DataObject dobj;
618         try {
619             dobj = DataObject.find(thisFileObj);
620         } catch (DataObjectNotFoundException ex) {
621             throw new CatalogModelException(ex);
622         }
623         Lookup proxyLookup = Lookups.proxy(
624                 new Lookup.Provider() {
625             public Lookup getLookup() {
626                 Document JavaDoc document = null;
627                 try {
628                     document = _getDocument(dobj);
629                     if (document != null) {
630                         return Lookups.fixed(new Object JavaDoc[] {
631                             dobj.getPrimaryFile(),
632                             document,
633                             dobj,
634                             DataObjectAdapters.source(dobj),
635                             catalogModel
636                         });
637                     } else {
638                         return Lookups.fixed(new Object JavaDoc[] {
639                             dobj.getPrimaryFile(),
640                             dobj,
641                             catalogModel
642                         });
643                     }
644                 } catch (IOException JavaDoc ioe) {
645                     logger.log(Level.SEVERE, ioe.getMessage());
646                     return Lookups.fixed(new Object JavaDoc[] {
647                         dobj,
648                         catalogModel
649                     });
650                 }
651             }
652         }
653         );
654         
655         return new ModelSource(proxyLookup, editable);
656     }
657     
658     
659     /**
660      * This method could be overridden by the Unit testcase to return a special
661      * ModelSource object for a FileObject with custom impl of classes added to the lookup.
662      * This is optional if both getDocument(FO) and createCatalogModel(FO) are overridden.
663      */

664     /*public static ModelSource createModelSource(final FileObject thisFileObj,
665         boolean editable) throws CatalogModelException{
666         assert thisFileObj != null : "Null file object.";
667         final CatalogModel catalogModel = createCatalogModel(thisFileObj);
668         final DataObject dobj;
669         try {
670             dobj = DataObject.find(thisFileObj);
671         } catch (DataObjectNotFoundException ex) {
672             throw new CatalogModelException(ex);
673         }
674      
675         ProxyLookup myLookup = new ProxyLookup() {
676             protected void beforeLookup(Lookup.Template template) {
677                 if (Document.class.isAssignableFrom(template.getType())) {
678                     Lookup l = Lookup.EMPTY;
679                     try {
680                         Document d = _getDocument(thisFileObj);
681                         l = Lookups.singleton(d);
682                     } catch (DataObjectNotFoundException ex) {
683                         getLogger().log(Level.SEVERE, "Can't load data object from "+thisFileObj.getPath());
684                     } catch (IOException ex) {
685                         getLogger().log(Level.SEVERE, ex.getMessage());
686                     }
687      
688                     setLookups(new Lookup[]{l});
689                 } else if (Source.class.isAssignableFrom(template.getType())) {
690                     setLookups(new Lookup[]{Lookups.singleton(DataObjectAdapters.source(dobj))});
691                 } else {
692                     Lookup l = Lookups.fixed(new Object[] {
693                         thisFileObj,
694                         dobj,
695                         catalogModel
696                     });
697                     setLookups(new Lookup[]{l});
698                 }
699             }
700         };
701      
702         return new ModelSource(myLookup, editable);
703     }*/

704     
705     
706     
707     
708     public static CatalogModel createCatalogModel(FileObject fo) throws CatalogModelException{
709         return new CatalogModelFactoryImpl().getCatalogModel(fo);
710     }
711     
712     public static void printMemoryUsage(String JavaDoc str){
713         long init = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getInit();
714         long cur = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
715         long max = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax();
716         System.out.printf("%s:\n@@@@@@MEMORY: %d/%d/%d\n",str, (init/(1024*1024)), (cur/(1024*1024)), (max/(1024*1024)));
717     }
718     
719     public static final String JavaDoc DEFAULT_PRIVATE_CATALOG_URI_STR = "private/cache/retriever/catalog.xml";
720     public static final String JavaDoc DEFAULT_PRIVATE_CAHCE_URI_STR = "private/cache/retriever";
721     
722     public static final String JavaDoc PRIVATE_CATALOG_URI_STR = "retriever/catalog.xml";
723     public static final String JavaDoc PRIVATE_CAHCE_URI_STR = "retriever";
724     
725     
726     
727     public static boolean retrieveAndCache(URI JavaDoc locationURI, FileObject sourceFileObject) {
728         URI JavaDoc privateCatalogURI = null;
729         URI JavaDoc privateCacheURI = null;
730         
731         Project prj = FileOwnerQuery.getOwner(sourceFileObject);
732         if(prj == null)
733             return false;
734         
735         FileObject prjrtfo = prj.getProjectDirectory();
736         File JavaDoc prjrt = FileUtil.toFile(prjrtfo);
737         if(prjrt == null)
738             return false;
739         
740         //determine the cache dir
741
CacheDirectoryProvider cdp = (CacheDirectoryProvider) prj.getLookup().
742                 lookup(CacheDirectoryProvider.class);
743         String JavaDoc catalogstr = DEFAULT_PRIVATE_CATALOG_URI_STR;
744         String JavaDoc cachestr = DEFAULT_PRIVATE_CAHCE_URI_STR;
745         try{
746             if( (cdp != null) && (cdp.getCacheDirectory() != null) ){
747                 URI JavaDoc prjrturi = prjrt.toURI();
748                 URI JavaDoc cpduri = FileUtil.toFile(cdp.getCacheDirectory()).toURI();
749                 String JavaDoc cachedirstr = Utilities.relativize(prjrturi, cpduri);
750                 catalogstr = cachedirstr+"/"+PRIVATE_CATALOG_URI_STR;
751                 cachestr = cachedirstr+"/"+PRIVATE_CAHCE_URI_STR;
752             }
753             privateCatalogURI = new URI JavaDoc(catalogstr);
754             privateCacheURI = new URI JavaDoc(cachestr);
755         }catch(Exception JavaDoc e){
756             return false;
757         }
758         
759         //retrieve
760
URI JavaDoc cacheURI = prjrt.toURI().resolve(privateCacheURI);
761         File JavaDoc cacheFile = new File JavaDoc(cacheURI);
762         if(!cacheFile.isDirectory())
763             cacheFile.mkdirs();
764         FileObject cacheFO = FileUtil.toFileObject(FileUtil.normalizeFile(cacheFile));
765         if(cacheFO == null)
766             return false;
767         Retriever ret = Retriever.getDefault();
768         FileObject result;
769         try {
770             ((RetrieverImpl) ret).startNewThread = true;
771             result = ret.retrieveResource(cacheFO, privateCatalogURI, locationURI);
772         } catch (UnknownHostException JavaDoc ex) {
773             result = null;
774         } catch (IOException JavaDoc ex) {
775             result = null;
776         } catch (URISyntaxException JavaDoc ex) {
777             result = null;
778         }
779         
780         /*if(result == null)
781             return false;*/

782         
783         //add private catalog as next catalog file to the public and peer catalog
784
XMLCatalogProvider catProv = (XMLCatalogProvider) prj.getLookup().
785                 lookup(XMLCatalogProvider.class);
786         FileObject publicCatFO = null;
787         FileObject peerCatFO = null;
788         if(catProv != null){
789             
790             //get public catalog
791
URI JavaDoc publicCatURI = catProv.getProjectWideCatalog();
792             if(publicCatURI != null){
793                 URI JavaDoc pubcatURI = prjrt.toURI().resolve(publicCatURI);
794                 if(pubcatURI != null){
795                     File JavaDoc pubcatFile = new File JavaDoc(pubcatURI);
796                     if(!pubcatFile.isFile())
797                         try {
798                             pubcatFile.createNewFile();
799                         } catch (IOException JavaDoc ex) {
800                         }
801                     publicCatFO = FileUtil.toFileObject(FileUtil.
802                             normalizeFile(pubcatFile));
803                 }
804             }
805             
806             //get peer catalog
807
URI JavaDoc peerCatURI = catProv.getCatalog(sourceFileObject);
808             if(peerCatURI != null){
809                 URI JavaDoc peercatURI = prjrt.toURI().resolve(peerCatURI);
810                 if(peercatURI != null){
811                     File JavaDoc peercatFile = new File JavaDoc(peercatURI);
812                     if(!peercatFile.isFile())
813                         try {
814                             peercatFile.createNewFile();
815                         } catch (IOException JavaDoc ex) {
816                         }
817                     peerCatFO = FileUtil.toFileObject(FileUtil.
818                             normalizeFile(peercatFile));
819                 }
820             }
821         }
822         //get the catalog write model
823
//add next cat entry to public catalog
824
URI JavaDoc cacheCatFullURI = FileUtil.toFile(prjrtfo).toURI().resolve(privateCatalogURI);
825         CatalogWriteModel catWriter = null;
826         try {
827             if(publicCatFO == null){
828                 //get the public catalog legacy way
829
catWriter = CatalogWriteModelFactory.getInstance().
830                         getCatalogWriteModelForProject(sourceFileObject);
831             } else{
832                 catWriter = CatalogWriteModelFactory.getInstance().
833                         getCatalogWriteModelForCatalogFile(publicCatFO);
834             }
835         } catch (CatalogModelException ex) {}
836         if(catWriter == null){
837             //return true. May be public cat had the priv cat entry already
838
return true;
839         }
840         try {
841             catWriter.addNextCatalog(cacheCatFullURI, true);
842         } catch (IOException JavaDoc ex) {
843         }
844         
845         //add the next cat entry to peer catalog
846
if(publicCatFO != peerCatFO){
847             //get the catalog write model
848
catWriter = null;
849             try {
850                 if(peerCatFO == null){
851                     //get the public catalog legacy way
852
catWriter = CatalogWriteModelFactory.getInstance().
853                             getCatalogWriteModelForProject(sourceFileObject);
854                 } else{
855                     catWriter = CatalogWriteModelFactory.getInstance().
856                             getCatalogWriteModelForCatalogFile(peerCatFO);
857                 }
858             } catch (CatalogModelException ex) {}
859             if(catWriter == null){
860                 //return true. May be public cat had the priv cat entry already
861
return true;
862             }
863             try {
864                 catWriter.addNextCatalog(cacheCatFullURI, true);
865             } catch (IOException JavaDoc ex) {
866             }
867         }
868         return true;
869     }
870     
871     public enum DocumentTypesEnum {
872         schema,
873         wsdl;
874         
875         public String JavaDoc toString(){
876             if(name().equals("schema"))
877                 return "xsd";
878             else
879                 return name();
880         }
881     }
882     
883     
884     public static final class HashNamespaceResolver implements NamespaceContext JavaDoc {
885         private Map JavaDoc<String JavaDoc, String JavaDoc> prefixes; // namespace, prefix
886
private Map JavaDoc<String JavaDoc, String JavaDoc> namespaces; // prefix, namespace
887

888         public HashNamespaceResolver(Map JavaDoc<String JavaDoc,String JavaDoc> nsTable) {
889             namespaces = nsTable;
890             prefixes = new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
891             for (Entry<String JavaDoc,String JavaDoc> e : namespaces.entrySet()) {
892                 prefixes.put(e.getValue(), e.getKey());
893             }
894         }
895         
896         public HashNamespaceResolver(Map JavaDoc<String JavaDoc,String JavaDoc> namespaces, Map JavaDoc<String JavaDoc,String JavaDoc> prefixes) {
897             this.namespaces = namespaces;
898             this.prefixes = prefixes;
899         }
900         
901         public Iterator JavaDoc getPrefixes(String JavaDoc namespaceURI) {
902             return Collections.singletonList(getPrefix(namespaceURI)).iterator();
903         }
904         
905         public String JavaDoc getPrefix(String JavaDoc namespaceURI) {
906             return prefixes.get(namespaceURI);
907         }
908         
909         public String JavaDoc getNamespaceURI(String JavaDoc prefix) {
910             return namespaces.get(prefix);
911         }
912     }
913 }
914
Popular Tags