001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041:
042: package org.netbeans.modules.xml.retriever.catalog;
043:
044: import java.io.BufferedInputStream;
045: import java.io.BufferedOutputStream;
046: import java.io.File;
047: import java.io.FileInputStream;
048: import java.io.FileNotFoundException;
049: import java.io.FileOutputStream;
050: import java.io.IOException;
051: import java.io.InputStream;
052: import java.io.UnsupportedEncodingException;
053: import java.net.MalformedURLException;
054: import java.net.Proxy;
055: import java.net.URI;
056: import java.net.URISyntaxException;
057: import java.net.URL;
058: import java.net.URLConnection;
059: import java.util.ArrayList;
060: import java.util.Collections;
061: import java.util.HashMap;
062: import java.util.Iterator;
063: import java.util.List;
064: import java.util.Map;
065: import java.util.Map.Entry;
066: import java.util.Set;
067: import java.util.StringTokenizer;
068: import java.util.logging.Level;
069: import java.util.logging.Logger;
070: import javax.swing.text.Document;
071: import javax.xml.namespace.NamespaceContext;
072: import javax.xml.xpath.XPath;
073: import javax.xml.xpath.XPathConstants;
074: import javax.xml.xpath.XPathFactory;
075: import org.netbeans.api.project.Project;
076: import org.netbeans.api.project.ProjectUtils;
077: import org.netbeans.api.project.SourceGroup;
078: import org.netbeans.editor.BaseDocument;
079: import org.netbeans.modules.xml.retriever.XMLCatalogProvider;
080: import org.netbeans.modules.xml.retriever.catalog.impl.*;
081: import org.netbeans.modules.xml.retriever.catalog.impl.XAMCatalogWriteModelImpl;
082: import org.netbeans.modules.xml.retriever.impl.Util;
083: import org.netbeans.modules.xml.xam.ModelSource;
084: import org.netbeans.modules.xml.xam.locator.CatalogModel;
085: import org.netbeans.modules.xml.xam.locator.CatalogModelException;
086: import org.netbeans.modules.xml.xam.locator.CatalogModelFactory;
087: import org.netbeans.spi.xml.cookies.DataObjectAdapters;
088: import org.openide.cookies.EditorCookie;
089: import org.openide.filesystems.FileObject;
090: import org.openide.filesystems.FileUtil;
091: import org.openide.loaders.DataObject;
092: import org.openide.loaders.DataObjectNotFoundException;
093: import org.openide.util.Lookup;
094: import org.openide.util.UserQuestionException;
095: import org.openide.util.lookup.Lookups;
096: import org.w3c.dom.Node;
097: import org.w3c.dom.NodeList;
098: import org.xml.sax.InputSource;
099:
100: /**
101: *
102: * @author girix
103: */
104: public class Utilities {
105: public static final String NO_NAME_SPACE = "NO_NAME_SPACE"; //NOI18N
106: private static final Logger logger = Logger
107: .getLogger(Utilities.class.getName());
108:
109: public static URL appendURL(URL prefixURL, String suffixStr) {
110: String str = prefixURL.toString();
111: String newurl = null;
112: if (str.endsWith("/"))
113: newurl = str + suffixStr;
114: else
115: newurl = str + "/" + suffixStr;
116: try {
117: return new URL(newurl);
118: } catch (MalformedURLException ex) {
119: }
120: return null;
121: }
122:
123: public static boolean localResourceExists(URL localURL) {
124: File locaFile = null;
125: try {
126: locaFile = new File(localURL.toURI());
127: return locaFile.exists();
128: } catch (URISyntaxException ex) {
129: }
130: return false;
131:
132: }
133:
134: public static File toFile(URL url) {
135: URI uri;
136: try {
137: uri = url.toURI();
138: } catch (URISyntaxException ex) {
139: return null;
140: }
141: return new File(uri);
142: }
143:
144: public static void deleteRecursively(File aDir) {
145: if (aDir.isDirectory()) {
146: //get all children and delete them too
147: File[] children = aDir.listFiles();
148: for (File file : children)
149: deleteRecursively(file);
150: //System.out.printf("Deleting: %s (%s)\n", aDir.getAbsolutePath(), (aDir.isFile())?"File":"Dir");
151: aDir.delete();
152: } else {
153: //normal file just delete
154: //System.out.printf("Deleting: %s (%s)\n", aDir.getAbsolutePath(), (aDir.isFile())?"File":"Dir");
155: aDir.delete();
156: }
157: }
158:
159: public static String normalizeURI(String uriref) {
160: StringBuilder newRef = new StringBuilder();
161: byte[] bytes;
162:
163: if (uriref == null) {
164: return null;
165: }
166:
167: try {
168: bytes = uriref.getBytes("UTF-8");
169: } catch (UnsupportedEncodingException uee) {
170: // this can't happen
171: return uriref;
172: }
173:
174: for (int count = 0; count < bytes.length; count++) {
175: int ch = bytes[count] & 0xFF;
176:
177: if ((ch <= 0x20) // ctrl
178: || (ch > 0x7F) // high ascii
179: || (ch == 0x22) // "
180: || (ch == 0x3C) // <
181: || (ch == 0x3E) // >
182: || (ch == 0x5C) // \
183: || (ch == 0x5E) // ^
184: || (ch == 0x60) // `
185: || (ch == 0x7B) // {
186: || (ch == 0x7C) // |
187: || (ch == 0x7D) // }
188: || (ch == 0x7F)) {
189: newRef.append(encodedByte(ch));
190: } else {
191: newRef.append((char) bytes[count]);
192: }
193: }
194:
195: return newRef.toString();
196: }
197:
198: public static String encodedByte(int b) {
199: String hex = Integer.toHexString(b).toUpperCase();
200: if (hex.length() < 2) {
201: return "%0" + hex;
202: } else {
203: return "%" + hex;
204: }
205: }
206:
207: /**
208: * This method will work ONLY for the files that are there in the local file system and
209: * that have common URI up to server level.
210: * Result is a relative URI of the slave file WRT the master file
211: */
212: public static String relativize(URI master, URI slave) {
213: String masterStr = master.toString();
214: String slaveStr = slave.toString();
215: StringTokenizer masterTok = new StringTokenizer(masterStr, "/");
216: StringTokenizer slaveTok = new StringTokenizer(slaveStr, "/");
217: String masterLast = null;
218: String slaveLast = null;
219: int iteration = -1;
220: while (true) {
221: iteration++;
222: if (masterTok.hasMoreTokens() && slaveTok.hasMoreTokens()) {
223: masterLast = masterTok.nextToken();
224: slaveLast = slaveTok.nextToken();
225: if (masterLast.equals(slaveLast))
226: continue;
227: else
228: break;
229: }
230: break;
231: }
232: //if even the server part is changing then just return the slave totally as absoulte URI
233: if (iteration < 2)
234: return slave.toString();
235: //count number of ../'es
236: int dirCount = masterTok.countTokens();
237: //generate prefix
238: String pathPrefix = "";
239: StringBuffer pathPrefixBuff = new StringBuffer("");
240: for (int i = 0; i < dirCount; i++) {
241: pathPrefixBuff.append("../");
242: }
243: pathPrefix = pathPrefixBuff.toString();
244: //collect rest of slave tokens
245: StringBuilder slaveResult = masterLast.equals(slaveLast) ? new StringBuilder()
246: : new StringBuilder(slaveLast);
247: while (slaveTok.hasMoreTokens()) {
248: if (slaveResult.length() != 0)
249: slaveResult.append('/');
250: slaveResult.append(slaveTok.nextToken());
251: }
252: //add prefix to slaveStr
253: return pathPrefix + slaveResult.toString();
254: }
255:
256: public static List<FileObject> getFilesOfNSInProj(Project prj,
257: DocumentTypesEnum docType, String nameSpace,
258: List<String> sourceGroupTypeList) {
259: List<FileObject> result = new ArrayList<FileObject>();
260: Map<FileObject, String> fobj2nsMap = getFiles2NSMappingInProj(
261: prj, docType, sourceGroupTypeList);
262: Set<FileObject> fileList = fobj2nsMap.keySet();
263: for (FileObject fobj : fileList) {
264: if (Thread.currentThread().isInterrupted())
265: //if interrupted by the client dump the result and immediately return
266: break;
267: if (fobj2nsMap.get(fobj).equals(nameSpace))
268: result.add(fobj);
269: }
270: return result;
271: }
272:
273: public static List<FileObject> getFilesOfNoNSInProj(Project prj,
274: DocumentTypesEnum docType, List<String> sourceGroupTypeList) {
275: return getFilesOfNSInProj(prj, docType, NO_NAME_SPACE,
276: sourceGroupTypeList);
277: }
278:
279: public static Map<FileObject, String> getFiles2NSMappingInProj(
280: Project prj, DocumentTypesEnum docType,
281: List<String> sourceGroupTypeList) {
282: Map<FileObject, String> result = new HashMap<FileObject, String>();
283: List<FileObject> rootList = getAllSourceRoots(prj,
284: sourceGroupTypeList);
285: for (FileObject fob : rootList) {
286: result.putAll(getFiles2NSMappingInProj(
287: FileUtil.toFile(fob), docType));
288: }
289: return result;
290: }
291:
292: private static List<FileObject> getAllSourceRoots(Project prj,
293: List<String> sourceGroupTypeList) {
294: List<FileObject> result = new ArrayList<FileObject>();
295: for (String type : sourceGroupTypeList) {
296: SourceGroup[] srcGrps = ProjectUtils.getSources(prj)
297: .getSourceGroups(type);
298: if (srcGrps != null) {
299: for (SourceGroup srcGrp : srcGrps)
300: result.add(srcGrp.getRootFolder());
301: }
302: }
303: return result;
304: }
305:
306: public static Map<FileObject, String> getFiles2NSMappingInProj(
307: File rootFile, DocumentTypesEnum docType) {
308: List<File> fileList = getFilesWithExtension(rootFile, docType
309: .toString(), new ArrayList<File>());
310: Map<FileObject, String> result = new HashMap<FileObject, String>();
311: String xpathQuery = null;
312: if (docType == docType.schema)
313: xpathQuery = "//xsd:schema/@targetNamespace";
314: else
315: xpathQuery = "//wsdl:definitions/@targetNamespace";
316:
317: for (File file : fileList) {
318: if (Thread.currentThread().isInterrupted())
319: //if interrupted by the client dump the result and immediately return
320: break;
321: List<String> targetNSList = null;
322: try {
323: targetNSList = runXPathQuery(file, xpathQuery);
324: String targetNS = null;
325: FileObject fobj = FileUtil.toFileObject(file);
326: if (targetNSList.size() > 0) {
327: //just take the first and ignore rest
328: targetNS = targetNSList.get(0);
329: } else {
330: targetNS = NO_NAME_SPACE;
331: }
332: if ((docType == docType.wsdl)
333: && (targetNS == NO_NAME_SPACE))
334: //this is wsdl and it must have NS so ignore this file
335: continue;
336: result.put(fobj, targetNS);
337: } catch (Exception ex) {
338: //ex.printStackTrace();
339: //ignore this route
340: }
341: }
342: return result;
343: }
344:
345: public static List<File> getFilesWithExtension(File startFile,
346: String fileExtension, List<File> curList) {
347: if (Thread.currentThread().isInterrupted())
348: //if interrupted by the client dump the result and immediately return
349: return curList;
350: if (curList == null)
351: curList = new ArrayList<File>();
352: if (startFile.isFile()) {
353: int index = startFile.getName().lastIndexOf(".");
354: if (index != -1) {
355: String extn = startFile.getName().substring(index + 1);
356: if ((extn != null)
357: && (extn.equalsIgnoreCase(fileExtension)))
358: curList.add(startFile);
359: }
360: }
361: if (startFile.isDirectory()) {
362: File[] children = startFile.listFiles();
363: if (children != null) {
364: for (File child : children) {
365: getFilesWithExtension(child, fileExtension, curList);
366: }
367: }
368: }
369: return curList;
370: }
371:
372: public static List<String> runXPathQuery(File parsedFile,
373: String xpathExpr) throws Exception {
374: List<String> result = new ArrayList<String>();
375: XPath xpath = XPathFactory.newInstance().newXPath();
376: xpath.setNamespaceContext(getNamespaceContext());
377:
378: InputSource inputSource = new InputSource(new FileInputStream(
379: parsedFile));
380: NodeList nodes = (NodeList) xpath.evaluate(xpathExpr,
381: inputSource, XPathConstants.NODESET);
382: if ((nodes != null) && (nodes.getLength() > 0)) {
383: for (int i = 0; i < nodes.getLength(); i++) {
384: Node node = nodes.item(i);
385: result.add(node.getNodeValue());
386: }
387: }
388: return result;
389: }
390:
391: private static Map<String, String> namespaces = new HashMap<String, String>();
392: private static Map<String, String> prefixes = new HashMap<String, String>();
393:
394: private static NamespaceContext getNamespaceContext() {
395: //schema related
396: namespaces.put("xsd", "http://www.w3.org/2001/XMLSchema");
397: prefixes.put("http://www.w3.org/2001/XMLSchema", "xsd");
398:
399: //wsdl related
400: namespaces.put("wsdl", "http://schemas.xmlsoap.org/wsdl/");
401: prefixes.put("http://schemas.xmlsoap.org/wsdl/", "wsdl");
402: return new HashNamespaceResolver(namespaces, prefixes);
403: }
404:
405: public static int countPushdownFolders(URI master, URI slave) {
406: String masterStr = master.toString();
407: String slaveStr = slave.toString();
408: StringTokenizer masterTok = new StringTokenizer(masterStr, "/");
409: StringTokenizer slaveTok = new StringTokenizer(slaveStr, "/");
410: String masterLast = null;
411: String slaveLast = null;
412: while (true) {
413: if (masterTok.hasMoreTokens() && slaveTok.hasMoreTokens()) {
414: masterLast = masterTok.nextToken();
415: slaveLast = slaveTok.nextToken();
416: if (masterLast.equals(slaveLast))
417: continue;
418: else
419: break;
420: }
421: break;
422: }
423: //count number of ../'es
424: return slaveTok.countTokens() + 1;
425: }
426:
427: public static File downloadURLAndSave(URL downloadURL, File saveFile)
428: throws IOException {
429: return downloadURLUsingProxyAndSave(downloadURL, null, saveFile);
430: }
431:
432: public static File downloadURLUsingProxyAndSave(URL downloadURL,
433: Proxy proxy, File saveFile) throws IOException {
434: IOException expn = null;
435: URLConnection ucn = null;
436:
437: if (Thread.currentThread().isInterrupted())
438: return null;
439: if (proxy != null)
440: ucn = downloadURL.openConnection(proxy);
441: else
442: ucn = downloadURL.openConnection();
443:
444: if (Thread.currentThread().isInterrupted())
445: return null;
446: ucn.connect();
447:
448: int fileLen = ucn.getContentLength();
449: byte buffer[] = new byte[1024];
450: BufferedInputStream bis = new BufferedInputStream(ucn
451: .getInputStream());
452: saveFile.getParentFile().mkdirs();
453: BufferedOutputStream bos = null;
454: try {
455: bos = new BufferedOutputStream(new FileOutputStream(
456: saveFile));
457: } catch (FileNotFoundException ex) {
458: bis.close();
459: throw ex;
460: }
461: int curLen = 0;
462: while (curLen < fileLen) {
463: try {
464: if (Thread.currentThread().isInterrupted())
465: break;
466: Thread.sleep(100);
467: } catch (InterruptedException ex) {
468: }
469: try {
470: int readLen = bis.available();
471: int len = bis.read(buffer, 0,
472: (readLen > buffer.length) ? buffer.length
473: : readLen);
474: bos.write(buffer, 0, len);
475: curLen += len;
476: } catch (IOException e) {
477: expn = e;
478: break;
479: }
480: }
481: try {
482: bis.close();
483: } catch (IOException ex) {
484: //cant do much: ignore
485: }
486: try {
487: bos.close();
488: } catch (IOException ex) {
489: //cant do much: ignore
490: }
491: if (expn != null)
492: throw expn;
493: return saveFile;
494: }
495:
496: public static InputStream getInputStreamOfURL(URL downloadURL,
497: Proxy proxy) throws IOException {
498:
499: URLConnection ucn = null;
500:
501: if (Thread.currentThread().isInterrupted())
502: return null;
503: if (proxy != null)
504: ucn = downloadURL.openConnection(proxy);
505: else
506: ucn = downloadURL.openConnection();
507:
508: if (Thread.currentThread().isInterrupted())
509: return null;
510: ucn.connect();
511:
512: return ucn.getInputStream();
513:
514: }
515:
516: public static Document getDocument(FileObject modelSourceFileObject) {
517: Document result = null;
518: try {
519: DataObject dObject = DataObject.find(modelSourceFileObject);
520: EditorCookie ec = (EditorCookie) dObject
521: .getCookie(EditorCookie.class);
522: Document doc = ec.openDocument();
523: if (doc instanceof BaseDocument)
524: return doc;
525:
526: result = new org.netbeans.editor.BaseDocument(
527: org.netbeans.modules.xml.text.syntax.XMLKit.class,
528: false);
529: String str = doc.getText(0, doc.getLength());
530: result.insertString(0, str, null);
531:
532: } catch (Exception dObjEx) {
533: return null;
534: }
535: return result;
536: }
537:
538: private static Document _getDocument(
539: DataObject modelSourceDataObject) throws IOException {
540: Document result = null;
541: if (modelSourceDataObject != null
542: && modelSourceDataObject.isValid()) {
543: EditorCookie ec = (EditorCookie) modelSourceDataObject
544: .getCookie(EditorCookie.class);
545: assert ec != null : "Data object "
546: + modelSourceDataObject.getPrimaryFile().getPath()
547: + " has no editor cookies.";
548: Document doc = null;
549: try {
550: doc = ec.openDocument();
551: } catch (UserQuestionException uce) {
552: // this exception is thrown if the document is to large
553: // lets just confirm that it is ok
554: uce.confirmed();
555: doc = ec.openDocument();
556: }
557: assert (doc instanceof BaseDocument);
558: result = doc;
559: }
560: return result;
561: }
562:
563: /**
564: * This method must be overridden by the Unit testcase to return a special
565: * Document object for a FileObject.
566: */
567: protected static Document _getDocument(
568: FileObject modelSourceFileObject)
569: throws DataObjectNotFoundException, IOException {
570: DataObject dObject = DataObject.find(modelSourceFileObject);
571: return _getDocument(dObject);
572: }
573:
574: private static CatalogWriteModel testCatalogModel = null;
575:
576: public static CatalogWriteModel getTestCatalogWriteModel()
577: throws IOException {
578: if (testCatalogModel == null) {
579: CatalogWriteModel cm = null;
580: try {
581: cm = new XAMCatalogWriteModelImpl(new File(System
582: .getProperty("java.io.tmpdir")));
583: } catch (CatalogModelException ex) {
584: return null;
585: }
586: File file = FileUtil.toFile(cm.getCatalogFileObject());
587: file.deleteOnExit();
588: return cm;
589: }
590: return testCatalogModel;
591: }
592:
593: public static FileObject getProjectCatalogFileObject(Project prj)
594: throws IOException {
595: return Util.getProjectCatalogFileObject(prj, true);
596: }
597:
598: /**
599: * Choose the suitable catalog file for this file object considering XMLCatalogProvider
600: * and return the correct choice
601: **/
602: /*public static FileObject getCatalogFile(FileObject fo) throws IOException{
603: if(fo == null)
604: return null;
605: Project foprj = FileOwnerQuery.getOwner(fo);
606: if(foprj == null)
607: return null;
608:
609: XMLCatalogProvider xcp = (XMLCatalogProvider) foprj.getLookup().lookup(XMLCatalogProvider.class);
610: if(xcp == null)
611: return getProjectCatalogFileObject(foprj);
612:
613: //look for per file catalog
614: URI catURI = xcp.getCatalog(fo);
615: if(catURI == null)
616: return getProjectCatalogFileObject(foprj);
617:
618: catURI = FileUtil.toFile(foprj.getProjectDirectory()).toURI().resolve(catURI);
619: File catFile = new File(catURI);
620: if(!catFile.isFile()){
621: catFile.createNewFile();
622: }
623: FileObject result = FileUtil.toFileObject(FileUtil.normalizeFile(catFile));
624:
625: if(result == null)
626: return getProjectCatalogFileObject(foprj);
627:
628: return result;
629: }*/
630:
631: public static FileObject getFileObject(ModelSource ms) {
632: return (FileObject) ms.getLookup().lookup(FileObject.class);
633: }
634:
635: public static CatalogModel getCatalogModel(ModelSource ms)
636: throws CatalogModelException {
637: return CatalogModelFactory.getDefault().getCatalogModel(ms);
638: }
639:
640: public static ModelSource getModelSource(
641: FileObject bindingHandlerFO, boolean editable) {
642: try {
643: return createModelSource(bindingHandlerFO, editable);
644: } catch (CatalogModelException ex) {
645: return null;
646: }
647: }
648:
649: /**
650: * This method could be overridden by the Unit testcase to return a special
651: * ModelSource object for a FileObject with custom impl of classes added to the lookup.
652: * This is optional if both getDocument(FO) and createCatalogModel(FO) are overridden.
653: */
654: public static ModelSource createModelSource(FileObject this FileObj,
655: boolean editable) throws CatalogModelException {
656: assert this FileObj != null : "Null file object.";
657: final CatalogModel catalogModel = createCatalogModel(this FileObj);
658: final DataObject dobj;
659: try {
660: dobj = DataObject.find(this FileObj);
661: } catch (DataObjectNotFoundException ex) {
662: throw new CatalogModelException(ex);
663: }
664: Lookup proxyLookup = Lookups.proxy(new Lookup.Provider() {
665: public Lookup getLookup() {
666: Document document = null;
667: try {
668: document = _getDocument(dobj);
669: if (document != null) {
670: return Lookups.fixed(new Object[] {
671: dobj.getPrimaryFile(), document, dobj,
672: DataObjectAdapters.source(dobj),
673: catalogModel });
674: } else {
675: return Lookups.fixed(new Object[] {
676: dobj.getPrimaryFile(), dobj,
677: catalogModel });
678: }
679: } catch (IOException ioe) {
680: logger.log(Level.SEVERE, ioe.getMessage());
681: return Lookups.fixed(new Object[] { dobj,
682: catalogModel });
683: }
684: }
685: });
686:
687: return new ModelSource(proxyLookup, editable);
688: }
689:
690: /**
691: * This method could be overridden by the Unit testcase to return a special
692: * ModelSource object for a FileObject with custom impl of classes added to the lookup.
693: * This is optional if both getDocument(FO) and createCatalogModel(FO) are overridden.
694: */
695: /*public static ModelSource createModelSource(final FileObject thisFileObj,
696: boolean editable) throws CatalogModelException{
697: assert thisFileObj != null : "Null file object.";
698: final CatalogModel catalogModel = createCatalogModel(thisFileObj);
699: final DataObject dobj;
700: try {
701: dobj = DataObject.find(thisFileObj);
702: } catch (DataObjectNotFoundException ex) {
703: throw new CatalogModelException(ex);
704: }
705:
706: ProxyLookup myLookup = new ProxyLookup() {
707: protected void beforeLookup(Lookup.Template template) {
708: if (Document.class.isAssignableFrom(template.getType())) {
709: Lookup l = Lookup.EMPTY;
710: try {
711: Document d = _getDocument(thisFileObj);
712: l = Lookups.singleton(d);
713: } catch (DataObjectNotFoundException ex) {
714: getLogger().log(Level.SEVERE, "Can't load data object from "+thisFileObj.getPath());
715: } catch (IOException ex) {
716: getLogger().log(Level.SEVERE, ex.getMessage());
717: }
718:
719: setLookups(new Lookup[]{l});
720: } else if (Source.class.isAssignableFrom(template.getType())) {
721: setLookups(new Lookup[]{Lookups.singleton(DataObjectAdapters.source(dobj))});
722: } else {
723: Lookup l = Lookups.fixed(new Object[] {
724: thisFileObj,
725: dobj,
726: catalogModel
727: });
728: setLookups(new Lookup[]{l});
729: }
730: }
731: };
732:
733: return new ModelSource(myLookup, editable);
734: }*/
735:
736: public static CatalogModel createCatalogModel(FileObject fo)
737: throws CatalogModelException {
738: return new CatalogModelFactoryImpl().getCatalogModel(fo);
739: }
740:
741: public static final String DEFAULT_PRIVATE_CATALOG_URI_STR = "private/cache/retriever/catalog.xml";
742: public static final String DEFAULT_PRIVATE_CAHCE_URI_STR = "private/cache/retriever";
743:
744: public static final String PRIVATE_CATALOG_URI_STR = "retriever/catalog.xml";
745: public static final String PRIVATE_CAHCE_URI_STR = "retriever";
746:
747: public static boolean retrieveAndCache(URI locationURI,
748: FileObject sourceFileObject) {
749: return Util.retrieveAndCache(locationURI, sourceFileObject,
750: true);
751: }
752:
753: public enum DocumentTypesEnum {
754: schema, wsdl;
755:
756: public String toString() {
757: if (name().equals("schema"))
758: return "xsd";
759: else
760: return name();
761: }
762: }
763:
764: public static final class HashNamespaceResolver implements
765: NamespaceContext {
766: private Map<String, String> prefixes; // namespace, prefix
767: private Map<String, String> namespaces; // prefix, namespace
768:
769: public HashNamespaceResolver(Map<String, String> nsTable) {
770: namespaces = nsTable;
771: prefixes = new HashMap<String, String>();
772: for (Entry<String, String> e : namespaces.entrySet()) {
773: prefixes.put(e.getValue(), e.getKey());
774: }
775: }
776:
777: public HashNamespaceResolver(Map<String, String> namespaces,
778: Map<String, String> prefixes) {
779: this .namespaces = namespaces;
780: this .prefixes = prefixes;
781: }
782:
783: public Iterator getPrefixes(String namespaceURI) {
784: return Collections.singletonList(getPrefix(namespaceURI))
785: .iterator();
786: }
787:
788: public String getPrefix(String namespaceURI) {
789: return prefixes.get(namespaceURI);
790: }
791:
792: public String getNamespaceURI(String prefix) {
793: return namespaces.get(prefix);
794: }
795: }
796: }
|