summaryrefslogtreecommitdiffstats
path: root/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl
diff options
context:
space:
mode:
Diffstat (limited to 'branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl')
-rw-r--r--branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ArtifactTypeDescriberImpl.java106
-rw-r--r--branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionMetadataDocumentProcessor.java108
-rw-r--r--branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionMetadataProcessor.java163
-rw-r--r--branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionRepositoryImpl.java297
-rw-r--r--branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionServiceImpl.java442
-rw-r--r--branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/InvalidContributionMetadataException.java54
-rw-r--r--branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/InvalidContributionURIException.java54
-rw-r--r--branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/PackageTypeDescriberImpl.java98
8 files changed, 1322 insertions, 0 deletions
diff --git a/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ArtifactTypeDescriberImpl.java b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ArtifactTypeDescriberImpl.java
new file mode 100644
index 0000000000..76318c6021
--- /dev/null
+++ b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ArtifactTypeDescriberImpl.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.contribution.service.impl;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.tuscany.sca.contribution.ContentType;
+import org.apache.tuscany.sca.contribution.Contribution;
+import org.apache.tuscany.sca.contribution.service.TypeDescriber;
+import org.apache.tuscany.sca.contribution.service.util.FileHelper;
+
+/**
+ * Implementation of the content describer for files
+ *
+ * @version $Rev$ $Date$
+ */
+public class ArtifactTypeDescriberImpl implements TypeDescriber {
+ private final Map<String, String> contentTypeRegistry = new HashMap<String, String>();
+
+ public ArtifactTypeDescriberImpl() {
+ super();
+ init();
+ }
+
+ /**
+ * Initialize contentType registry with know types based on known file extensions
+ */
+ private void init() {
+ contentTypeRegistry.put("COMPOSITE", ContentType.COMPOSITE);
+ contentTypeRegistry.put("SCDL", ContentType.COMPOSITE);
+ contentTypeRegistry.put("WSDL", ContentType.WSDL);
+ contentTypeRegistry.put("JAR", ContentType.JAR);
+ }
+
+ protected String resolveContentyTypeByExtension(URL resourceURL) {
+ String artifactExtension = FileHelper.getExtension(resourceURL.getPath());
+ if (artifactExtension == null) {
+ return null;
+ }
+ return contentTypeRegistry.get(artifactExtension.toUpperCase());
+ }
+
+ /**
+ * Build contentType for a specific resource. We first check if the file is
+ * a supported one (looking into our registry based on resource extension)
+ * If not found, we try to check file contentType Or we return
+ * defaultContentType provided
+ *
+ * @param resourceURL The artifact url
+ * @param defaultContentType The default content type if we can't find the correc one
+ * @return The content type
+ */
+ public String getType(URL resourceURL, String defaultContentType) {
+ URLConnection connection = null;
+ String contentType = defaultContentType;
+
+ if (resourceURL.getProtocol().equals("file") && FileHelper.toFile(resourceURL).isDirectory()) {
+ // Special case : contribution is a folder
+ contentType = ContentType.FOLDER;
+ } else if (resourceURL.toExternalForm().endsWith(Contribution.SCA_CONTRIBUTION_META)
+ || resourceURL.toExternalForm().endsWith(Contribution.SCA_CONTRIBUTION_GENERATED_META)) {
+ // Special case : contribution metadata
+ contentType = ContentType.CONTRIBUTION_METADATA;
+ } else {
+ contentType = resolveContentyTypeByExtension(resourceURL);
+ if (contentType == null) {
+ try {
+ connection = resourceURL.openConnection();
+ contentType = connection.getContentType();
+
+ if (contentType == null || contentType.equals("content/unknown")) {
+ // here we couldn't figure out from our registry or from URL and it's not a special file
+ // return defaultContentType if provided
+ contentType = defaultContentType;
+ }
+ } catch (IOException io) {
+ // could not access artifact, just ignore and we will return
+ // null contentType
+ }
+ }
+ }
+ return contentType == null ? defaultContentType : contentType;
+ }
+
+}
diff --git a/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionMetadataDocumentProcessor.java b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionMetadataDocumentProcessor.java
new file mode 100644
index 0000000000..8189914ffb
--- /dev/null
+++ b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionMetadataDocumentProcessor.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.contribution.service.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.tuscany.sca.assembly.AssemblyFactory;
+import org.apache.tuscany.sca.contribution.Contribution;
+import org.apache.tuscany.sca.contribution.ContributionFactory;
+import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor;
+import org.apache.tuscany.sca.contribution.service.ContributionReadException;
+
+/**
+ * MetadataDocumentProcessor that handles contribution metadata files
+ *
+ * @version $Rev$ $Date$
+ */
+public class ContributionMetadataDocumentProcessor {
+ protected final URLClassLoader classLoader;
+ protected final StAXArtifactProcessor staxProcessor;
+ protected final AssemblyFactory assemblyFactory;
+ protected final ContributionFactory contributionFactory;
+ protected final XMLInputFactory inputFactory;
+
+ public ContributionMetadataDocumentProcessor(URLClassLoader classLoader, StAXArtifactProcessor staxProcessor, AssemblyFactory assemblyFactory, ContributionFactory contributionFactory, XMLInputFactory inputFactory) {
+ super();
+ this.classLoader = classLoader;
+ this.staxProcessor = staxProcessor;
+ this.assemblyFactory = assemblyFactory;
+ this.contributionFactory = contributionFactory;
+ this.inputFactory = inputFactory;
+ }
+
+ private Contribution mergeContributionMetadata(Contribution contrib1, Contribution contrib2 ) {
+ contrib1.getDeployables().addAll(contrib2.getDeployables());
+ contrib1.getImports().addAll(contrib2.getImports());
+ contrib1.getExports().addAll(contrib2.getExports());
+
+ return contrib1;
+ }
+
+ public void read(Contribution contribution) throws XMLStreamException, ContributionReadException {
+ List<URL> artifactList = new ArrayList<URL>(2);
+ //set generated first, as the user created one ovverrides generated information
+ artifactList.add(this.classLoader.getResource(Contribution.SCA_CONTRIBUTION_GENERATED_META));
+ artifactList.add(this.classLoader.getResource(Contribution.SCA_CONTRIBUTION_META));
+
+ URL artifactURL = null;
+ InputStream artifactStream = null;
+ Iterator artifactIterator = artifactList.iterator();
+ while( artifactIterator.hasNext() ){
+
+ try {
+ artifactURL = (URL) artifactIterator.next();
+ if( artifactURL != null) {
+ artifactStream = artifactURL.openStream();
+ XMLStreamReader reader = inputFactory.createXMLStreamReader(artifactStream);
+ reader.nextTag();
+
+ Contribution contributionMetadata = (Contribution) staxProcessor.read(reader);
+ if (contributionMetadata != null) {
+ this.mergeContributionMetadata(contribution, contributionMetadata);
+ }
+ }
+
+ } catch (XMLStreamException e) {
+ throw new ContributionReadException(e);
+ } catch (IOException e) {
+ throw new ContributionReadException(e);
+ } finally {
+ try {
+ if (artifactStream != null) {
+ artifactStream.close();
+ artifactStream = null;
+ }
+ } catch (IOException ioe) {
+ //ignore
+ }
+ }
+ }
+ }
+}
diff --git a/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionMetadataProcessor.java b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionMetadataProcessor.java
new file mode 100644
index 0000000000..de38db1945
--- /dev/null
+++ b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionMetadataProcessor.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.contribution.service.impl;
+
+import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.apache.tuscany.sca.assembly.AssemblyFactory;
+import org.apache.tuscany.sca.assembly.Composite;
+import org.apache.tuscany.sca.contribution.Contribution;
+import org.apache.tuscany.sca.contribution.ContributionFactory;
+import org.apache.tuscany.sca.contribution.Export;
+import org.apache.tuscany.sca.contribution.Import;
+import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor;
+import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor;
+import org.apache.tuscany.sca.contribution.resolver.ModelResolver;
+import org.apache.tuscany.sca.contribution.service.ContributionReadException;
+import org.apache.tuscany.sca.contribution.service.ContributionResolveException;
+import org.apache.tuscany.sca.contribution.service.ContributionWriteException;
+
+/**
+ * Processor responsible for loading particular elements from contribution metadata file
+ *
+ * @version $Rev$ $Date$
+ */
+public class ContributionMetadataProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor<Contribution> {
+
+ private static final String SCA10_NS = "http://www.osoa.org/xmlns/sca/1.0";
+
+ private static final QName CONTRIBUTION = new QName(SCA10_NS, "contribution");
+ private static final QName DEPLOYABLE = new QName(SCA10_NS, "deployable");
+
+ private final AssemblyFactory assemblyFactory;
+ private final ContributionFactory contributionFactory;
+
+ private final StAXArtifactProcessor<Object> extensionProcessor;
+
+ public ContributionMetadataProcessor(AssemblyFactory assemblyFactory, ContributionFactory contributionFactory, StAXArtifactProcessor<Object> extensionProcessor) {
+ super();
+ this.assemblyFactory = assemblyFactory;
+ this.contributionFactory = contributionFactory;
+ this.extensionProcessor = extensionProcessor;
+ }
+
+
+ public QName getArtifactType() {
+ return CONTRIBUTION;
+ }
+
+ public Class<Contribution> getModelType() {
+ return Contribution.class;
+ }
+
+ public Contribution read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException {
+ Contribution contribution = null;
+
+ QName element = null;
+ while (reader.hasNext()) {
+ int event = reader.getEventType();
+ switch (event) {
+ case START_ELEMENT:
+ element = reader.getName();
+
+ if (CONTRIBUTION.equals(element)) {
+
+ // Read <contribution>
+ contribution = this.contributionFactory.createContribution();
+
+ } else if (DEPLOYABLE.equals(element)) {
+
+
+ // Read <deployable>
+ QName compositeName = getQName(reader, "composite");
+ if (compositeName == null) {
+ throw new ContributionReadException("Attribute 'composite' is missing");
+ }
+
+ if (contribution != null) {
+ Composite composite = assemblyFactory.createComposite();
+ composite.setName(compositeName);
+ composite.setUnresolved(true);
+ contribution.getDeployables().add(composite);
+
+ }
+ } else{
+
+ // Read an extension element
+ Object extension = extensionProcessor.read(reader);
+ if (extension != null && contribution != null) {
+ if (extension instanceof Import) {
+ contribution.getImports().add((Import)extension);
+ } else if (extension instanceof Export) {
+ contribution.getExports().add((Export)extension);
+ }
+ }
+ }
+ break;
+
+ case XMLStreamConstants.END_ELEMENT:
+ if (CONTRIBUTION.equals(reader.getName())) {
+ return contribution;
+ }
+ break;
+ }
+
+ //Read the next element
+ if (reader.hasNext()) {
+ reader.next();
+ }
+ }
+
+ return contribution;
+ }
+
+ public void write(Contribution contribution, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException {
+
+ // Write <contribution>
+ writeStartDocument(writer, CONTRIBUTION.getNamespaceURI(), CONTRIBUTION.getLocalPart());
+
+ // Write imports
+ for (Import imp: contribution.getImports()) {
+ extensionProcessor.write(imp, writer);
+ }
+
+ // Write exports
+ for (Export export: contribution.getExports()) {
+ extensionProcessor.write(export, writer);
+ }
+
+ // Write <deployable> elements
+ for (Composite deployable: contribution.getDeployables()) {
+ writeStart(writer, DEPLOYABLE.getNamespaceURI(), DEPLOYABLE.getLocalPart(),
+ new XAttr("composite", deployable.getName()));
+ writeEnd(writer);
+ }
+
+ writeEndDocument(writer);
+ }
+
+ public void resolve(Contribution model, ModelResolver resolver) throws ContributionResolveException {
+ }
+}
diff --git a/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionRepositoryImpl.java b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionRepositoryImpl.java
new file mode 100644
index 0000000000..d53693d875
--- /dev/null
+++ b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionRepositoryImpl.java
@@ -0,0 +1,297 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.contribution.service.impl;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.tuscany.sca.contribution.Contribution;
+import org.apache.tuscany.sca.contribution.service.ContributionRepository;
+import org.apache.tuscany.sca.contribution.service.util.FileHelper;
+import org.apache.tuscany.sca.contribution.service.util.IOHelper;
+
+/**
+ * The default implementation of ContributionRepository
+ *
+ * @version $Rev$ $Date$
+ */
+public class ContributionRepositoryImpl implements ContributionRepository {
+ private static final String NS = "http://tuscany.apache.org/xmlns/1.0-SNAPSHOT";
+ private static final String DOMAIN_INDEX_FILENAME = "sca-domain.xml";
+ private final File rootFile;
+ private Map<String, String> contributionLocations = new HashMap<String, String>();
+
+ private Map<String, Contribution> contributionMap = new HashMap<String, Contribution>();
+ private List<Contribution> contributions = new ArrayList<Contribution>();
+
+ private URI domain;
+ private XMLInputFactory factory;
+
+ /**
+ * Constructor with repository root
+ *
+ * @param repository
+ * @param factory
+ */
+ public ContributionRepositoryImpl(final String repository, XMLInputFactory factory) throws IOException {
+ String root = repository;
+ if (repository == null) {
+ root = AccessController.doPrivileged(new PrivilegedAction<String>() {
+ public String run() {
+ // Default to <user.home>/.tuscany/domains/local/
+ String userHome = System.getProperty("user.home");
+ String slash = File.separator;
+ return userHome + slash + ".tuscany" + slash + "domains" + slash + "local" + slash;
+ }
+ });
+ }
+ this.rootFile = new File(root);
+ this.domain = rootFile.toURI();
+ FileHelper.forceMkdir(rootFile);
+ if (!rootFile.exists() || !rootFile.isDirectory() || !rootFile.canRead()) {
+ throw new IOException("The root is not a directory: " + repository);
+ }
+ this.factory = factory;
+ }
+
+ public URI getDomain() {
+ return domain;
+ }
+
+ /**
+ * Resolve contribution location in the repository -> root repository /
+ * contribution file -> contribution group id / artifact id / version
+ *
+ * @param contribution
+ * @return
+ */
+ private File mapToFile(URL sourceURL) {
+ String fileName = FileHelper.toFile(sourceURL).getName();
+ return new File(rootFile, "contributions" + File.separator + fileName);
+ }
+
+ /**
+ * Write a specific source inputstream to a file on disk
+ *
+ * @param source contents of the file to be written to disk
+ * @param target file to be written
+ * @throws IOException
+ */
+ public static void copy(InputStream source, File target) throws IOException {
+ BufferedOutputStream out = null;
+ BufferedInputStream in = null;
+
+ try {
+ out = new BufferedOutputStream(new FileOutputStream(target));
+ in = new BufferedInputStream(source);
+ IOHelper.copy(in, out);
+ } finally {
+ IOHelper.closeQuietly(out);
+ IOHelper.closeQuietly(in);
+ }
+ }
+
+ public URL store(String contribution, URL sourceURL, InputStream contributionStream) throws IOException {
+ // where the file should be stored in the repository
+ File location = mapToFile(sourceURL);
+ FileHelper.forceMkdir(location.getParentFile());
+
+ copy(contributionStream, location);
+
+ // add contribution to repositoryContent
+ URL contributionURL = location.toURL();
+ URI relative = rootFile.toURI().relativize(location.toURI());
+ contributionLocations.put(contribution, relative.toString());
+ saveMap();
+
+ return contributionURL;
+ }
+
+ public URL store(String contribution, URL sourceURL) throws IOException {
+ // where the file should be stored in the repository
+ File location = mapToFile(sourceURL);
+ File source = FileHelper.toFile(sourceURL);
+ if (source == null || source.isFile()) {
+ InputStream is = sourceURL.openStream();
+ try {
+ return store(contribution, sourceURL, is);
+ } finally {
+ IOHelper.closeQuietly(is);
+ }
+ }
+
+ FileHelper.forceMkdir(location);
+ FileHelper.copyDirectory(source, location);
+
+ // add contribution to repositoryContent
+ URI relative = rootFile.toURI().relativize(location.toURI());
+ contributionLocations.put(contribution, relative.toString());
+ saveMap();
+
+ return location.toURL();
+ }
+
+ public URL find(String contribution) {
+ if (contribution == null) {
+ return null;
+ }
+ String location = contributionLocations.get(contribution);
+ if (location == null) {
+ return null;
+ }
+ try {
+ return new File(rootFile, location).toURL();
+ } catch (MalformedURLException e) {
+ // Should not happen
+ throw new AssertionError(e);
+ }
+ }
+
+ public void remove(String contribution) {
+ URL contributionURL = this.find(contribution);
+ if (contributionURL != null) {
+ // remove
+ try {
+ FileHelper.forceDelete(FileHelper.toFile(contributionURL));
+ this.contributionLocations.remove(contribution);
+ saveMap();
+ } catch (IOException ioe) {
+ // handle file could not be removed
+ }
+ }
+ }
+
+ public List<String> list() {
+ return new ArrayList<String>(contributionLocations.keySet());
+ }
+
+ public void init() {
+ File domainFile = new File(rootFile, "sca-domain.xml");
+ if (!domainFile.isFile()) {
+ return;
+ }
+ FileInputStream is;
+ try {
+ is = new FileInputStream(domainFile);
+ } catch (FileNotFoundException e) {
+ return;
+ }
+ try {
+ XMLStreamReader reader = factory.createXMLStreamReader(new InputStreamReader(is, "UTF-8"));
+ while (reader.hasNext()) {
+ switch (reader.getEventType()) {
+ case XMLStreamConstants.START_ELEMENT:
+ String name = reader.getName().getLocalPart();
+ if ("domain".equals(name)) {
+ String uri = reader.getAttributeValue(null, "uri");
+ if (uri != null) {
+ domain = URI.create(uri);
+ }
+ }
+ if ("contribution".equals(name)) {
+ String uri = reader.getAttributeValue(null, "uri");
+ String location = reader.getAttributeValue(null, "location");
+ contributionLocations.put(uri, location);
+ }
+ break;
+ default:
+ break;
+ }
+ reader.next();
+ }
+ } catch (Exception e) {
+ // Ignore
+ } finally {
+ IOHelper.closeQuietly(is);
+ }
+ }
+
+ private void saveMap() {
+ File domainFile = new File(rootFile, DOMAIN_INDEX_FILENAME);
+ FileOutputStream os = null;
+ try {
+ os = new FileOutputStream(domainFile);
+ PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
+ writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
+ writer.println("<domain uri=\"" + getDomain() + "\" xmlns=\"" + NS + "\">");
+ for (Map.Entry<String, String> e : contributionLocations.entrySet()) {
+ writer.println(" <contribution uri=\"" + e.getKey() + "\" location=\"" + e.getValue() + "\"/>");
+ }
+ writer.println("</domain>");
+ writer.flush();
+ } catch (IOException e) {
+ throw new IllegalArgumentException(e);
+ } finally {
+ IOHelper.closeQuietly(os);
+ }
+ }
+
+ public void destroy() {
+ }
+
+ public void addContribution(Contribution contribution) {
+ contributionMap.put(contribution.getURI(), contribution);
+ contributions.add(contribution);
+ }
+
+ public void removeContribution(Contribution contribution) {
+ contributionMap.remove(contribution.getURI());
+ contributions.remove(contribution);
+ }
+
+ public void updateContribution(Contribution contribution) {
+ Contribution oldContribution = contributionMap.remove(contribution.getURI());
+ contributions.remove(oldContribution);
+ contributionMap.put(contribution.getURI(), contribution);
+ contributions.add(contribution);
+ }
+
+ public Contribution getContribution(String uri) {
+ return contributionMap.get(uri);
+ }
+
+ public List<Contribution> getContributions() {
+ return Collections.unmodifiableList(contributions);
+ }
+
+}
diff --git a/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionServiceImpl.java b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionServiceImpl.java
new file mode 100644
index 0000000000..b817f339c1
--- /dev/null
+++ b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/ContributionServiceImpl.java
@@ -0,0 +1,442 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.contribution.service.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+
+import org.apache.tuscany.sca.assembly.AssemblyFactory;
+import org.apache.tuscany.sca.assembly.Composite;
+import org.apache.tuscany.sca.contribution.Contribution;
+import org.apache.tuscany.sca.contribution.ContributionFactory;
+import org.apache.tuscany.sca.contribution.DeployedArtifact;
+import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint;
+import org.apache.tuscany.sca.contribution.processor.PackageProcessor;
+import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor;
+import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor;
+import org.apache.tuscany.sca.contribution.resolver.ExtensibleModelResolver;
+import org.apache.tuscany.sca.contribution.resolver.ModelResolver;
+import org.apache.tuscany.sca.contribution.resolver.ModelResolverExtensionPoint;
+import org.apache.tuscany.sca.contribution.service.ContributionException;
+import org.apache.tuscany.sca.contribution.service.ContributionRepository;
+import org.apache.tuscany.sca.contribution.service.ContributionService;
+import org.apache.tuscany.sca.contribution.service.ExtensibleContributionListener;
+import org.apache.tuscany.sca.contribution.service.util.IOHelper;
+import org.apache.tuscany.sca.definitions.SCADefinitions;
+
+/**
+ * Service interface that manages artifacts contributed to a Tuscany runtime.
+ *
+ * @version $Rev$ $Date$
+ */
+/**
+ *
+ */
+public class ContributionServiceImpl implements ContributionService {
+
+ /**
+ * Repository where contributions are stored. Usually set by injection.
+ */
+ private ContributionRepository contributionRepository;
+
+ /**
+ * Registry of available package processors.
+ */
+ private PackageProcessor packageProcessor;
+
+ /**
+ * Registry of available artifact processors
+ */
+
+ private URLArtifactProcessor artifactProcessor;
+
+ /**
+ * Registry of available stax processors,
+ * used for loading contribution metadata in a extensible way
+ */
+ private StAXArtifactProcessor staxProcessor;
+
+ /**
+ * Event listener for contribution operations
+ */
+ private ExtensibleContributionListener contributionListener;
+
+ /**
+ * Registry of available model resolvers
+ */
+
+ private ModelResolverExtensionPoint modelResolvers;
+
+ /**
+ * Model factory extension point
+ */
+
+ private ModelFactoryExtensionPoint modelFactories;
+
+ /**
+ * xml factory used to create reader instance to load contribution metadata
+ */
+ private XMLInputFactory xmlFactory;
+
+ /**
+ * Assembly factory
+ */
+ private AssemblyFactory assemblyFactory;
+
+ /**
+ * Contribution model factory
+ */
+ private ContributionFactory contributionFactory;
+
+
+ private List<SCADefinitions> contributionSCADefinitions = new ArrayList<SCADefinitions>();
+
+ private ModelResolver domainResolver;
+
+ public ContributionServiceImpl(ContributionRepository repository,
+ PackageProcessor packageProcessor,
+ URLArtifactProcessor documentProcessor,
+ StAXArtifactProcessor staxProcessor,
+ ExtensibleContributionListener contributionListener,
+ ModelResolver domainResolver,
+ ModelResolverExtensionPoint modelResolvers,
+ ModelFactoryExtensionPoint modelFactories,
+ AssemblyFactory assemblyFactory,
+ ContributionFactory contributionFactory,
+ XMLInputFactory xmlFactory) {
+ super();
+ this.contributionRepository = repository;
+ this.packageProcessor = packageProcessor;
+ this.artifactProcessor = documentProcessor;
+ this.staxProcessor = staxProcessor;
+ this.contributionListener = contributionListener;
+ this.modelResolvers = modelResolvers;
+ this.modelFactories = modelFactories;
+ this.xmlFactory = xmlFactory;
+ this.assemblyFactory = assemblyFactory;
+ this.contributionFactory = contributionFactory;
+ this.domainResolver = domainResolver;
+ }
+
+ public Contribution contribute(String contributionURI, URL sourceURL, boolean storeInRepository)
+ throws ContributionException, IOException {
+ if (contributionURI == null) {
+ throw new IllegalArgumentException("URI for the contribution is null");
+ }
+ if (sourceURL == null) {
+ throw new IllegalArgumentException("Source URL for the contribution is null");
+ }
+
+ return addContribution(contributionURI, sourceURL, null, null, storeInRepository);
+ }
+
+ public Contribution contribute(String contributionURI,
+ URL sourceURL,
+ ModelResolver modelResolver,
+ boolean storeInRepository) throws ContributionException, IOException {
+ if (contributionURI == null) {
+ throw new IllegalArgumentException("URI for the contribution is null");
+ }
+ if (sourceURL == null) {
+ throw new IllegalArgumentException("Source URL for the contribution is null");
+ }
+
+ return addContribution(contributionURI, sourceURL, null, modelResolver, storeInRepository);
+ }
+
+ public Contribution contribute(String contributionURI, URL sourceURL, InputStream input)
+ throws ContributionException, IOException {
+
+ return addContribution(contributionURI, sourceURL, input, null, true);
+ }
+
+ public Contribution contribute(String contributionURI, URL sourceURL, InputStream input, ModelResolver modelResolver)
+ throws ContributionException, IOException {
+
+ return addContribution(contributionURI, sourceURL, input, modelResolver, true);
+ }
+
+ public Contribution getContribution(String uri) {
+ return this.contributionRepository.getContribution(uri);
+ }
+
+ /**
+ * Remove a contribution and notify listener that contribution was removed
+ */
+ public void remove(String uri) throws ContributionException {
+ Contribution contribution = contributionRepository.getContribution(uri);
+ this.contributionRepository.removeContribution(contribution);
+ this.contributionListener.contributionRemoved(this.contributionRepository, contribution);
+ }
+
+ /**
+ * Add a composite model to the contribution
+ */
+ public void addDeploymentComposite(Contribution contribution, Composite composite) throws ContributionException {
+ DeployedArtifact artifact = this.contributionFactory.createDeployedArtifact();
+ artifact.setURI(composite.getURI());
+ artifact.setModel(composite);
+
+ contribution.getArtifacts().add(artifact);
+
+ contribution.getDeployables().add(composite);
+ }
+
+ /**
+ * Utility/Helper methods for contribution service
+ */
+
+ /**
+ * Perform read of the contribution metada loader (sca-contribution.xml and sca-contribution-generated.xml)
+ * When the two metadata files are available, the information provided are merged, and the sca-contribution has priorities
+ *
+ * @param sourceURL
+ * @return Contribution
+ * @throws ContributionException
+ */
+ private Contribution readContributionMetadata(URL sourceURL) throws ContributionException {
+ Contribution contributionMetadata = null;
+
+ URL[] clUrls = {sourceURL};
+ URLClassLoader cl = new URLClassLoader(clUrls, null);
+
+ ContributionMetadataDocumentProcessor metadataDocumentProcessor =
+ new ContributionMetadataDocumentProcessor(cl, staxProcessor, assemblyFactory, contributionFactory,
+ xmlFactory);
+ contributionMetadata = contributionFactory.createContribution();
+ try {
+ metadataDocumentProcessor.read(contributionMetadata);
+ } catch (XMLStreamException e) {
+ throw new InvalidContributionMetadataException("Invalid contribution metadata for contribution.");
+ }
+
+ // For debugging purposes, write it back to XML
+ // if (contributionMetadata != null) {
+ // try {
+ // ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ // XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
+ // outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
+ // staxProcessor.write(contributionMetadata, outputFactory.createXMLStreamWriter(bos));
+ // Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(bos.toByteArray()));
+ // OutputFormat format = new OutputFormat();
+ // format.setIndenting(true);
+ // format.setIndent(2);
+ // XMLSerializer serializer = new XMLSerializer(System.out, format);
+ // serializer.serialize(document);
+ // } catch (Exception e) {
+ // e.printStackTrace();
+ // }
+ // }
+
+ return contributionMetadata;
+ }
+
+ /**
+ * Note:
+ *
+ * @param contributionURI ContributionID
+ * @param sourceURL contribution location
+ * @param contributionStream contribution content
+ * @param storeInRepository flag if we store the contribution into the
+ * repository or not
+ * @return the contribution model representing the contribution
+ * @throws IOException
+ * @throws DeploymentException
+ */
+ private Contribution addContribution(String contributionURI,
+ URL sourceURL,
+ InputStream contributionStream,
+ ModelResolver modelResolver,
+ boolean storeInRepository) throws IOException, ContributionException {
+
+ if (contributionStream == null && sourceURL == null) {
+ throw new IllegalArgumentException("The content of the contribution is null.");
+ }
+
+ // store the contribution in the contribution repository
+ URL locationURL = sourceURL;
+ if (contributionRepository != null && storeInRepository) {
+ if (contributionStream == null) {
+ locationURL = contributionRepository.store(contributionURI, sourceURL);
+ } else {
+ locationURL = contributionRepository.store(contributionURI, sourceURL, contributionStream);
+ }
+ }
+
+ //initialize contribution based on it's metadata if available
+ Contribution contribution = readContributionMetadata(locationURL);
+
+ // Create contribution model resolver
+ if (modelResolver == null) {
+ modelResolver = new ExtensibleModelResolver(contribution, modelResolvers, modelFactories);
+ }
+
+ if (modelResolver instanceof ExtensibleModelResolver) {
+ ((ExtensibleModelResolver)modelResolver).setDomainResolver(domainResolver);
+ }
+
+ //set contribution initial information
+ contribution.setURI(contributionURI.toString());
+ contribution.setLocation(locationURL.toString());
+ contribution.setModelResolver(modelResolver);
+
+ List<URI> contributionArtifacts = null;
+
+ //NOTE: if a contribution is stored on the repository
+ //the stream would be consumed at this point
+ if (storeInRepository || contributionStream == null) {
+ contributionStream = sourceURL.openStream();
+ try {
+ // process the contribution
+ contributionArtifacts = this.packageProcessor.getArtifacts(locationURL, contributionStream);
+ } finally {
+ IOHelper.closeQuietly(contributionStream);
+ contributionStream = null;
+ }
+ } else {
+ // process the contribution
+ contributionArtifacts = this.packageProcessor.getArtifacts(locationURL, contributionStream);
+ }
+
+ // Read all artifacts in the contribution
+ processReadPhase(contribution, contributionArtifacts);
+
+ //
+ this.contributionListener.contributionAdded(this.contributionRepository, contribution);
+
+ // Resolve them
+ processResolvePhase(contribution);
+
+ // Add all composites under META-INF/sca-deployables to the
+ // list of deployables
+ String prefix = Contribution.SCA_CONTRIBUTION_DEPLOYABLES;
+ for (DeployedArtifact artifact : contribution.getArtifacts()) {
+ if (artifact.getModel() instanceof Composite) {
+ if (artifact.getURI().startsWith(prefix)) {
+ Composite composite = (Composite)artifact.getModel();
+ if (!contribution.getDeployables().contains(composite)) {
+ contribution.getDeployables().add(composite);
+ }
+ }
+ }
+ }
+
+ // store the contribution on the registry
+ this.contributionRepository.addContribution(contribution);
+
+ return contribution;
+ }
+
+ /**
+ * This utility method process each artifact and delegates to proper
+ * artifactProcessor to read the model and generate the in-memory representation
+ *
+ * @param contribution
+ * @param artifacts
+ * @throws ContributionException
+ * @throws MalformedURLException
+ */
+ private void processReadPhase(Contribution contribution, List<URI> artifacts) throws ContributionException,
+ MalformedURLException {
+
+ ModelResolver modelResolver = contribution.getModelResolver();
+ URL contributionURL = new URL(contribution.getLocation());
+ for (URI a : artifacts) {
+ URL artifactURL = packageProcessor.getArtifactURL(new URL(contribution.getLocation()), a);
+
+ // Add the deployed artifact model to the resolver
+ DeployedArtifact artifact = this.contributionFactory.createDeployedArtifact();
+ artifact.setURI(a.toString());
+ artifact.setLocation(artifactURL.toString());
+ contribution.getArtifacts().add(artifact);
+ modelResolver.addModel(artifact);
+
+ // Let the artifact processor read the artifact into a model
+ Object model = this.artifactProcessor.read(contributionURL, a, artifactURL);
+ if (model != null) {
+ artifact.setModel(model);
+
+ // Add the loaded model to the model resolver
+ modelResolver.addModel(model);
+
+ if ( model instanceof SCADefinitions ) {
+ contributionSCADefinitions.add((SCADefinitions)model);
+ }
+ }
+ }
+ }
+
+ /**
+ * This utility method process each artifact and delegates to proper
+ * artifactProcessor to resolve the model references
+ *
+ * @param contribution
+ * @throws ContributionException
+ */
+ @SuppressWarnings("unchecked")
+ private void processResolvePhase(Contribution contribution) throws ContributionException {
+ List<DeployedArtifact> composites = new ArrayList<DeployedArtifact>();
+
+ // for each artifact that was processed on the contribution
+ for (DeployedArtifact artifact : contribution.getArtifacts()) {
+ //leave the composites to be resolved at the end
+ if (artifact.getURI().endsWith(".composite")) {
+ composites.add(artifact);
+ } else {
+ // resolve the model object
+ if (artifact.getModel() != null) {
+ this.artifactProcessor.resolve(artifact.getModel(), contribution.getModelResolver());
+ }
+ }
+ }
+
+ //process each composite file
+ for (DeployedArtifact artifact : composites) {
+ // resolve the model object
+ if (artifact.getModel() != null) {
+ // System.out.println("Processing Resolve Phase : " + artifact.getURI());
+ this.artifactProcessor.resolve(artifact.getModel(), contribution.getModelResolver());
+ }
+ }
+
+ //resolve deployables from contribution metadata
+ List<Composite> resolvedDeployables = new ArrayList<Composite>();
+ for (Composite deployableComposite : contribution.getDeployables()) {
+ Composite resolvedDeployable =
+ contribution.getModelResolver().resolveModel(Composite.class, deployableComposite);
+
+ resolvedDeployables.add(resolvedDeployable);
+ }
+ contribution.getDeployables().clear();
+ contribution.getDeployables().addAll(resolvedDeployables);
+ }
+
+ public List<SCADefinitions> getContributionSCADefinitions() {
+ return contributionSCADefinitions;
+ }
+}
diff --git a/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/InvalidContributionMetadataException.java b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/InvalidContributionMetadataException.java
new file mode 100644
index 0000000000..6fbf46a5b4
--- /dev/null
+++ b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/InvalidContributionMetadataException.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.contribution.service.impl;
+
+import org.apache.tuscany.sca.contribution.service.ContributionException;
+
+/**
+ * Exception that indicates that the supplied XML Document invalid.
+ *
+ * @version $Rev$ $Date$
+ */
+public class InvalidContributionMetadataException extends ContributionException {
+
+ private static final long serialVersionUID = -3184477070625689942L;
+
+ protected InvalidContributionMetadataException() {
+ }
+
+ protected InvalidContributionMetadataException(String message) {
+ super(message);
+ }
+
+ protected InvalidContributionMetadataException(String message, String identifier) {
+ super(message, identifier);
+ }
+
+ protected InvalidContributionMetadataException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ protected InvalidContributionMetadataException(String message, String identifier, Throwable cause) {
+ super(message, identifier, cause);
+ }
+
+ protected InvalidContributionMetadataException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/InvalidContributionURIException.java b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/InvalidContributionURIException.java
new file mode 100644
index 0000000000..e243294bd0
--- /dev/null
+++ b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/InvalidContributionURIException.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.contribution.service.impl;
+
+import org.apache.tuscany.sca.contribution.service.ContributionException;
+
+/**
+ * Exception that indicates that the supplied contribution URI is invalid or inexistent.
+ *
+ * @version $Rev$ $Date$
+ */
+public class InvalidContributionURIException extends ContributionException {
+
+ private static final long serialVersionUID = -3184477070625689942L;
+
+ protected InvalidContributionURIException() {
+ }
+
+ protected InvalidContributionURIException(String message) {
+ super(message);
+ }
+
+ protected InvalidContributionURIException(String message, String identifier) {
+ super(message, identifier);
+ }
+
+ protected InvalidContributionURIException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ protected InvalidContributionURIException(String message, String identifier, Throwable cause) {
+ super(message, identifier, cause);
+ }
+
+ protected InvalidContributionURIException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/PackageTypeDescriberImpl.java b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/PackageTypeDescriberImpl.java
new file mode 100644
index 0000000000..165c9d0616
--- /dev/null
+++ b/branches/sca-java-1.1/modules/contribution-impl/src/main/java/org/apache/tuscany/sca/contribution/service/impl/PackageTypeDescriberImpl.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.contribution.service.impl;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.tuscany.sca.contribution.ContentType;
+import org.apache.tuscany.sca.contribution.service.TypeDescriber;
+import org.apache.tuscany.sca.contribution.service.util.FileHelper;
+
+/**
+ * Implementation of the content describer for contribution packages
+ *
+ * @version $Rev$ $Date$
+ */
+public class PackageTypeDescriberImpl implements TypeDescriber {
+ private final Map<String, String> contentTypeRegistry = new HashMap<String, String>();
+
+ public PackageTypeDescriberImpl() {
+ super();
+ init();
+ }
+
+ /**
+ * Initialize contentType registry with know types based on known file extensions
+ */
+ private void init() {
+ contentTypeRegistry.put("JAR", ContentType.JAR);
+ }
+
+ protected String resolveContentyTypeByExtension(URL resourceURL) {
+ String artifactExtension = FileHelper.getExtension(resourceURL.getPath());
+ if (artifactExtension == null) {
+ return null;
+ }
+ return contentTypeRegistry.get(artifactExtension.toUpperCase());
+ }
+
+ /**
+ * Build contentType for a specific resource. We first check if the file is
+ * a supported one (looking into our registry based on resource extension)
+ * If not found, we try to check file contentType Or we return
+ * defaultContentType provided
+ *
+ * @param resourceURL The artifact url
+ * @param defaultContentType The default content type if we can't find the correc one
+ * @return The content type
+ */
+ public String getType(URL resourceURL, String defaultContentType) {
+ URLConnection connection = null;
+ String contentType = defaultContentType;
+
+ if (resourceURL.getProtocol().equals("file") && FileHelper.toFile(resourceURL).isDirectory()) {
+ // Special case : contribution is a folder
+ contentType = ContentType.FOLDER;
+ } else {
+ contentType = resolveContentyTypeByExtension(resourceURL);
+ if (contentType == null) {
+ try {
+ connection = resourceURL.openConnection();
+ contentType = connection.getContentType();
+
+ if (contentType == null || contentType.equals("content/unknown")) {
+ // here we couldn't figure out from our registry or from URL and it's not a special file
+ // return defaultContentType if provided
+ contentType = defaultContentType;
+ }
+ } catch (IOException io) {
+ // could not access artifact, just ignore and we will return
+ // null contentType
+ }
+ }
+ }
+ return contentType == null ? defaultContentType : contentType;
+ }
+
+}