diff options
Diffstat (limited to 'branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager')
6 files changed, 859 insertions, 524 deletions
diff --git a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionCollectionImpl.java b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionCollectionImpl.java index 6d13e38937..5dcd09770b 100644 --- a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionCollectionImpl.java +++ b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionCollectionImpl.java @@ -74,6 +74,7 @@ import org.apache.tuscany.sca.data.collection.ItemCollection; import org.apache.tuscany.sca.data.collection.LocalItemCollection; import org.apache.tuscany.sca.data.collection.NotFoundException; import org.apache.tuscany.sca.domain.manager.impl.ContributionCollectionImpl.Cache.ContributionCache; +import org.apache.tuscany.sca.domain.search.DomainSearch; import org.apache.tuscany.sca.monitor.Monitor; import org.apache.tuscany.sca.monitor.MonitorFactory; import org.apache.tuscany.sca.monitor.Problem; @@ -97,8 +98,8 @@ import org.w3c.dom.Document; * @version $Rev$ $Date$ */ @Scope("COMPOSITE") -@Service(interfaces={ItemCollection.class, LocalItemCollection.class, WorkspaceReader.class}) -public class ContributionCollectionImpl implements ItemCollection, LocalItemCollection, WorkspaceReader { +@Service(interfaces={ItemCollection.class, LocalItemCollection.class}) +public class ContributionCollectionImpl implements ItemCollection, LocalItemCollection { private static final Logger logger = Logger.getLogger(ContributionCollectionImpl.class.getName()); @@ -111,6 +112,9 @@ public class ContributionCollectionImpl implements ItemCollection, LocalItemColl @Reference public DomainManagerConfiguration domainManagerConfiguration; + @Reference + public DomainSearch domainSearch; + private Monitor monitor; private ContributionFactory contributionFactory; private WorkspaceFactory workspaceFactory; @@ -256,6 +260,7 @@ public class ContributionCollectionImpl implements ItemCollection, LocalItemColl // Write the workspace writeWorkspace(workspace); return; + } } throw new NotFoundException(key); @@ -479,7 +484,6 @@ public class ContributionCollectionImpl implements ItemCollection, LocalItemColl private static String title(String contributionURI) { return contributionURI; } - /** * Read the workspace. @@ -652,9 +656,5 @@ public class ContributionCollectionImpl implements ItemCollection, LocalItemColl } return contributions; } - - public Workspace getWorkspace() { - return readContributions(readWorkspace()); - } } diff --git a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionsReader.java b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionsReader.java new file mode 100644 index 0000000000..b679f594e6 --- /dev/null +++ b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionsReader.java @@ -0,0 +1,9 @@ +package org.apache.tuscany.sca.domain.manager.impl; + +import org.apache.tuscany.sca.contribution.Contribution; + +public interface ContributionsReader { + + Contribution[] readContributions(); + +} diff --git a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeCollectionImpl.java b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeCollectionImpl.java index 3dac9b535e..63af213fbb 100644 --- a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeCollectionImpl.java +++ b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeCollectionImpl.java @@ -33,6 +33,7 @@ import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Logger; @@ -54,10 +55,8 @@ import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; -import org.apache.tuscany.sca.contribution.resolver.DefaultModelResolver; import org.apache.tuscany.sca.contribution.resolver.ModelResolverExtensionPoint; import org.apache.tuscany.sca.contribution.service.ContributionReadException; -import org.apache.tuscany.sca.contribution.service.ContributionResolveException; import org.apache.tuscany.sca.core.ExtensionPointRegistry; import org.apache.tuscany.sca.core.UtilityExtensionPoint; import org.apache.tuscany.sca.data.collection.Entry; @@ -78,331 +77,405 @@ import org.osoa.sca.annotations.Scope; import org.osoa.sca.annotations.Service; /** - * Implementation of a deployable composite collection service. - * + * Implementation of a deployable composite collection service. + * * @version $Rev$ $Date$ */ @Scope("COMPOSITE") -@Service(interfaces={ItemCollection.class, LocalItemCollection.class}) -public class DeployableCompositeCollectionImpl implements ItemCollection, LocalItemCollection { - - private static final Logger logger = Logger.getLogger(DeployableCompositeCollectionImpl.class.getName()); - - @Reference - public LocalItemCollection contributionCollection; - - @Reference - public DomainManagerConfiguration domainManagerConfiguration; - - private ModelFactoryExtensionPoint modelFactories; - private ModelResolverExtensionPoint modelResolvers; - private URLArtifactProcessor<Contribution> contributionProcessor; - private XMLOutputFactory outputFactory; - private ContributionDependencyBuilder contributionDependencyBuilder; - private Monitor monitor; - - /** - * Cache contribution models. - */ - static class Cache { - static class ContributionCache { - private Contribution contribution; - private long contributionLastModified; - } - private Map<URL, ContributionCache> contributions = new HashMap<URL, ContributionCache>(); - } - - private Cache cache = new Cache(); - - /** - * Initialize the component. - */ - @Init - public void initialize() throws ParserConfigurationException { - - ExtensionPointRegistry extensionPoints = domainManagerConfiguration.getExtensionPoints(); - - // Create a monitor - UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); - MonitorFactory monitorFactory = utilities.getUtility(MonitorFactory.class); - monitor = monitorFactory.createMonitor(); - - // Get model factories - modelFactories = extensionPoints.getExtensionPoint(ModelFactoryExtensionPoint.class); - XMLInputFactory inputFactory = modelFactories.getFactory(XMLInputFactory.class); - outputFactory = modelFactories.getFactory(XMLOutputFactory.class); - outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); - - // Get and initialize artifact processors - StAXArtifactProcessorExtensionPoint staxProcessors = extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); - StAXArtifactProcessor<Object> staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, outputFactory, monitor); - - URLArtifactProcessorExtensionPoint urlProcessors = extensionPoints.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); - URLArtifactProcessor<Object> urlProcessor = new ExtensibleURLArtifactProcessor(urlProcessors, monitor); - - // Create contribution processor - modelResolvers = extensionPoints.getExtensionPoint(ModelResolverExtensionPoint.class); - contributionProcessor = new ContributionContentProcessor(extensionPoints, monitor); - - // Create contribution and composite builders - contributionDependencyBuilder = new ContributionDependencyBuilderImpl(monitor); - } - - public Entry<String, Item>[] getAll() { - logger.fine("getAll"); - - // Return all the deployable composites in the contributions - List<Entry<String, Item>> entries = new ArrayList<Entry<String, Item>>(); - - // Get the list of contributions in the workspace - Entry<String, Item>[] contributionEntries = contributionCollection.getAll(); - - // Read contribution metadata - for (Entry<String, Item> contributionEntry: contributionEntries) { - Item contributionItem = contributionEntry.getData(); - Contribution contribution; - try { - contribution = contribution(contributionEntry.getKey(), contributionItem.getAlternate()); - } catch (ContributionReadException e) { - continue; - } - - // Create entries for the deployable composites - for (Composite deployable: contribution.getDeployables()) { - entries.add(entry(contribution, deployable)); - } - - } - return entries.toArray(new Entry[entries.size()]); - } - - public Item get(String key) throws NotFoundException { - logger.fine("get " + key); - - // Get the specified contribution info - String contributionURI = contributionURI(key); - Item contributionItem = contributionCollection.get(contributionURI); - - // Read the contribution - Contribution contribution; - try { - contribution = contribution(contributionURI, contributionItem.getAlternate()); - } catch (ContributionReadException e) { - throw new NotFoundException(key); - } - - // Find the specified deployable composite - QName qname = compositeQName(key); - for (Composite deployable: contribution.getDeployables()) { - if (qname.equals(deployable.getName())) { - // find the deployable composite - deployable = contribution.getModelResolver().resolveModel(Composite.class, deployable); - - if (deployable.isUnresolved()) { - throw new NotFoundException(key); - } - - // Return an item describing the deployable composite - return item(contribution, deployable); - } - } - - throw new NotFoundException(key); - } - - public String post(String key, Item item) { - throw new UnsupportedOperationException(); - } - - public void put(String key, Item item) throws NotFoundException { - throw new UnsupportedOperationException(); - } - - public void delete(String key) throws NotFoundException { - throw new UnsupportedOperationException(); - } - - public Entry<String, Item>[] query(String queryString) { - logger.fine("query " + queryString); - - if (queryString.startsWith("contribution=")) { - - // Return all the deployable composites in the specified - // contribution - List<Entry<String, Item>> entries = new ArrayList<Entry<String, Item>>(); - - // Get the specified contribution info - String contributionURI = queryString.substring(queryString.indexOf('=') + 1); - Item contributionItem; - try { - contributionItem = contributionCollection.get(contributionURI); - } catch (NotFoundException e) { - return entries.toArray(new Entry[entries.size()]); - } - - // Read the contribution - Contribution contribution; - try { - contribution = contribution(contributionURI, contributionItem.getAlternate()); - } catch (ContributionReadException e) { - return entries.toArray(new Entry[entries.size()]); - } - - // Create entries for the deployable composites - for (Composite deployable: contribution.getDeployables()) { - entries.add(entry(contribution, deployable)); - } - - return entries.toArray(new Entry[entries.size()]); - - } else { - throw new UnsupportedOperationException(); - } - } - - /** - * Returns the contribution with the given URI. - * - * @param contributionURI - * @param contributionLocation - * @return - * @throws NotFoundException - */ - private Contribution contribution(String contributionURI, String contributionLocation) throws ContributionReadException { - try { - URI uri = URI.create(contributionURI); - URL location = locationURL(contributionLocation); - - // Get contribution from cache - ContributionCache contributionCache = cache.contributions.get(location); - long lastModified = lastModified(location); - if (contributionCache != null) { - if (contributionCache.contributionLastModified == lastModified) { - return contributionCache.contribution; - } - - // Reset contribution cache - cache.contributions.remove(location); - } - - Contribution contribution = (Contribution)contributionProcessor.read(null, uri, location); - - // TODO - analyse dependencies here? - - //contributionProcessor.resolve(contribution, new DefaultModelResolver()); - - // Cache contribution - contributionCache = new ContributionCache(); - contributionCache.contribution = contribution; - contributionCache.contributionLastModified = lastModified; - cache.contributions.put(location, contributionCache); - - return contribution; - - } catch (ContributionReadException e) { - throw e; - } catch (MalformedURLException e) { - throw new ContributionReadException(e); - // } catch (ContributionResolveException e) { - // throw new ContributionReadException(e); - } catch (Throwable e) { - throw new ContributionReadException(e); - } - } - - /** - * Returns the entry contents describing a composite. - * - * @param composite - * @return - */ - private static String content(Composite composite) { - StringBuffer sb = new StringBuffer(); - List<Component> components = composite.getComponents(); - for (int i = 0, n = components.size(); i < n; i++) { - Component component = components.get(i); - if (component.getImplementation() instanceof NodeImplementation) { - List<ComponentService> services = component.getServices(); - if (!services.isEmpty()) { - List<Binding> bindings = services.get(0).getBindings(); - if (!bindings.isEmpty()) { - - // List node URIs - sb.append("Node URI: <span id=\"nodeURI\">"); - sb.append(component.getServices().get(0).getBindings().get(0).getURI()); - break; - } - } - } else { - - // List component names - if (sb.length() == 0) { - sb.append("Components: <span id=\"components\">"); - } else { - sb.append(" "); - } - sb.append(component.getName()); - } - } - if (sb.length() != 0) { - sb.append("</span>"); - } - return sb.toString(); - } - - /** - * Returns the link to the resource related to a composite. - * - * @param composite - * @return - */ - private static String relatedLink(Composite composite) { - for (Component component: composite.getComponents()) { - if (component.getImplementation() instanceof NodeImplementation) { - NodeImplementation nodeImplementation = (NodeImplementation)component.getImplementation(); - Composite deployable = nodeImplementation.getComposite(); - String contributionURI = deployable.getURI(); - QName qname = deployable.getName(); - String key = compositeKey(contributionURI, qname); - return "/composite-source/" + key; - } - } - return null; - } - - /** - * Returns an entry describing the given deployable. - * - * @param contribution - * @param deployable - * @return - */ - private static Entry<String, Item> entry(Contribution contribution, Composite deployable) { - Entry<String, Item> entry = new Entry<String, Item>(); - entry.setKey(DomainManagerUtil.compositeKey(contribution.getURI(), deployable.getName())); - entry.setData(item(contribution, deployable)); - return entry; - } - - /** - * Returns an item describing the given deployable. - * - * @param contribution - * @param deployable - * @return - */ - private static Item item(Contribution contribution, Composite deployable) { - String contributionURI = contribution.getURI(); - String contributionLocation = contribution.getLocation(); - QName qname = deployable.getName(); - String deployableURI = deployable.getURI(); - Item item = new Item(); - item.setTitle(compositeTitle(contributionURI, qname)); - item.setContents(content(deployable)); - item.setLink(compositeSourceLink(contributionURI, qname)); - item.setAlternate(compositeAlternateLink(contributionLocation, deployableURI)); - item.setRelated(relatedLink(deployable)); - return item; - } +@Service(interfaces = { ItemCollection.class, LocalItemCollection.class, ContributionsReader.class }) +public class DeployableCompositeCollectionImpl implements ItemCollection, + LocalItemCollection, ContributionsReader { + + private static final Logger logger = Logger + .getLogger(DeployableCompositeCollectionImpl.class.getName()); + + @Reference + public LocalItemCollection contributionCollection; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + private ModelFactoryExtensionPoint modelFactories; + private ModelResolverExtensionPoint modelResolvers; + private URLArtifactProcessor<Contribution> contributionProcessor; + private XMLOutputFactory outputFactory; + private ContributionDependencyBuilder contributionDependencyBuilder; + private Monitor monitor; + + /** + * Cache contribution models. + */ + static class Cache { + static class ContributionCache { + private Contribution contribution; + private long contributionLastModified; + } + + private Map<URL, ContributionCache> contributions = new HashMap<URL, ContributionCache>(); + } + + private Cache cache = new Cache(); + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + + ExtensionPointRegistry extensionPoints = domainManagerConfiguration + .getExtensionPoints(); + + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints + .getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = utilities + .getUtility(MonitorFactory.class); + monitor = monitorFactory.createMonitor(); + + // Get model factories + modelFactories = extensionPoints + .getExtensionPoint(ModelFactoryExtensionPoint.class); + XMLInputFactory inputFactory = modelFactories + .getFactory(XMLInputFactory.class); + outputFactory = modelFactories.getFactory(XMLOutputFactory.class); + outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, + true); + + // Get and initialize artifact processors + StAXArtifactProcessorExtensionPoint staxProcessors = extensionPoints + .getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + StAXArtifactProcessor<Object> staxProcessor = new ExtensibleStAXArtifactProcessor( + staxProcessors, inputFactory, outputFactory, monitor); + + URLArtifactProcessorExtensionPoint urlProcessors = extensionPoints + .getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + URLArtifactProcessor<Object> urlProcessor = new ExtensibleURLArtifactProcessor( + urlProcessors, monitor); + + // Create contribution processor + modelResolvers = extensionPoints + .getExtensionPoint(ModelResolverExtensionPoint.class); + contributionProcessor = new ContributionContentProcessor( + extensionPoints, monitor); + + // Create contribution and composite builders + contributionDependencyBuilder = new ContributionDependencyBuilderImpl( + monitor); + } + + public Entry<String, Item>[] getAll() { + logger.fine("getAll"); + + // Return all the deployable composites in the contributions + List<Entry<String, Item>> entries = new ArrayList<Entry<String, Item>>(); + + // Get the list of contributions in the workspace + Entry<String, Item>[] contributionEntries = contributionCollection + .getAll(); + + // Read contribution metadata + for (Entry<String, Item> contributionEntry : contributionEntries) { + Item contributionItem = contributionEntry.getData(); + Contribution contribution; + try { + contribution = contribution(contributionEntry.getKey(), + contributionItem.getAlternate()); + } catch (ContributionReadException e) { + continue; + } + + // Create entries for the deployable composites + for (Composite deployable : contribution.getDeployables()) { + entries.add(entry(contribution, deployable)); + } + + } + return entries.toArray(new Entry[entries.size()]); + } + + public Contribution[] readContributions() { + + // Get the list of contributions in the workspace + Entry<String, Item>[] contributionEntries = contributionCollection + .getAll(); + + LinkedList<Contribution> contributions = new LinkedList<Contribution>(); + + // Read contribution metadata + for (Entry<String, Item> contributionEntry : contributionEntries) { + Item contributionItem = contributionEntry.getData(); + Contribution contribution; + try { + contribution = contribution(contributionEntry.getKey(), + contributionItem.getAlternate()); + + } catch (ContributionReadException e) { + continue; + } + + LinkedList<Composite> resolvedComposites = new LinkedList<Composite>(); + + for (Composite composite : contribution.getDeployables()) { + + // find the deployable composite + composite = contribution.getModelResolver().resolveModel( + Composite.class, composite); + + resolvedComposites.add(composite); + + } + + contribution.getDeployables().clear(); + contribution.getDeployables().addAll(resolvedComposites); + + contributions.add(contribution); + + } + + return contributions.toArray(new Contribution[0]); + + } + + public Item get(String key) throws NotFoundException { + logger.fine("get " + key); + + // Get the specified contribution info + String contributionURI = contributionURI(key); + Item contributionItem = contributionCollection.get(contributionURI); + + // Read the contribution + Contribution contribution; + try { + contribution = contribution(contributionURI, contributionItem + .getAlternate()); + } catch (ContributionReadException e) { + throw new NotFoundException(key); + } + + // Find the specified deployable composite + QName qname = compositeQName(key); + for (Composite deployable : contribution.getDeployables()) { + if (qname.equals(deployable.getName())) { + // find the deployable composite + deployable = contribution.getModelResolver().resolveModel( + Composite.class, deployable); + + if (deployable.isUnresolved()) { + throw new NotFoundException(key); + } + + // Return an item describing the deployable composite + return item(contribution, deployable); + } + } + + throw new NotFoundException(key); + } + + public String post(String key, Item item) { + throw new UnsupportedOperationException(); + } + + public void put(String key, Item item) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public void delete(String key) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public Entry<String, Item>[] query(String queryString) { + logger.fine("query " + queryString); + + if (queryString.startsWith("contribution=")) { + + // Return all the deployable composites in the specified + // contribution + List<Entry<String, Item>> entries = new ArrayList<Entry<String, Item>>(); + + // Get the specified contribution info + String contributionURI = queryString.substring(queryString + .indexOf('=') + 1); + Item contributionItem; + try { + contributionItem = contributionCollection.get(contributionURI); + } catch (NotFoundException e) { + return entries.toArray(new Entry[entries.size()]); + } + + // Read the contribution + Contribution contribution; + try { + contribution = contribution(contributionURI, contributionItem + .getAlternate()); + } catch (ContributionReadException e) { + return entries.toArray(new Entry[entries.size()]); + } + + // Create entries for the deployable composites + for (Composite deployable : contribution.getDeployables()) { + entries.add(entry(contribution, deployable)); + } + + return entries.toArray(new Entry[entries.size()]); + + } else { + throw new UnsupportedOperationException(); + } + } + + /** + * Returns the contribution with the given URI. + * + * @param contributionURI + * @param contributionLocation + * @return + * @throws NotFoundException + */ + private Contribution contribution(String contributionURI, + String contributionLocation) throws ContributionReadException { + try { + URI uri = URI.create(contributionURI); + URL location = locationURL(contributionLocation); + + // Get contribution from cache + ContributionCache contributionCache = cache.contributions + .get(location); + long lastModified = lastModified(location); + if (contributionCache != null) { + if (contributionCache.contributionLastModified == lastModified) { + return contributionCache.contribution; + } + + // Reset contribution cache + cache.contributions.remove(location); + } + + Contribution contribution = (Contribution) contributionProcessor + .read(null, uri, location); + + // TODO - analyse dependencies here? + + // contributionProcessor.resolve(contribution, new + // DefaultModelResolver()); + + // Cache contribution + contributionCache = new ContributionCache(); + contributionCache.contribution = contribution; + contributionCache.contributionLastModified = lastModified; + cache.contributions.put(location, contributionCache); + + return contribution; + + } catch (ContributionReadException e) { + throw e; + } catch (MalformedURLException e) { + throw new ContributionReadException(e); + // } catch (ContributionResolveException e) { + // throw new ContributionReadException(e); + } catch (Throwable e) { + throw new ContributionReadException(e); + } + } + + /** + * Returns the entry contents describing a composite. + * + * @param composite + * @return + */ + private static String content(Composite composite) { + StringBuffer sb = new StringBuffer(); + List<Component> components = composite.getComponents(); + for (int i = 0, n = components.size(); i < n; i++) { + Component component = components.get(i); + if (component.getImplementation() instanceof NodeImplementation) { + List<ComponentService> services = component.getServices(); + if (!services.isEmpty()) { + List<Binding> bindings = services.get(0).getBindings(); + if (!bindings.isEmpty()) { + + // List node URIs + sb.append("Node URI: <span id=\"nodeURI\">"); + sb.append(component.getServices().get(0).getBindings() + .get(0).getURI()); + break; + } + } + } else { + + // List component names + if (sb.length() == 0) { + sb.append("Components: <span id=\"components\">"); + } else { + sb.append(" "); + } + sb.append(component.getName()); + } + } + if (sb.length() != 0) { + sb.append("</span>"); + } + return sb.toString(); + } + + /** + * Returns the link to the resource related to a composite. + * + * @param composite + * @return + */ + private static String relatedLink(Composite composite) { + for (Component component : composite.getComponents()) { + if (component.getImplementation() instanceof NodeImplementation) { + NodeImplementation nodeImplementation = (NodeImplementation) component + .getImplementation(); + Composite deployable = nodeImplementation.getComposite(); + String contributionURI = deployable.getURI(); + QName qname = deployable.getName(); + String key = compositeKey(contributionURI, qname); + return "/composite-source/" + key; + } + } + return null; + } + + /** + * Returns an entry describing the given deployable. + * + * @param contribution + * @param deployable + * @return + */ + private static Entry<String, Item> entry(Contribution contribution, + Composite deployable) { + Entry<String, Item> entry = new Entry<String, Item>(); + entry.setKey(DomainManagerUtil.compositeKey(contribution.getURI(), + deployable.getName())); + entry.setData(item(contribution, deployable)); + return entry; + } + + /** + * Returns an item describing the given deployable. + * + * @param contribution + * @param deployable + * @return + */ + private static Item item(Contribution contribution, Composite deployable) { + String contributionURI = contribution.getURI(); + String contributionLocation = contribution.getLocation(); + QName qname = deployable.getName(); + String deployableURI = deployable.getURI(); + Item item = new Item(); + item.setTitle(compositeTitle(contributionURI, qname)); + item.setContents(content(deployable)); + item.setLink(compositeSourceLink(contributionURI, qname)); + item.setAlternate(compositeAlternateLink(contributionLocation, + deployableURI)); + item.setRelated(relatedLink(deployable)); + return item; + } } diff --git a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileServiceImpl.java b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileServiceImpl.java index 2adb623876..1493b73248 100644 --- a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileServiceImpl.java +++ b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileServiceImpl.java @@ -39,6 +39,9 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; import org.osoa.sca.annotations.Init; import org.osoa.sca.annotations.Property; import org.osoa.sca.annotations.Reference; @@ -47,107 +50,161 @@ import org.osoa.sca.annotations.Service; /** * Implementation of a servlet component supporting file upload/download. - * + * * @version $Rev$ $Date$ */ @Scope("COMPOSITE") @Service(Servlet.class) public class FileServiceImpl extends HttpServlet { - private static final long serialVersionUID = -4560385595481971616L; - - private static final Logger logger = Logger.getLogger(FileServiceImpl.class.getName()); - - @Property - public String directoryName; - - @Reference - public DomainManagerConfiguration domainManagerConfiguration; - - private ServletFileUpload upload; - - /** - * Initialize the component. - */ - @Init - public void initialize() throws IOException { - upload = new ServletFileUpload(new DiskFileItemFactory()); - } - - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { - - // Upload files - String rootDirectory = domainManagerConfiguration.getRootDirectory(); - try { - for (FileItem item: (List<FileItem>)upload.parseRequest(request)) { - if (!item.isFormField()) { - File directory = new File(rootDirectory + "/" + directoryName); - if (!directory.exists()) { - directory.mkdirs(); - } - logger.fine("post " + item.getName()); - item.write(new File(directory, item.getName())); - } - } - - // Redirect to the admin page - response.sendRedirect("/ui/files"); - } - catch (Exception e) { - throw new IOException(e.toString()); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - // Download a file - String requestURI = URLDecoder.decode(request.getRequestURI(), "UTF-8"); - String path = requestURI.substring(request.getServletPath().length()); - if (path.startsWith("/")) { - path = path.substring(1); - } - logger.fine("get " + path); - - try { - - // Analyze the given path - URI uri = URI.create(path); - String scheme = uri.getScheme(); - if (scheme == null) { - - // If no scheme is specified then the path identifies file - // inside our directory - String rootDirectory = domainManagerConfiguration.getRootDirectory(); - uri = new File(rootDirectory + "/" + directoryName, path).toURI(); - - } else if (!scheme.equals("file")) { - - // If the scheme does not identify a local file, just redirect to the server - // hosting the file - response.sendRedirect(path); - } - - // Read the file and write to response - URLConnection connection = uri.toURL().openConnection(); - connection.setUseCaches(false); - connection.connect(); - InputStream is = connection.getInputStream(); - ServletOutputStream os = response.getOutputStream(); - byte[] buffer = new byte[4096]; - for (;;) { - int n = is.read(buffer); - if (n < 0) { - break; - } - os.write(buffer, 0, n); - } - is.close(); - os.flush(); - - } catch (FileNotFoundException e) { - response.sendError(HttpServletResponse.SC_NOT_FOUND); - } - } - + private static final long serialVersionUID = -4560385595481971616L; + + private static final Logger logger = Logger.getLogger(FileServiceImpl.class + .getName()); + + @Property + public String directoryName; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + @Reference + public LocalItemCollection contributionCollection; + + private ServletFileUpload upload; + + /** + * Initialize the component. + */ + @Init + public void initialize() throws IOException { + upload = new ServletFileUpload(new DiskFileItemFactory()); + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws IOException { + + // Upload files + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + try { + for (FileItem item : (List<FileItem>) upload.parseRequest(request)) { + if (!item.isFormField()) { + File directory = new File(rootDirectory + "/" + + directoryName); + if (!directory.exists()) { + directory.mkdirs(); + } + logger.fine("post " + item.getName()); + item.write(new File(directory, item.getName())); + } + } + + // Redirect to the admin page + response.sendRedirect("/ui/files"); + } catch (Exception e) { + throw new IOException(e.toString()); + } + } + + @Override + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + + // Download a file + String requestURI = URLDecoder.decode(request.getRequestURI(), "UTF-8"); + String path = requestURI.substring(request.getServletPath().length()); + if (path.startsWith("/")) { + path = path.substring(1); + } + logger.fine("get " + path); + + try { + + // Analyze the given path + String artifactURI; + if (path.startsWith("contribution=")) { + int semicolonIndex = path.indexOf(';'); + String contributionName = path.substring("contribution=" + .length(), semicolonIndex); + artifactURI = path.substring(semicolonIndex + 1); + + try { + Item item = this.contributionCollection + .get(contributionName); + + if (item == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + + return; + + } + + path = item.getAlternate(); + + } catch (NotFoundException e) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + + return; + + } + + if (path.endsWith(".jar") || path.endsWith(".zip")) { + path = "jar:" + (path.startsWith("file:") ? "" : "file:") + path + '!' + (artifactURI.startsWith("/") ? "" : "/") + artifactURI; + + } else { + path += (path.endsWith("/") ? "" : "/") + artifactURI; + } + + } else { + artifactURI = null; + } + + URI uri = URI.create(path); + String scheme = uri.getScheme(); + if (scheme == null) { + + if (artifactURI != null) { + uri = URI.create("file:" + uri.toString()); + + } else { + + // If no scheme is specified then the path identifies file + // inside our directory + String rootDirectory = domainManagerConfiguration + .getRootDirectory(); + uri = new File(rootDirectory + "/" + directoryName, path) + .toURI(); + + } + + } else if (!scheme.equals("file") && !scheme.equals("jar")) { + + // If the scheme does not identify a local file, just redirect + // to the server + // hosting the file + response.sendRedirect(path); + } + + // Read the file and write to response + URLConnection connection = uri.toURL().openConnection(); + connection.setUseCaches(false); + connection.connect(); + InputStream is = connection.getInputStream(); + ServletOutputStream os = response.getOutputStream(); + byte[] buffer = new byte[4096]; + for (;;) { + int n = is.read(buffer); + if (n < 0) { + break; + } + os.write(buffer, 0, n); + } + is.close(); + os.flush(); + + } catch (FileNotFoundException e) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } + } diff --git a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/Searcher.java b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/Searcher.java index 5a2873b35f..0fb1812975 100644 --- a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/Searcher.java +++ b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/Searcher.java @@ -2,10 +2,12 @@ package org.apache.tuscany.sca.domain.manager.impl; import java.io.IOException; import java.io.StringWriter; +import java.io.Writer; import java.util.Arrays; -import java.util.Collection; +import java.util.Map; import org.apache.commons.lang.StringEscapeUtils; +import org.apache.tuscany.sca.contribution.Contribution; import org.apache.tuscany.sca.data.collection.Entry; import org.apache.tuscany.sca.data.collection.Item; import org.apache.tuscany.sca.data.collection.ItemCollection; @@ -13,9 +15,9 @@ import org.apache.tuscany.sca.data.collection.LocalItemCollection; import org.apache.tuscany.sca.data.collection.NotFoundException; import org.apache.tuscany.sca.domain.search.DomainSearch; import org.apache.tuscany.sca.domain.search.Result; -import org.apache.tuscany.sca.domain.search.impl.ArtifactResult; -import org.apache.tuscany.sca.domain.search.impl.FileContentResult; +import org.apache.tuscany.sca.domain.search.impl.DomainSearchFormatter; import org.apache.tuscany.sca.domain.search.impl.HighlightingUtil; +import org.apache.tuscany.sca.domain.search.impl.SearchFields; import org.osoa.sca.annotations.Reference; import org.osoa.sca.annotations.Scope; import org.osoa.sca.annotations.Service; @@ -25,20 +27,29 @@ import org.osoa.sca.annotations.Service; public class Searcher implements ItemCollection, LocalItemCollection { static char[] characters = { '\u0001'/* */, '\u0003'/* */, - '\u0004'/* */, - - }; + '\u0004'/* */, }; final private static String HTML_NEW_LINE = "<BR/>"; final private static String PATH_SEPARATOR = "/"; + final private static int MAX_CONTENT_LINE_WIDTH = 300; + + final private static String HIGHLIGHT_START = "<font color='#FF0000'>"; + + final private static String HIGHLIGHT_END = "</font>"; + @Reference - public WorkspaceReader contributionCollection; + public ContributionsReader contributionReader; + + @Reference + public LocalItemCollection contributionCollection; @Reference public DomainSearch domainSearch; + private int elementCounter; + public void delete(String key) throws NotFoundException { System.out.println("delete"); } @@ -56,35 +67,159 @@ public class Searcher implements ItemCollection, LocalItemCollection { } public Item get(String key) throws NotFoundException { - System.out.println("get"); - this.domainSearch.contributionAdded(null, this.contributionCollection - .getWorkspace()); - Result[] results = this.domainSearch.parseAndSearch(key, false); + + try { + + if (key.startsWith("highlight")) { + int lastSemicolonIndex = key.lastIndexOf(";"); + String artifact = key.substring(lastSemicolonIndex + 1); + int secondLastSemicolonIndex = key.lastIndexOf(";", + lastSemicolonIndex - 1); + String contribution = key.substring( + secondLastSemicolonIndex + 1, lastSemicolonIndex); + String query = key.substring("highlight".length(), + secondLastSemicolonIndex); + + return highlightArtifact(contribution, artifact, query); + + } else if (key.startsWith("query")) { + return executeQuery(key.substring("query".length())); + + } else { + throw new NotFoundException("Invalid operation!"); + } + + } catch (Exception t) { + + if (t instanceof NotFoundException) { + throw (NotFoundException) t; + } + + throw new NotFoundException("Internal error!"); + + } + + } + + private Item highlightArtifact(String contribution, String artifact, + String query) throws NotFoundException { + + // Item item = this.contributionCollection.get(contribution); + // + // if (item == null) { + // throw new NotFoundException("contribution not found: " + + // contribution); + // } + // + // String location = item.getAlternate(); + // + // if (location.endsWith(".jar") || location.endsWith(".zip")) { + // location = "jar:" + (location.startsWith("file:") ? "" : "file:") + + // location + '!' + (artifact.startsWith("/") ? "" : "/") + artifact; + // + // } else { + // location += (location.endsWith("/") ? "" : "/") + artifact; + // } + // + // try { + // Reader reader = new InputStreamReader(new + // URL(location).openStream()); + // StringBuilder sb = new StringBuilder(); + // int c; + // + // // TODO: load the chars into an array buffer instead of one + // // at a + // // time + // while ((c = reader.read()) != -1) { + // char character = (char) c; + // + // if (!Character.isIdentifierIgnorable(character)) { + // sb.append(character); + // } + // + // } + // + // String highlightedText = + // this.domainSearch.highlight(SearchFields.FILE_CONTENT_FIELD, + // sb.toString(), query); + // highlightedText = + // HighlightingUtil.replaceHighlightMarkupBy(highlightedText, + // HIGHLIGHT_START, HIGHLIGHT_END); + // + // item = new Item(); + // item.setTitle("Highlighted Artifact"); + // item.setContents(highlightedText); + // + // return item; + // + // } catch (Exception e) { + // throw new NotFoundException("Could not highlight artifact: " + + // e.getMessage(), e); + // } + + return null; + + } + + private Item executeQuery(String query) throws NotFoundException { + + if (!this.domainSearch.indexExists()) { + + Contribution[] contributions = this.contributionReader + .readContributions(); + + for (Contribution contribution : contributions) { + + if (!contribution.getURI().equals( + DomainManagerUtil.DEPLOYMENT_CONTRIBUTION_URI)) { + + this.domainSearch.contributionUpdated(contribution, + contribution); + + } + + } + + } + + Result[] results; + try { + results = this.domainSearch.parseAndSearch(query, true); + + } catch (Exception e1) { + + throw new NotFoundException("Exception while searching: " + + e1.getMessage(), e1); + + } Item item = new Item(); item.setTitle("Results"); StringWriter sw = new StringWriter(); + this.elementCounter = 0; - for (Result result : results) { + if (results.length > 0) { - try { - writeToHTML(0, result, sw); + for (Result result : results) { - } catch (IOException e) { - // ignore result - } + try { + writeToHTML(0, result, sw); - sw.write(HTML_NEW_LINE); + } catch (IOException e) { + // ignore result + } - } + } + + String contents = HighlightingUtil.replaceHighlightMarkupBy(sw + .getBuffer(), HIGHLIGHT_START, HIGHLIGHT_END); - String contents = HighlightingUtil.replaceHighlightMarkupBy(sw - .getBuffer(), "<font color='#FF0000'>", "</font>"); + item.setContents(replaceAll(contents, 40) + "end"); - item.setContents(replaceAll(contents, 40) + "end"); - - System.out.println(item.getContents().indexOf("@Referencevar")); + } else { + item.setContents("No results match: <u>" + query + "</u>"); + } System.out.println(item.getContents()); @@ -148,7 +283,9 @@ public class Searcher implements ItemCollection, LocalItemCollection { if (actual > less || actual == '&' || actual == '#' || actual == '\'' || actual == ' ' || actual == '%' - || actual == ':') { + || actual == ':' || actual == '(' || actual == ')' + || actual == '"') { + sb.append(actual); } else { @@ -171,100 +308,168 @@ public class Searcher implements ItemCollection, LocalItemCollection { } - private static Result writeFileContentResultToHTML(int indentation, - Result result, StringWriter writer) throws IOException { + private static String getIconLocationForResult(Result result) { - String content = ((FileContentResult) result).getContent(); - writer.write("file:"); + if (SearchFields.COMPONENT_FIELD.equals(result.getField())) { + return "icons/component.png' title='Component"; - if (content != null && content.length() > 0) { + } else if (SearchFields.COMPOSITE_FIELD.equals(result.getField())) { + return "icons/composite.png' title='Composite"; - StringEscapeUtils.escapeHtml(writer, result.getName()); - writer.write(HTML_NEW_LINE); + } else if (SearchFields.ARTIFACT_FIELD.equals(result.getField())) { + return "icons/artifact.png' title='Artifact"; + } - startIndentation(indentation, writer); - writer.write("<span style='max-width:100%'>"); - StringEscapeUtils.escapeHtml(writer, content); - writer.write("</span>"); - endIndentation(writer); - writer.write(HTML_NEW_LINE); + return "icons/feed-icon.png"; - } else { + } - writer.write(result.getName()); - Collection<Result> contents = result.getContents().values(); + private static void writeResultIcon(Writer writer, Result result) + throws IOException { + writer.write("<img src='"); + writer.write(getIconLocationForResult(result)); + writer.write("'/> "); - while (contents.size() == 1) { - result = contents.iterator().next(); + } - if (result instanceof FileContentResult) { - writer.write(PATH_SEPARATOR); - writer.write(result.getName()); + private static Result writeFileContentResultToHTML(int indentation, + Result result, StringWriter writer) throws IOException { - contents = result.getContents().values(); + Map<String, Result> contents = result.getContents(); + writeResultIcon(writer, result); - } else { - break; - } + if (contents.size() == 1 + && SearchFields.ARTIFACT_FIELD.equals(contents.values() + .iterator().next().getField())) { - } - - if (result instanceof FileContentResult) { - FileContentResult fileResult = (FileContentResult) result; - content = fileResult.getContent(); + writer.write(result.getValue()); + contents = result.getContents(); - if (content != null && content.length() > 0) { + while (contents.size() == 1 + && SearchFields.ARTIFACT_FIELD.equals(contents.values() + .iterator().next().getField())) { - writer.write(HTML_NEW_LINE); + result = contents.values().iterator().next(); - startIndentation(indentation, writer); - writer.write("<span style='max-width:100%'>"); - StringEscapeUtils.escapeHtml(writer, content); - writer.write("</span>"); - endIndentation(writer); - writer.write(HTML_NEW_LINE); + writer.write(PATH_SEPARATOR); + StringEscapeUtils.escapeHtml(writer, result.getValue()); - } + contents = result.getContents(); } + } else { + StringEscapeUtils.escapeHtml(writer, result.getValue()); } - + return result; } - private static void writeToHTML(int indentation, Result result, - StringWriter writer) throws IOException { + private static String removeHighlighting(String text) { + return HighlightingUtil.replaceHighlightMarkupBy(text, "", ""); + } - startIndentation(indentation++, writer); + private static void writeResultName(Result result, StringWriter writer) + throws IOException { + + if (SearchFields.CONTRIBUTION_FIELD.equals(result.getField())) { + writer.write("<a href='/contribution/"); + writer.write(removeHighlighting(result.getValue())); + writer.write("'>"); + writer.write(StringEscapeUtils.escapeHtml(result.getValue())); + writer.write("</a>"); + + } else if (SearchFields.COMPOSITE_FIELD.equals(result.getField())) { + writer.write("<a href='/composite-source/composite:"); + writer.write(getContributionURI(result)); + writer.write(';'); + writer.write(removeHighlighting(result.getValue())); + writer.write("'>"); + writer.write(StringEscapeUtils.escapeHtml(result.getValue())); + writer.write("</a>"); - if (result instanceof FileContentResult) { - result = writeFileContentResultToHTML(indentation, result, writer); + } else { + StringEscapeUtils.escapeHtml(writer, result.getValue()); + } + + } + + private static String getContributionURI(Result result) { + + if (result == null) { + return ""; + + } else if (SearchFields.CONTRIBUTION_FIELD.equals(result.getField())) { + return removeHighlighting(result.getValue()); } else { + return getContributionURI(result.getContainer()); + } + + } + + private void writeToHTML(int indentation, Result result, StringWriter writer) + throws IOException { - StringEscapeUtils.escapeHtml(writer, result.getClass() - .getSimpleName().substring(0, - result.getClass().getSimpleName().length() - 6)); - writer.write(':'); - StringEscapeUtils.escapeHtml(writer, result.getName()); - writer.write(HTML_NEW_LINE); - - if (result instanceof ArtifactResult) { - String location = ((ArtifactResult) result).getLocation(); - - if (location != null) { - startIndentation(indentation, writer); - writer.write("location: "); - StringEscapeUtils.escapeHtml(writer, location); - endIndentation(writer); + startIndentation(indentation++, writer); + String field = result.getField(); + + if (SearchFields.FILE_CONTENT_FIELD.equals(field)) { + String content = result.getValue(); + + if (content != null && content.length() > 0 + && DomainSearchFormatter.isHighlighted(content)) { + + writer.write(HTML_NEW_LINE); + + this.elementCounter++; + writer.write("<div style='margin-top:0em;margin-left:"); + writer.write(Integer.toString(indentation)); + writer + .write("em;background-color:#FFE175;max-width:100%;border-style:dashed;border-width:1px;padding:5px'>" + + "<p style='margin:0px;padding:0px;font-size:70%'>" + + "<a style='margin:0px;padding:0px' href='#filecontent"); + + writer.write(Integer.toString(this.elementCounter)); + + String contributionPlusArtifact = getContributionURI(result) + + ";" + + removeHighlighting(result.getContainer().getValue()); + + // writer.write("' onclick='search"); + // writer.write("'>view all</a> <a href='/files/contribution="); + writer.write("' onclick='getHighlighted(\""); + writer.write(contributionPlusArtifact); + writer + .write("\")'>view all</a> <a href='/files/contribution="); + + writer.write(contributionPlusArtifact); + writer + .write("'>download</a></p><p style='margin:8px 0px 0px 0px;padding:0px'>"); + + int i = 0; + while (i < content.length()) { + StringEscapeUtils.escapeHtml(writer, content.substring(i, + Math.min(i + MAX_CONTENT_LINE_WIDTH, content + .length()))); writer.write(HTML_NEW_LINE); + i += MAX_CONTENT_LINE_WIDTH; } + writer.write("</p></div>"); + } + } else if (SearchFields.ARTIFACT_FIELD.equals(field)) { + result = writeFileContentResultToHTML(indentation, result, writer); + + } else { + + writeResultIcon(writer, result); + writeResultName(result, writer); + } endIndentation(writer); diff --git a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/WorkspaceReader.java b/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/WorkspaceReader.java deleted file mode 100644 index d4cb1d21af..0000000000 --- a/branches/sca-java-1.x/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/WorkspaceReader.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.apache.tuscany.sca.domain.manager.impl; - -import org.apache.tuscany.sca.workspace.Workspace; - -public interface WorkspaceReader { - - Workspace getWorkspace(); - -} |