View Javadoc

1   /*
2    * $Id: SWResourceManager.java,v 1.13 2005/05/31 16:26:41 jlerner Exp $
3    *
4    * Copyright (c) 1999-2004, BBN Technologies, LLC.
5    * All rights reserved.
6    * http://www.daml.org/legal/opensource/bbn_license.html
7    */
8   
9   package com.bbn.swede.core.resources;
10  
11  import java.io.IOException;
12  import java.io.InputStream;
13  import java.net.MalformedURLException;
14  import java.net.URL;
15  import java.util.ArrayList;
16  import java.util.Iterator;
17  import java.util.Map;
18  
19  import org.eclipse.core.resources.IFile;
20  import org.eclipse.core.resources.IFolder;
21  import org.eclipse.core.resources.IProject;
22  import org.eclipse.core.resources.IResource;
23  import org.eclipse.core.runtime.CoreException;
24  
25  import com.bbn.swede.core.ElementTypeVisitor;
26  import com.bbn.swede.core.IOWLClass;
27  import com.bbn.swede.core.IOWLDocument;
28  import com.bbn.swede.core.IOWLElement;
29  import com.bbn.swede.core.IOWLExternalDocument;
30  import com.bbn.swede.core.IOWLFolder;
31  import com.bbn.swede.core.IOWLLibrary;
32  import com.bbn.swede.core.IOWLModel;
33  import com.bbn.swede.core.IOWLProject;
34  import com.bbn.swede.core.IOWLProperty;
35  import com.bbn.swede.core.OWLCore;
36  import com.bbn.swede.core.OWLDocumentInfo;
37  import com.bbn.swede.core.OWLElementInfo;
38  import com.bbn.swede.core.config.SWProjectInfo;
39  import com.bbn.swede.core.libraries.ILibraryDescriptor;
40  import com.bbn.swede.core.libraries.ILibraryEntryDescriptor;
41  import com.bbn.swede.core.libraries.LibraryOWLDocument;
42  import com.bbn.swede.core.libraries.OWLLibrary;
43  import com.hp.hpl.jena.rdf.model.Property;
44  import com.hp.hpl.jena.rdf.model.Resource;
45  
46  /***
47   * Factory class for creating semantic web resources.
48   * @author tself
49   */
50  public final class SWResourceManager
51  {
52     //Hidden constructor, since this is a utility class.
53     private SWResourceManager()
54     {
55     }
56     
57     /***
58      * Creates an OWL library element based on a given ILibraryDescriptor.
59      * @param ild The library descriptor
60      * @return An IOWLLibrary if successful, or <code>null</code> if not.
61      */
62     public static IOWLLibrary create(ILibraryDescriptor ild)
63     {
64        OWLLibrary toReturn = new OWLLibrary(ild);
65        return toReturn;
66     }
67     
68     /***
69      * Creates an element info for an OWL library element.
70      * @param owlLibrary The OWL library
71      * @return An element info for <code>owlLibrary</code>
72      */
73     public static OWLElementInfo createElementInfo(IOWLLibrary owlLibrary)
74     {
75        OWLElementInfo toReturn = null;
76        toReturn = new OWLElementInfo(owlLibrary);
77        ILibraryDescriptor ild = owlLibrary.getLibrary();
78        ILibraryEntryDescriptor iled = null;
79        LibraryOWLDocument newDoc = null;
80        Iterator i = null;
81        if(ild.isAvailable())
82        {
83           if(ild != null)
84           {
85              i = ild.getEntryDescriptors().iterator();
86              while (i.hasNext())
87              {
88                 iled = (ILibraryEntryDescriptor) i.next();
89                 newDoc = new LibraryOWLDocument(iled, owlLibrary);
90  //               owlLibrary.getLibrary().addLibraryChangeListener(newDoc);
91                 toReturn.addChild(newDoc);
92              }
93           }
94        }
95        return toReturn;
96     }
97     
98     /***
99      * Creates an OWLProject based on the given IProject.
100     * 
101     * @param proj IProject containing OWL Nature
102     * @return IOWLProject if success or null if failure.
103     */
104    public static IOWLProject create(IProject proj)
105    {
106       OWLProject oProj = null;
107       try
108       {
109          if(proj.hasNature(OWLCore.OWL_NATURE))
110          {
111             oProj = new OWLProject(proj);
112          }
113       }
114       catch (CoreException ce)
115       {
116          OWLCore.logError(OWLCore.getID(),
117             "Unable to convert IProject into SWeDE Project", ce);
118       }
119       return oProj;
120    }
121 
122    /***
123     * Attempts to create an OWL Folder element based on the provided Eclipse
124     * folder resource. If the resource provided contains no OWL documents, this
125     * method will return <code>null</code>. This is intended as a convenience
126     * method for creating up an OWL model based on an existing project. To
127     * create a new folder that will later have OWL documents added to it, you
128     * can just directly construct an OWLFolder object.
129     * 
130     * @param folder Eclipse folder resource to serve as the basis for the OWL
131     *        folder
132     * @return A newly created IOWLFolder, or <code>null</code> if the IFolder
133     *         provided (and its subfolders) does not contain any OWL documents.
134     */
135    public static IOWLFolder create(IFolder folder)
136    {
137       if(containsOWL(folder))
138       {
139          OWLFolder owlFolder = new OWLFolder(folder);
140          //            if (owlFolder.getElementInfo().getChildren().length > 0)
141          //                return owlFolder;
142          return owlFolder;
143       }
144       return null;
145    }
146 
147    /***
148     * Attempts to create an OWL File element based on the provided Eclipse file
149     * resource. If the resource provided is not an OWL document, this method
150     * will return <code>null</code>.
151     * @param file Eclipse file resource to serve as the basis for the OWL file
152     * @return A newly created IOWLDocument, or <code>null</code> if the IFile
153     *         provided is not an OWL document
154     */
155    public static IOWLDocument create(IFile file)
156    {
157       OWLDocument rvDoc = null;
158 
159       if(!file.getName().endsWith(".owl"))
160       {
161          return null;
162       }
163 
164       String sourceURL = SWProjectInfo.getDocumentSourceURL(file);
165       String uri = SWProjectInfo.getDocumentURI(file);
166       
167       //its external
168       if (sourceURL != null)
169       {                  
170          rvDoc = new OWLExternalDocument(file, sourceURL);
171       }
172       //else its internal
173       else
174       {
175          rvDoc = new OWLDocument(file);
176       }
177       Map map = SWProjectInfo.getGeneratedCodeMap(file);
178       if (rvDoc != null && map != null)
179       {
180          rvDoc._mapGenLocs.putAll(map);
181       }
182       return rvDoc;
183    }
184 
185    /***
186     * Attempts to create an external OWL File element based on the provided 
187     * Eclipse file resource and source URL. If the resource provided is not an 
188     * OWL document, this method will return <code>null</code>.
189     * @param file Eclipse file resource to serve as the basis for the OWL file
190     * @param sourceURL The URL the external document was imported from
191     * @return A newly created IOWLDocument, or <code>null</code> if the IFile
192     *         provided is not an OWL document
193     */
194    public static IOWLDocument create(IFile file, String sourceURL)
195    {
196       OWLDocument rvDoc = null;
197       rvDoc = new OWLExternalDocument(file, sourceURL);
198 
199       return rvDoc;
200    }
201 
202    /***
203     * Creates an OWL Class element based on a Jena resource.
204     * @param res The Jena resource to serve as the basis for the OWL class.
205     * @return The created OWL class element.
206     */
207    public static IOWLClass createOWLClass(Resource res)
208    {
209       return new OWLClass(res);
210    }
211 
212    /***
213     * Creates an OWL Property element based on a Jena property.
214     * @param prop The Jena property to serve as the basis for the OWL property.
215     * @return The created OWL property element.
216     */
217    public static IOWLProperty createOWLProperty(Property prop)
218    {
219       return new OWLProperty(prop);
220    }
221 
222    /***
223     * Provides access to the OWL model representing the entire Eclipse 
224     * workspace.
225     * @return The singleton instance of IOWLModel.
226     */
227    public static IOWLModel getModel()
228    {
229       return OWLModel.getModel();
230    }
231 
232    /***
233     * Retrieves a document from the web and adds it to the workspace and OWL 
234     * model.  The resulting local copy will be flagged as read-only and will
235     * retain the URL it was imported from as metadata.
236     * @param sUri The URI to download the document from
237     * @param sLocalName The filename to use for the local copy
238     * @param folder The folder to place the local copy in
239     * @return A newly constructed IOWLExternalDocument representing the
240     *         downloaded file, or <code>null</code> if external document
241     *         creation fails.
242     * @throws IOException if an input stream cannot be opened for 
243     *         <code>sUri</code>.
244     * @throws CoreException if creation of the local copy fails
245     */
246    public static IOWLExternalDocument addExternalDocument(String sUri,
247       String sLocalName, IFolder folder) throws IOException, CoreException
248    {
249       IOWLModel model = SWResourceManager.getModel();
250       if(model == null)
251       {
252          trace("addExternalDocument(): No model found", true);
253          return null;
254       }
255       URL url = null;
256       try
257       {
258          url = new URL(sUri);
259       }
260       catch (MalformedURLException mfe)
261       {
262          trace("Malformed URL: " + sUri, true);
263          return null;
264       }
265       // create an abstract representation of the new File in the system
266       IFile file = folder.getFile(sLocalName);
267       if(file.exists())
268       {
269          return null;
270       }
271       InputStream is = url.openStream();
272       file.create(is, false, null);
273       IOWLExternalDocument extDoc = (IOWLExternalDocument)SWResourceManager
274          .create(file, sUri);
275       model.add(extDoc);
276       return extDoc;
277    }
278 
279    /***
280     * Recursively checks a folder and its subfolders for OWL documents.
281     * @param folder The folder to check
282     * @return <code>true</code> if <code>folder</code> or one of its subfolders
283     *         contains one or more OWL documents, <code>false</code> if not.
284     */
285    public static boolean containsOWL(IFolder folder)
286    {
287       ArrayList alFolders = new ArrayList();
288       try
289       {
290          for(int i = 0; i < folder.members().length; i++)
291          {
292             IResource res = folder.members()[i];
293             if(res instanceof IFile)
294             {
295                IFile file = (IFile)res;
296                if(file.getName().endsWith(".owl"))
297                {
298                   return true;
299                }
300             }
301             else if(res instanceof IFolder)
302             {
303                alFolders.add(res);
304             }
305          }
306          for(int i = 0; i < alFolders.size(); i++)
307          {
308             IFolder fold = (IFolder)alFolders.get(i);
309             if(containsOWL(fold))
310             {
311                return true;
312             }
313          }
314       }
315       catch (CoreException e)
316       {
317          OWLCore.logWarning(OWLCore.getID(),
318             "Unabled to inspect folder contents for OWL documents", e);
319       }
320       return false;
321    }
322 
323    /***
324     * Creates a document info object for an OWL document.
325     * @param doc The OWL document
326     * @return The newly constructed OWLDocumentInfo
327     */
328    public static OWLDocumentInfo createDocumentInfo(IOWLDocument doc)
329    {
330       OWLDocumentInfo docInfo = new OWLDocumentInfo(doc);
331       return docInfo;
332    }
333 
334    /***
335     * Creates an element info object for an OWL element.  If the element is
336     * an OWL document, a document info will be created instead.
337     * @param elem The OWL element
338     * @return The newly constructed OWLElementInfo
339     */
340    public static OWLElementInfo createElementInfo(IOWLElement elem)
341    {
342       if(elem instanceof IOWLDocument)
343       {
344          return createDocumentInfo((IOWLDocument)elem);
345       }
346       if(elem instanceof IOWLFolder)
347       {
348          return createElementInfo((IOWLFolder)elem);
349       }
350       if(elem instanceof IOWLProject)
351       {
352          return createElementInfo((IOWLProject)elem);
353       }
354       if(elem instanceof IOWLLibrary)
355       {
356          return createElementInfo((IOWLLibrary) elem);
357       }
358       return null;
359    }
360 
361    /***
362     * Creates an element info object for an OWL folder.  Folder element infos
363     * contain all the OWL folders and OWL documents that appear directly under
364     * the folder in the OWL model.
365     * @param folder The folder
366     * @return The newly constructed element info
367     */
368    public static OWLElementInfo createElementInfo(IOWLFolder folder)
369    {
370       IFolder resFolder = (IFolder)folder.getResource().getAdapter(
371          IFolder.class);
372       if(resFolder == null)
373       {
374          return null;
375       }
376       OWLElementInfo info = new OWLElementInfo(folder);
377       try
378       {
379          IResource[] resources = resFolder.members();
380          for(int i = 0; i < resources.length; i++)
381          {
382             if(resources[i] instanceof IFile)
383             {
384                IOWLDocument owlFile = (IOWLDocument)SWResourceManager
385                   .create((IFile)resources[i]);
386                if(owlFile != null)
387                {
388                   info.addChild(owlFile);
389                }
390             }
391             else if(resources[i] instanceof IFolder)
392             {
393                IOWLFolder owlFolder = (IOWLFolder)SWResourceManager
394                   .create((IFolder)resources[i]);
395                if(owlFolder != null)
396                {
397                   info.addChild(owlFolder);
398                }
399             }
400          }
401       }
402       catch (CoreException e)
403       {
404          OWLCore.logWarning(OWLCore.getID(), "ElementInfo creation failed", e);
405       }
406       return info;
407    }
408 
409    /***
410     * Creates an element info object for an OWL project.  Project element infos
411     * contain all the OWL folders and OWL documents that appear directly under
412     * the project in the OWL model.  OWL elements further down in the model will
413     * appear in their parent elements' info object.
414     * @param project The project
415     * @return The newly constructed element info
416     */
417    public static OWLElementInfo createElementInfo(IOWLProject project)
418    {
419       IProject resProject = (IProject)project.getResource().getAdapter(
420          IProject.class);
421       
422       if(resProject == null)
423       {
424          return null;
425       }
426       OWLElementInfo info = new OWLElementInfo(project);
427       try
428       {
429          IResource[] resources = resProject.members();
430          for(int i = 0; i < resources.length; i++)
431          {
432             if(resources[i] instanceof IFile)
433             {
434                IFile file = (IFile)resources[i];
435                String sExtension = file.getFileExtension();
436                if(sExtension != null && sExtension.equalsIgnoreCase("owl"))
437                {
438                   IOWLDocument doc = SWResourceManager.create(file);
439                   if(doc != null)
440                   {
441                      info.addChild((IOWLDocument)doc);
442                   }
443                }
444             }
445             if(resources[i] instanceof IFolder)
446             {
447                IOWLFolder folder = (IOWLFolder)SWResourceManager
448                   .create((IFolder)resources[i]);
449                if(folder != null)
450                {
451                   info.addChild(folder);
452                }
453             }
454          }
455       }
456       catch (CoreException e)
457       {
458          OWLCore.logWarning(OWLCore.getID(),
459             "Unable to populate element infor for " + project.getElementName(),
460             e);
461       }
462       
463       ILibraryDescriptor[] libraries = SWProjectInfo.getLibraries(project.getProject());
464       OWLLibrary lib = null;
465       for(int i = 0; i < libraries.length; i++)
466       {
467          lib = (OWLLibrary) SWResourceManager.create(libraries[i]);
468          lib.addLibraryChangeListener((OWLProject) project);
469          info.addChild(lib);
470       }
471       
472       return info;
473    }
474 
475    /***
476     * Searches an element's descendants for instances of a Java type.
477     * @param elem The element to search
478     * @param c The type to search for
479     * @return An array containing all OWL elements of type <code>c</code> below
480     *         <code>elem</code>.  This may be an empty array.
481     */
482    public static IOWLElement[] findChildrenOfType(IOWLElement elem, Class c)
483    {
484       ArrayList al = new ArrayList();
485       ElementTypeVisitor visitor = new ElementTypeVisitor(c, al);
486       elem.accept(visitor);
487       IOWLElement[] elements = new IOWLElement[al.size()];
488       for(int i = 0; i < al.size(); i++)
489       {
490          elements[i] = (IOWLElement)al.get(i);
491       }
492       return elements;
493    }
494 
495    /***
496     * print trace statement.
497     * 
498     * @param message
499     * @param user
500     */
501    private static void trace(String message, String user)
502    {
503 //      OWLCore.trace("SWResourceManager", message, false);            
504    }
505    private static void trace(String msg, boolean error)
506    {
507 //      OWLCore.trace("SWResourceManager", msg, error);
508    }
509 
510 
511 }