aries-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From z..@apache.org
Subject svn commit: r1075132 [10/18] - in /aries/tags/application-0.3: ./ application-api/ application-api/src/ application-api/src/main/ application-api/src/main/java/ application-api/src/main/java/org/ application-api/src/main/java/org/apache/ application-ap...
Date Sun, 27 Feb 2011 20:20:30 GMT
Added: aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModelledResourceManagerImpl.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModelledResourceManagerImpl.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModelledResourceManagerImpl.java (added)
+++ aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModelledResourceManagerImpl.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,210 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.impl;
+
+import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY;
+import static org.apache.aries.application.utils.AppConstants.LOG_EXIT;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.jar.Attributes;
+
+import org.apache.aries.application.InvalidAttributeException;
+import org.apache.aries.application.filesystem.IDirectory;
+import org.apache.aries.application.filesystem.IFile;
+import org.apache.aries.application.modelling.ExportedService;
+import org.apache.aries.application.modelling.ImportedService;
+import org.apache.aries.application.modelling.ModelledResource;
+import org.apache.aries.application.modelling.ModelledResourceManager;
+import org.apache.aries.application.modelling.ModellerException;
+import org.apache.aries.application.modelling.ModellingManager;
+import org.apache.aries.application.modelling.ParsedServiceElements;
+import org.apache.aries.application.modelling.ParserProxy;
+import org.apache.aries.application.modelling.internal.BundleBlueprintParser;
+import org.apache.aries.application.utils.manifest.BundleManifest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class ModelledResourceManagerImpl implements ModelledResourceManager
+{
+  private Logger _logger = LoggerFactory.getLogger(ModelledResourceManagerImpl.class);
+  private ParserProxy _parserProxy;
+  private ModellingManager _modellingManager;
+  
+  public void setModellingManager (ModellingManager m) { 
+    _modellingManager = m;
+  }
+  
+  public void setParserProxy (ParserProxy p) { 
+    _parserProxy = p;
+  }
+  public ParserProxy getParserProxy()
+  {
+	  return _parserProxy;
+  }
+  
+
+
+  /**
+   * For a given file, which we know to be a bundle, parse out all the
+   * service, reference and reference-list elements. This method will return
+   * all such services, including anonymous ones, 
+   * but should not return indistinguishable duplicates. 
+   * @param archive CommonArchive. The caller is responsible for closing this afterwards. 
+   * @return ParsedServiceElementsImpl 
+   * @throws OpenFailureException 
+   */
+  @Override
+  public ParsedServiceElements getServiceElements (IDirectory archive) throws ModellerException { 
+
+    _logger.debug(LOG_ENTRY,"getServiceElements", archive );
+
+    Set<ExportedService> services = new HashSet<ExportedService>();
+    Set<ImportedService> references = new HashSet<ImportedService>();
+    try { 
+      Collection<IFile> blueprints = findBlueprints(archive);
+      InputStream is = null;
+      for (IFile bpFile : blueprints) {
+        URL url = bpFile.toURL();
+        URLConnection conn = url.openConnection();
+        is = conn.getInputStream();
+        
+        try {
+          ParsedServiceElements pse = getParserProxy().parseAllServiceElements(is);
+          services.addAll(pse.getServices());
+          references.addAll(pse.getReferences());
+
+        } finally {
+          if (is != null) {
+            is.close();
+          }
+        }
+      }
+    } catch (URISyntaxException e) {
+      ModellerException m = new ModellerException(e);
+      _logger.debug(LOG_EXIT, "getServiceElements", m);
+      throw m;
+    } catch (IOException e) {
+      ModellerException m = new ModellerException(e);
+      _logger.debug(LOG_EXIT, "getServiceElements", m);
+      throw m;
+    } catch (Exception e) {
+      ModellerException m = new ModellerException(e);
+      _logger.debug(LOG_EXIT, "getServiceElements", m);
+      throw m;
+    } 
+    ParsedServiceElements result = _modellingManager.getParsedServiceElements(services, references);
+    _logger.debug(LOG_EXIT, "getServiceElements", result);
+    return result;
+  }
+
+  @Override
+  public ModelledResource getModelledResource(String uri, IDirectory bundle) throws ModellerException{
+    _logger.debug(LOG_ENTRY, "getModelledResource", new Object[]{uri, bundle});
+    ParsedServiceElements pse = getServiceElements(bundle);
+
+    BundleManifest bm = BundleManifest.fromBundle(new File(bundle.toString()));
+    Attributes attributes = bm.getRawAttributes();
+    ModelledResource mbi;
+    try {
+      mbi = _modellingManager.getModelledResource(uri, attributes, pse.getReferences(), pse.getServices());
+    } catch (InvalidAttributeException iae) {
+      throw new ModellerException(iae);
+    }
+    _logger.debug(LOG_EXIT, "getModelledResource", mbi);
+    return mbi;
+  }
+
+  /**
+   * Helper method to pass a single bundle into findBlueprints 
+   * @param oneBundle a single bundle
+   * @return Files for all the blueprint files within the bundle
+   * @throws URISyntaxException
+   * @throws IOException
+   * @throws OpenFailureException
+   */
+  private Collection<IFile> findBlueprints (IDirectory oneBundle) 
+  throws  IOException, URISyntaxException
+  {
+    _logger.debug(LOG_ENTRY, "findBlueprints", oneBundle);
+    Set<IDirectory> archiveSet = new HashSet<IDirectory>();
+    archiveSet.add(oneBundle);
+    Collection<IFile> result = findBlueprints (archiveSet);
+    _logger.debug(LOG_EXIT, "findBlueprints", result);
+    return result;
+  }
+
+  /**
+   * Locate all blueprint xml files located within a set of bundles. Typically, call findApplicationBundles()
+   * first to determine which bundles within an EBA fall within the range of the Application-Content header. 
+   * (See the comment on that method). 
+   * @param applicationBundles
+   * @return A Collection of blue print files
+   * @throws URISyntaxException
+   * @throws IOException
+   * @throws OpenFailureException
+   */
+  private Collection<IFile> findBlueprints(Collection<IDirectory> applicationBundles)
+  throws IOException, URISyntaxException
+  {
+    _logger.debug(LOG_ENTRY, "findBlueprints", applicationBundles);
+    Collection<IFile> blueprints = new ArrayList<IFile>();
+    for (IDirectory appBundle : applicationBundles) {
+      if (appBundle != null) {
+        BundleManifest bundleMf = BundleManifest.fromBundle(appBundle);
+        BundleBlueprintParser bpParser = new BundleBlueprintParser(bundleMf);
+        List<IFile> files = appBundle.listAllFiles();
+        Iterator<IFile> it = files.iterator();
+        while (it.hasNext()) {
+          IFile file = (IFile) it.next();         
+          String directoryFullPath = file.getName(); 
+          String directoryName = "";
+          String fileName = "";
+          if (directoryFullPath.lastIndexOf("/") != -1) {
+            directoryName = directoryFullPath.substring(0, directoryFullPath.lastIndexOf("/"));
+            fileName = directoryFullPath.substring(directoryFullPath.lastIndexOf("/") + 1);
+          } else {
+            if (file.isFile()) {
+              directoryName="";
+              fileName = directoryFullPath;
+            } 
+
+          }
+          if (bpParser.isBPFile(directoryName, fileName)) {
+            blueprints.add(file);
+          }
+        }
+      }
+    }
+    _logger.debug(LOG_EXIT, "findBlueprints", blueprints);
+    return blueprints;
+  }
+}

Added: aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModellingManagerImpl.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModellingManagerImpl.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModellingManagerImpl.java (added)
+++ aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModellingManagerImpl.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,139 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.impl;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.jar.Attributes;
+
+import org.apache.aries.application.InvalidAttributeException;
+import org.apache.aries.application.management.BundleInfo;
+import org.apache.aries.application.modelling.ExportedBundle;
+import org.apache.aries.application.modelling.ExportedPackage;
+import org.apache.aries.application.modelling.ExportedService;
+import org.apache.aries.application.modelling.ImportedBundle;
+import org.apache.aries.application.modelling.ImportedPackage;
+import org.apache.aries.application.modelling.ImportedService;
+import org.apache.aries.application.modelling.ModelledResource;
+import org.apache.aries.application.modelling.ModellingManager;
+import org.apache.aries.application.modelling.ParsedServiceElements;
+import org.apache.aries.application.modelling.ResourceType;
+
+public class ModellingManagerImpl implements ModellingManager
+{
+
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getExportedBundle(java.util.Map, org.apache.aries.application.modelling.ImportedBundle)
+   */
+  public ExportedBundle getExportedBundle(Map<String, String> attributes, ImportedBundle fragHost) {
+
+    return new ExportedBundleImpl(attributes, fragHost);
+  }
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getExportedPackage(org.apache.aries.application.modelling.ModelledResource, java.lang.String, java.util.Map)
+   */
+  public ExportedPackage getExportedPackage(ModelledResource mr, String pkg, Map<String, Object> attributes)  {
+
+    return new ExportedPackageImpl(mr, pkg, attributes);
+  }
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getExportedService(java.lang.String, int, java.util.Collection, java.util.Map)
+   */
+  public ExportedService getExportedService(String name, int ranking, Collection<String> ifaces, 
+      Map<String, Object> serviceProperties ) {
+    return new ExportedServiceImpl (name, ranking, ifaces, serviceProperties );
+  }
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getExportedService(java.lang.String, java.util.Map)
+   */
+  @SuppressWarnings("deprecation")
+  public ExportedService getExportedService(String ifaceName, Map<String, String> attrs) {
+    return new ExportedServiceImpl (ifaceName, attrs );
+  }
+  
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getImportedBundle(java.lang.String, java.util.Map)
+   */
+  public ImportedBundle getImportedBundle(String filterString, Map<String, String> attributes) throws InvalidAttributeException {
+    return new ImportedBundleImpl(filterString, attributes);
+  }
+  
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getImportedBundle(java.lang.String, java.lang.String)
+   */
+  public ImportedBundle getImportedBundle(String bundleName, String versionRange) throws InvalidAttributeException {
+    return new ImportedBundleImpl(bundleName, versionRange);
+  }
+  
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getImportedPackage(java.lang.String, java.util.Map)
+   */
+  public ImportedPackage getImportedPackage(String pkg, Map<String, String> attributes) throws InvalidAttributeException{
+    return new ImportedPackageImpl(pkg, attributes);
+  }
+  
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getImportedService(boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean)
+   */
+  public ImportedService getImportedService(boolean optional, String iface, String componentName, 
+      String blueprintFilter, String id, boolean isMultiple) throws InvalidAttributeException{
+    return new ImportedServiceImpl(optional, iface, componentName, blueprintFilter, id, isMultiple);
+  }
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getImportedService(java.lang.String, java.util.Map)
+   */
+  @SuppressWarnings("deprecation")
+  public ImportedService getImportedService(String ifaceName, Map<String, String> attributes) throws InvalidAttributeException{
+    return new ImportedServiceImpl(ifaceName, attributes);
+  }
+  
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getModelledResource(java.lang.String, org.apache.aries.application.management.BundleInfo, java.util.Collection, java.util.Collection)
+   */
+  public ModelledResource getModelledResource(String fileURI, BundleInfo bundleInfo, 
+      Collection<ImportedService> importedServices, 
+      Collection<ExportedService> exportedServices) throws InvalidAttributeException {
+    return new ModelledResourceImpl(fileURI, bundleInfo, importedServices, exportedServices);
+    
+  }
+  
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getModelledResource(java.lang.String, java.util.jar.Attributes, java.util.Collection, java.util.Collection)
+   */
+  public ModelledResource getModelledResource(String fileURI, Attributes bundleAttributes, 
+      Collection<ImportedService> importedServices, 
+      Collection<ExportedService> exportedServices) throws InvalidAttributeException {
+    return new ModelledResourceImpl(fileURI, bundleAttributes, importedServices, exportedServices);
+    
+  }
+  
+  /* (non-Javadoc)
+   * @see org.apache.aries.application.modelling.ModellingManager#getParsedServiceElements(java.util.Collection, java.util.Collection)
+   */
+  public ParsedServiceElements getParsedServiceElements ( Collection<ExportedService> services, 
+      Collection<ImportedService> references) {
+    return new ParsedServiceElementsImpl(services, references);
+  }
+  public ModelledResource getModelledResource(String fileURI,
+      Attributes bundleAttributes, ExportedBundle exportedBundle,
+      ResourceType resourceType, Collection<ImportedService> importedServices,
+      Collection<ExportedService> exportedServices) throws InvalidAttributeException {
+    return new ModelledResourceImpl(fileURI, bundleAttributes, exportedBundle, resourceType, importedServices, exportedServices);
+  }
+}

Added: aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParsedServiceElementsImpl.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParsedServiceElementsImpl.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParsedServiceElementsImpl.java (added)
+++ aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParsedServiceElementsImpl.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,80 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.impl;
+
+
+import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY;
+import static org.apache.aries.application.utils.AppConstants.LOG_EXIT;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.aries.application.modelling.ExportedService;
+import org.apache.aries.application.modelling.ImportedService;
+import org.apache.aries.application.modelling.ParsedServiceElements;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A simple data structure containing two immutable Collections, 
+ * one each of ImportedServiceImpl and ExportedServiceImpl
+ */
+public final class ParsedServiceElementsImpl implements ParsedServiceElements
+{
+ 
+  private final Logger logger = LoggerFactory.getLogger(ParsedServiceElementsImpl.class);
+  private final Set<ExportedService> _services;
+  private final Set<ImportedService> _references;
+  
+  /**
+   * Copy collections of Service and Reference metadata into a ParsedServiceElementsImpl
+   * @param services
+   * @param references
+   */
+  public ParsedServiceElementsImpl ( Collection<ExportedService> services, 
+      Collection<ImportedService> references) { 
+    logger.debug(LOG_ENTRY, "ParsedServiceElementsImpl", new Object[]{services, references});
+    _services = new HashSet<ExportedService>(services);
+    _references = new HashSet<ImportedService>(references);
+    logger.debug(LOG_ENTRY, "ParsedServiceElementsImpl");
+  }
+
+  /**
+   * Get the ImportedServices
+   * @return imported services
+   */
+  public Collection<ImportedService> getReferences() {
+    logger.debug(LOG_ENTRY, "getReferences");
+    logger.debug(LOG_EXIT, "getReferences", _references);
+    return Collections.unmodifiableCollection(_references);
+  }
+
+  /**
+   * Get the exported services
+   * @return exported services
+   */
+  public Collection<ExportedService> getServices() {
+    logger.debug(LOG_ENTRY, "getServices");
+    logger.debug(LOG_EXIT, "getServices", _services);
+    return Collections.unmodifiableCollection(_services);
+  }
+}

Added: aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParserProxyImpl.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParserProxyImpl.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParserProxyImpl.java (added)
+++ aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParserProxyImpl.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,275 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.impl;
+import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY;
+import static org.apache.aries.application.utils.AppConstants.LOG_EXIT;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.aries.application.InvalidAttributeException;
+import org.apache.aries.application.modelling.ExportedService;
+import org.apache.aries.application.modelling.ImportedService;
+import org.apache.aries.application.modelling.ModellingManager;
+import org.apache.aries.application.modelling.ParsedServiceElements;
+import org.apache.aries.application.modelling.ParserProxy;
+import org.apache.aries.application.modelling.WrappedServiceMetadata;
+import org.apache.aries.application.utils.manifest.ManifestHeaderProcessor;
+import org.apache.aries.blueprint.ComponentDefinitionRegistry;
+import org.apache.aries.blueprint.ParserService;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.blueprint.reflect.BeanMetadata;
+import org.osgi.service.blueprint.reflect.CollectionMetadata;
+import org.osgi.service.blueprint.reflect.ComponentMetadata;
+import org.osgi.service.blueprint.reflect.MapEntry;
+import org.osgi.service.blueprint.reflect.Metadata;
+import org.osgi.service.blueprint.reflect.RefMetadata;
+import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
+import org.osgi.service.blueprint.reflect.ServiceMetadata;
+import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
+import org.osgi.service.blueprint.reflect.Target;
+import org.osgi.service.blueprint.reflect.ValueMetadata;
+import org.osgi.service.jndi.JNDIConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ParserProxyImpl implements ParserProxy {
+  private Logger _logger = LoggerFactory.getLogger(ParserProxyImpl.class);
+  private ParserService _parserService;
+  private BundleContext _bundleContext;
+  private ModellingManager _modellingManager;
+  
+  public void setParserService (ParserService p) { 
+    _parserService = p;
+  }
+  
+  public void setBundleContext (BundleContext b) { 
+    _bundleContext = b;
+  }
+  
+  public void setModellingManager (ModellingManager m) { 
+    _modellingManager = m;
+  }
+  
+  @Override
+  public List<? extends WrappedServiceMetadata> parse(List<URL> blueprintsToParse) throws Exception {
+    _logger.debug(LOG_ENTRY, "parse", new Object[]{blueprintsToParse});
+    ComponentDefinitionRegistry cdr = _parserService.parse (blueprintsToParse, _bundleContext.getBundle());
+    List<? extends WrappedServiceMetadata> result = parseCDRForServices (cdr, true);
+    _logger.debug(LOG_EXIT, "parse", new Object[]{result});
+    return result;
+  }
+   
+  @Override
+  public List<? extends WrappedServiceMetadata> parse(URL blueprintToParse) throws Exception {
+    _logger.debug(LOG_ENTRY, "parse", new Object[]{blueprintToParse});
+    List<URL> list = new ArrayList<URL>();
+    list.add(blueprintToParse);
+   
+    List<? extends WrappedServiceMetadata> result = parse (list);
+    _logger.debug(LOG_EXIT, "parse", new Object[]{result});
+    return result;
+  }
+
+  @Override
+  public List<? extends WrappedServiceMetadata> parse(InputStream blueprintToParse) throws Exception {
+    _logger.debug(LOG_ENTRY, "parse", new Object[]{blueprintToParse});
+    ComponentDefinitionRegistry cdr = _parserService.parse (blueprintToParse, _bundleContext.getBundle());
+    List<? extends WrappedServiceMetadata> result = parseCDRForServices (cdr, true);
+    _logger.debug(LOG_EXIT, "parse", new Object[]{result});
+    return result;
+  }
+ 
+
+  @Override
+  public ParsedServiceElements parseAllServiceElements(InputStream blueprintToParse) throws Exception {
+    _logger.debug(LOG_ENTRY, "parseAllServiceElements", new Object[]{blueprintToParse});
+    ComponentDefinitionRegistry cdr = _parserService.parse (blueprintToParse, _bundleContext.getBundle());
+    Collection<ExportedService> services = parseCDRForServices(cdr, false);
+    Collection<ImportedService> references = parseCDRForReferences (cdr);
+    ParsedServiceElements result = _modellingManager.getParsedServiceElements(services, references);
+    _logger.debug(LOG_EXIT, "parseAllServiceElements", new Object[]{result});
+    return result;
+  }
+  
+  /**
+   * Extract Service metadata from a ComponentDefinitionRegistry. When doing SCA modelling, we
+   * need to suppress anonymous services. We don't want to do that when we're modelling for 
+   * provisioning dependencies. 
+   * @param cdr                       ComponentDefinitionRegistry
+   * @param suppressAnonymousServices Unnamed services will not be returned if this is true
+   * @return List<WrappedServiceMetadata>
+   */
+  private List<ExportedService> parseCDRForServices (ComponentDefinitionRegistry cdr, 
+      boolean suppressAnonymousServices) { 
+    _logger.debug(LOG_ENTRY, "parseCDRForServices", new Object[]{cdr, suppressAnonymousServices});
+    List<ExportedService> result = new ArrayList<ExportedService>();
+    Set<String> names = cdr.getComponentDefinitionNames();
+    for (String name: names) { 
+      ComponentMetadata compMetadata = cdr.getComponentDefinition(name);
+      if (compMetadata instanceof ServiceMetadata) { 
+        ServiceMetadata serviceMetadata = (ServiceMetadata)compMetadata;
+        String serviceName;
+        int ranking;
+        Collection<String> interfaces = new ArrayList<String>(); 
+        Map<String, Object> serviceProps = new HashMap<String, Object>();
+
+        ranking = serviceMetadata.getRanking();
+        for (Object i : serviceMetadata.getInterfaces()) {
+          interfaces.add((String)i);
+        }
+        
+        // get the service properties
+        List<MapEntry> props = serviceMetadata.getServiceProperties();
+        for (MapEntry entry : props) { 
+          String key = ((ValueMetadata)entry.getKey()).getStringValue();
+          
+          Metadata value = entry.getValue();
+          if (value instanceof CollectionMetadata) { 
+            List<Metadata> values = ((CollectionMetadata)value).getValues();
+            String[] theseValues = new String[values.size()];
+            for (int i=0; i < values.size(); i++) { 
+              Metadata m = values.get(i); 
+              theseValues[i] = ((ValueMetadata)m).getStringValue();
+            }
+            serviceProps.put(key, theseValues);
+          } else { 
+            serviceProps.put(key, ((ValueMetadata)entry.getValue()).getStringValue());
+          }
+        }
+
+        // serviceName: use the service id unless that's not set, 
+        // in which case we use the bean id. 
+        serviceName = serviceMetadata.getId();
+        
+        // If the Service references a Bean, export the bean id as a service property
+        // as per 121.6.5 p669 of the blueprint 1.0 specification
+        Target t = serviceMetadata.getServiceComponent();
+        String targetId = null;
+        if (t instanceof RefMetadata) { 
+          targetId = ((RefMetadata)t).getComponentId();
+        } else if (t instanceof BeanMetadata) { 
+          targetId = ((BeanMetadata)t).getId();
+        }
+        
+        // Our OBR code MUST have access to targetId if it's available (i.e. not null 
+        // or auto-generated for an anonymous service. This must ALWAYS be set. 
+        if (targetId != null && !targetId.startsWith(".")) { // Don't set this for anonymous inner components
+            serviceProps.put("osgi.service.blueprint.compname", targetId);
+          if (serviceName == null || serviceName.equals("") || serviceName.startsWith(".")) { 
+            serviceName = targetId;
+          }
+        }
+        
+        if(serviceName != null && serviceName.startsWith("."))
+          serviceName = null;
+        
+        // If suppressAnonymous services, do not expose services that have no name
+        if (!suppressAnonymousServices || (serviceName != null)) { 
+          ExportedService wsm = _modellingManager.getExportedService(serviceName, ranking, interfaces, serviceProps);
+          result.add(wsm);
+        }
+      }
+    }
+    _logger.debug(LOG_EXIT, "parseAllServiceElements", new Object[]{result});
+    return result; 
+  }
+
+  /**
+   * Extract References metadata from a ComponentDefinitionRegistry. 
+   * @param cdr                       ComponentDefinitionRegistry
+   * @return List<WrappedReferenceMetadata>
+   * @throws InvalidAttributeException 
+   */
+  private List<ImportedService> parseCDRForReferences (ComponentDefinitionRegistry cdr) throws InvalidAttributeException { 
+    _logger.debug(LOG_ENTRY, "parseCDRForReferences", new Object[]{cdr});
+    List<ImportedService> result = new ArrayList<ImportedService>();
+    Set<String> names = cdr.getComponentDefinitionNames();
+    for (String name: names) { 
+      ComponentMetadata compMetadata = cdr.getComponentDefinition(name);
+      if (compMetadata instanceof ServiceReferenceMetadata) { 
+        ServiceReferenceMetadata referenceMetadata = (ServiceReferenceMetadata)compMetadata;
+
+        boolean optional = referenceMetadata.getAvailability() == ServiceReferenceMetadata.AVAILABILITY_OPTIONAL;
+        String iface = referenceMetadata.getInterface();
+        String compName = referenceMetadata.getComponentName();
+        String blueprintFilter = referenceMetadata.getFilter();
+        String id = referenceMetadata.getId();
+        boolean isMultiple = (referenceMetadata instanceof ReferenceListMetadata);
+        
+        //The blueprint parser teams up with JPA and blueprint resource ref
+        // namespace handlers to give us service imports of the form, 
+        // objectClass=javax.persistence.EntityManagerFactory, org.apache.aries.jpa.proxy.factory=*, osgi.unit.name=blabber
+        //
+        // There will be no matching service for this reference. 
+        // For now we blacklist certain objectClasses and filters - this is a pretty dreadful thing to do. 
+        if (isNotBlacklisted (iface, blueprintFilter)) { 
+          ImportedService ref = _modellingManager.getImportedService (optional, iface, compName, blueprintFilter, 
+              id, isMultiple);
+          result.add (ref);  
+        }
+      }
+    }
+    _logger.debug(LOG_EXIT, "parseCDRForReferences", new Object[]{result});
+    return result; 
+  }
+  
+  /**
+   * Some services are injected directly into isolated frameworks by default. We do 
+   * not need to model these services. They are not represented as ExportedServices 
+   * (Capabilities) in the various OBR registries, and so cannot be resolved against. 
+   * Since they are injected directly into each isolated framework, we do not need
+   * an entry in DEPLOYMENT.MF's Deployed-ImportService header for any of these 
+   * services. 
+   * 
+   * @param iface           The interface declared on a blueprint reference
+   * @param blueprintFilter The filter on the blueprint reference
+   * @return                True if the service is not 'blacklisted' and so may be exposed
+   *                        in the model being generated. 
+   */
+  private boolean isNotBlacklisted (String iface, String blueprintFilter) { 
+    _logger.debug(LOG_ENTRY, "isNotBlacklisted", new Object[]{iface, blueprintFilter});
+    boolean blacklisted = false;
+    if (iface != null) {
+      // JPA - detect interface;
+      blacklisted |= iface.equals("javax.persistence.EntityManagerFactory");
+      blacklisted |= iface.equals("javax.persistence.EntityManager");
+    
+      // JTA - detect interface
+      blacklisted |= iface.equals("javax.transaction.UserTransaction");
+      blacklisted |= iface.equals("javax.transaction.TransactionSynchronizationRegistry");
+      
+      // Don't provision against JNDI references
+      if (blueprintFilter != null && !blueprintFilter.trim().isEmpty()) { 
+        Map<String, String> filter = ManifestHeaderProcessor.parseFilter(blueprintFilter);
+        blacklisted |= filter.containsKey(JNDIConstants.JNDI_SERVICENAME);
+      }
+    }
+    _logger.debug(LOG_EXIT, "isNotBlacklisted", new Object[]{!blacklisted});
+    return !blacklisted;
+  }
+
+ 
+}

Added: aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/BundleBlueprintParser.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/BundleBlueprintParser.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/BundleBlueprintParser.java (added)
+++ aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/BundleBlueprintParser.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,161 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.internal;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.apache.aries.application.utils.manifest.BundleManifest;
+import org.apache.aries.application.utils.manifest.ManifestHeaderProcessor;
+
+/**
+ * A bundle may contain a Bundle-Blueprint: header as per p649 of the v4 spec. If present, 
+ * this denotes where to look for blueprint xml files. We could use Bundle.findEntries() 
+ * to deal with the wildcards that the last entry in the list may contain, but our caller
+ * is introspecting .jar files within an EBA and does not have  access to Bundle objects, 
+ * so we need this extra support. Our caller needs to iterate over the files 
+ * within a jar in each case asking this class, 'is this a blueprint file'?
+ *
+ */
+public class BundleBlueprintParser {
+  
+  public static final String DEFAULT_HEADER = "OSGI-INF/blueprint/*.xml";
+  
+  String _mfHeader = null;
+  List<Path> _paths;
+  
+  static class Path { 
+    String directory;
+    String filename;  // This will either be a simple filename or 'null', in which case filenamePattern will be set
+    Pattern filenamePattern;
+    public Path (String d, String f) { 
+      directory = d;
+      if (f.contains("*")) { 
+        filename = null;
+        String pattern = f.replace(".", "\\.");
+        pattern = pattern.replace("*", ".*");
+        filenamePattern = Pattern.compile(pattern);
+      } else { 
+        filename = f;
+        filenamePattern = null;
+      }
+    }
+    
+    /**
+     * Match this Path object against a specific directory, file pair. Case sensitive. 
+     * @param dir Directory
+     * @param fil Filename - may not contain a wildcard
+     * @return true these match
+     */
+    public boolean matches (String dir, String fil) {
+      boolean match = false;
+      if (!directory.equals(dir)) { 
+        match = false;
+      } else if (filename != null) { 
+        match = (filename.equals(fil));
+      } else { 
+        match = filenamePattern.matcher(fil).matches();
+      }
+      return match;
+    }
+  }
+  
+  /**
+   * BundleBlueprintParser constructor
+   * @param bundleMf BundleManifest to construct the parser from
+   */
+  public BundleBlueprintParser (BundleManifest bundleMf) {
+    String bundleBPHeader = (String) bundleMf.getRawAttributes().getValue("Bundle-Blueprint");
+    setup (bundleBPHeader);
+  }
+
+  /**
+   * BundleBlueprintParser alternative constructor
+   * @param bundleBPHeader Bundle-Blueprint header to construct the parser from
+   */
+  public BundleBlueprintParser (String bundleBPHeader) {
+    setup (bundleBPHeader);
+  }
+  
+  /**
+   * Default constructor
+   */
+  public BundleBlueprintParser () { 
+    setup(null);
+  }
+  
+  private void setup (String bundleBPHeader) { 
+    _paths = new LinkedList <Path>();
+    if (bundleBPHeader == null) { 
+      _mfHeader = DEFAULT_HEADER;
+    } else { 
+      _mfHeader = bundleBPHeader;
+    }
+    
+    // Break this comma separated list up
+    List<String> files = ManifestHeaderProcessor.split(_mfHeader, ",");
+    clauses: for (String fileClause : files) {
+
+      // we could be doing directives, so we split again, the clause can
+      // have multiple paths with directives at the end.
+        
+      List<String> yetMoreFiles = ManifestHeaderProcessor.split(fileClause, ";");
+      for (String f : yetMoreFiles) {
+          
+        // if f has an = in it then we have hit the directive, which must
+        // be at the end, we do not have any directives so we just continue
+        // onto the next clause.
+        if (f.contains("=")) continue clauses;
+          
+        // we need to make sure we have zero spaces here, otherwise stuff may
+        // not be found.
+        f = f.trim();
+        if (f.startsWith("\"") && f.endsWith("\"")) {
+          f = f.substring(1,f.length()-1);
+        }
+          
+        int index = f.lastIndexOf('/');
+        String path = "";
+        String file = f;
+        if (index != -1) {
+          path = f.substring(0, index);
+          file = f.substring(index + 1);
+        }
+        _paths.add(new Path(path, file));
+      }
+    }
+  }  
+ 
+  /**
+   * Iterate through the list of valid file patterns. Return true if this matches against
+   * the header provided to the constructor. We're going to have to be case sensitive. 
+   *  @param directory Directory name
+   *  @param filename File name 
+   *  @return true if this is a blueprint file according to the Bundle-Blueprint header
+   */
+  public boolean isBPFile (String directory, String filename) { 
+    for (Path path: _paths) { 
+      if (path.matches(directory, filename)) { 
+        return true;
+      }
+    }
+    return false;
+  }
+       
+}

Added: aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/MessageUtil.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/MessageUtil.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/MessageUtil.java (added)
+++ aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/MessageUtil.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,46 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.internal;
+
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+
+public class MessageUtil
+{
+  /** The resource bundle for blueprint messages */
+  private final static ResourceBundle messages = ResourceBundle.getBundle("org.apache.aries.application.modelling.messages.APPModellingMessages");
+
+  /**
+   * Resolve a message from the bundle, including any necessary formatting.
+   * 
+   * @param key     the message key.
+   * @param inserts any required message inserts.
+   * @return        the message translated into the server local.
+   */
+  public static final String getMessage(String key, Object ... inserts)
+  {
+    String msg = messages.getString(key);
+    
+    if (inserts.length > 0)
+      msg = MessageFormat.format(msg, inserts);
+    
+    return msg;
+  }
+}

Added: aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/PackageRequirementMerger.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/PackageRequirementMerger.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/PackageRequirementMerger.java (added)
+++ aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/internal/PackageRequirementMerger.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,138 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.internal;
+import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY;
+import static org.apache.aries.application.utils.AppConstants.LOG_EXIT;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.aries.application.modelling.ImportedPackage;
+import org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A class to merge collections of package requirements, such that multiple requirements
+ * for the same package are consolidated to a single requirement with a version constraint
+ * that is the intersection of the original version requirements.
+ */
+public final class PackageRequirementMerger
+{
+  private final Logger logger = LoggerFactory.getLogger(PackageRequirementMerger.class);
+  /** The merged requirements, or null if the merge failed. */
+  private final Collection<ImportedPackage> mergedRequirements;
+  /** Names of packages for which requirements were incompatible. */
+  private final Set<String> invalidRequirements = new HashSet<String>();
+  
+  /**
+   * Constructor.
+   * @param requirements the package requirements to be merged.
+   * @throws NullPointerException if the parameter is {@code null}.
+   */
+  public PackageRequirementMerger(Collection<ImportedPackage> requirements)
+  {
+    logger.debug(LOG_ENTRY, "PackageRequirementMerger", requirements);
+    
+    if (requirements == null)
+    {
+      NullPointerException npe = new NullPointerException();
+      logger.debug(LOG_EXIT, "PackageRequirementMerger", npe);
+      throw npe;
+    }
+
+    // Do the merge.
+    Map<String, ImportedPackage> reqMap = new HashMap<String, ImportedPackage>();
+    for (ImportedPackage req : requirements)
+    {
+      String pkgName = req.getPackageName();
+      ImportedPackage existingReq = reqMap.get(pkgName);
+      if (existingReq == null)
+      {
+        reqMap.put(pkgName, req);
+        continue;
+      }
+      
+      ImportedPackage intersectReq = ModellingHelperImpl.intersectPackage_(req, existingReq);
+      if (intersectReq != null)
+      {
+        reqMap.put(pkgName, intersectReq);
+        continue;
+      }
+
+      invalidRequirements.add(pkgName);
+    }
+    
+    mergedRequirements = (invalidRequirements.isEmpty() ? reqMap.values() : null);
+    logger.debug(LOG_EXIT,"PackageRequirementMerger");
+    }
+
+  /**
+   * Check if the requirements could be successfully merged.
+   * @return true if the merge was successful; false if the requirements were not compatible.
+   */
+  public boolean isMergeSuccessful()
+  {
+    logger.debug(LOG_ENTRY, "isMergeSuccessful");
+    boolean result = mergedRequirements != null;
+    logger.debug(LOG_EXIT, "isMergeSuccessful", result);
+    return result;
+  }
+  
+  /**
+   * Get the merged package requirements. The result will mirror the input collection,
+   * except that multiple requirements for the same package will be replaced by a single
+   * requirement that is the intersection of all the input requirements.
+   * <p>
+   * The {@code isMergeSuccessful} method should be checked for success prior to calling this method.
+   * @param inputRequirements
+   * @return A collection of package requirements, or {@code null} if the input contained incompatible requirements.
+   * @throws IllegalStateException if the merge was not successful.
+   */
+  public Collection<ImportedPackage> getMergedRequirements()
+  {
+    logger.debug(LOG_ENTRY, "getMergedRequirements");
+    if (mergedRequirements == null)
+    {
+      IllegalStateException ise = new IllegalStateException();
+      logger.debug(LOG_EXIT, "getMergedRequirements", ise);
+      throw ise;
+    }
+    logger.debug(LOG_EXIT, "getMergedRequirements", mergedRequirements);
+    return Collections.unmodifiableCollection(mergedRequirements);
+  }
+  
+  /**
+   * Get the names of packages that caused the merge to fail due to their constraints
+   * being mutually exclusive.
+   * @return an unmodifiable set of package names.
+   */
+  public Set<String> getInvalidRequirements()
+  {
+    logger.debug(LOG_ENTRY, "getInvalidRequirements");
+    logger.debug(LOG_EXIT, "getInvalidRequirements", invalidRequirements);
+    return Collections.unmodifiableSet(invalidRequirements);
+  }
+
+}

Added: aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/utils/impl/ModellingHelperImpl.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/utils/impl/ModellingHelperImpl.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/utils/impl/ModellingHelperImpl.java (added)
+++ aries/tags/application-0.3/application-modeller/src/main/java/org/apache/aries/application/modelling/utils/impl/ModellingHelperImpl.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,212 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.utils.impl;
+
+import static org.apache.aries.application.modelling.ModellingConstants.OPTIONAL_KEY;
+import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY;
+import static org.apache.aries.application.utils.AppConstants.LOG_EXIT;
+import static org.osgi.framework.Constants.BUNDLE_VERSION_ATTRIBUTE;
+import static org.osgi.framework.Constants.VERSION_ATTRIBUTE;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.aries.application.InvalidAttributeException;
+import org.apache.aries.application.VersionRange;
+import org.apache.aries.application.modelling.DeployedBundles;
+import org.apache.aries.application.modelling.ImportedBundle;
+import org.apache.aries.application.modelling.ImportedPackage;
+import org.apache.aries.application.modelling.ModelledResource;
+import org.apache.aries.application.modelling.ModellingConstants;
+import org.apache.aries.application.modelling.Provider;
+import org.apache.aries.application.modelling.impl.DeployedBundlesImpl;
+import org.apache.aries.application.modelling.impl.ImportedBundleImpl;
+import org.apache.aries.application.modelling.impl.ImportedPackageImpl;
+import org.apache.aries.application.modelling.internal.MessageUtil;
+import org.apache.aries.application.modelling.utils.ModellingHelper;
+import org.apache.aries.application.utils.manifest.ManifestHeaderProcessor;
+import org.apache.aries.application.utils.manifest.ManifestHeaderProcessor.NameValueMap;
+import org.osgi.framework.Constants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class ModellingHelperImpl implements ModellingHelper
+{
+  private static final  Logger logger = LoggerFactory.getLogger(ModellingHelperImpl.class);
+
+  
+  @Override
+  public boolean areMandatoryAttributesPresent(
+      Map<String, String> consumerAttributes, Provider p) {
+    return areMandatoryAttributesPresent_(consumerAttributes, p);
+  }
+
+
+  @Override
+  public ImportedBundle buildFragmentHost(String fragmentHostHeader)
+      throws InvalidAttributeException {
+    return buildFragmentHost_(fragmentHostHeader);
+  }
+
+
+  @Override
+  public ImportedPackage intersectPackage(ImportedPackage p1, ImportedPackage p2) {
+    return intersectPackage_(p1, p2);
+  }
+  
+  @Override
+  public DeployedBundles createDeployedBundles(String assetName,
+      Collection<ImportedBundle> appContentNames,
+      Collection<ImportedBundle> appUseBundleNames,
+      Collection<ModelledResource> fakeServiceProvidingBundles) 
+  {
+    logger.debug(LOG_ENTRY, "createDeployedBundles", new Object[]{assetName, 
+        appContentNames, appUseBundleNames, fakeServiceProvidingBundles});  
+    DeployedBundles result = new DeployedBundlesImpl (assetName, 
+        appContentNames, appUseBundleNames, fakeServiceProvidingBundles);
+    logger.debug(LOG_EXIT, "createDeployedBundles", result);
+    return result;
+  }
+  
+  // These underlying static methods are directly accessible 
+  // from other classes within the bundle
+  public static boolean areMandatoryAttributesPresent_(Map<String,String> consumerAttributes, Provider p) {
+    logger.debug(LOG_ENTRY, "areMandatoryAttributesPresent_", new Object[]{consumerAttributes, p});
+    boolean allPresent = true;
+    String mandatory = (String) p.getAttributes().get(Constants.MANDATORY_DIRECTIVE + ":");
+    
+    if(mandatory != null && !mandatory.equals("")) {
+      List<String> attributeNames = ManifestHeaderProcessor.split(mandatory, ",");
+      
+      for(String name : attributeNames) {
+        allPresent = consumerAttributes.containsKey(name);
+        if(!allPresent)
+          break;
+      }
+    }
+    logger.debug(LOG_EXIT, "areMandatoryAttributesPresent_", allPresent);
+    return allPresent;
+  }
+  
+  
+  
+  public static ImportedBundle buildFragmentHost_(String fragmentHostHeader) throws InvalidAttributeException {
+    logger.debug(LOG_ENTRY, "buildFragmentHost_", new Object[]{fragmentHostHeader});
+    if(fragmentHostHeader == null) { 
+      
+      return null;
+    }
+    Map<String, NameValueMap<String, String>> parsedFragHost = ManifestHeaderProcessor.parseImportString(fragmentHostHeader);
+    if(parsedFragHost.size() != 1)
+      throw new InvalidAttributeException(MessageUtil.getMessage("APPUTILS0001W",
+          new Object[] {fragmentHostHeader}, 
+          "An internal error occurred. A bundle fragment manifest must define exactly one Fragment-Host entry. The following entry was found" + fragmentHostHeader + "."));
+    
+    String hostName = parsedFragHost.keySet().iterator().next();
+    Map<String, String> attribs = parsedFragHost.get(hostName);
+    
+    String bundleVersion = attribs.remove(BUNDLE_VERSION_ATTRIBUTE);
+    if (bundleVersion != null && attribs.get(VERSION_ATTRIBUTE) == null) { 
+      attribs.put (VERSION_ATTRIBUTE, bundleVersion);
+    }
+    attribs.put(ModellingConstants.OBR_SYMBOLIC_NAME, hostName);  
+    
+    String filter = ManifestHeaderProcessor.generateFilter(attribs);
+    
+    ImportedBundle result = new ImportedBundleImpl(filter, attribs);
+    logger.debug(LOG_EXIT, "buildFragmentHost_", result);
+    return result;
+  }
+  
+  public static ImportedPackage intersectPackage_ (ImportedPackage p1, ImportedPackage p2) { 
+    
+    logger.debug(LOG_ENTRY, "intersectPackage_", new Object[]{p1, p2});
+    ImportedPackage result = null;
+    if (p1.getPackageName().equals(p2.getPackageName()))
+    {
+      Map<String,String> att1 = new HashMap<String, String>(p1.getAttributes());
+      Map<String,String> att2 = new HashMap<String, String>(p2.getAttributes());
+      
+      // Get the versions, we remove them so that the remaining attributes can be matched.
+      String rangeStr1 = att1.remove(Constants.VERSION_ATTRIBUTE);
+      String rangeStr2 = att2.remove(Constants.VERSION_ATTRIBUTE);
+
+      //Also remove the optional directive as we don't care about that either
+      att1.remove(OPTIONAL_KEY);
+      att2.remove(OPTIONAL_KEY);
+      
+      //If identical take either, otherwise null!
+      Map<String, String> mergedAttribs = (att1.equals(att2) ? att1 : null);
+      if (mergedAttribs == null)
+      {
+        // Cannot intersect requirements if attributes are not identical.
+        result = null;
+      }
+      else
+      {
+        boolean isIntersectSuccessful = true;
+        
+        if (rangeStr1 != null && rangeStr2 != null)
+        {
+          // Both requirements have a version constraint so check for an intersection between them.
+          VersionRange range1 = ManifestHeaderProcessor.parseVersionRange(rangeStr1);
+          VersionRange range2 = ManifestHeaderProcessor.parseVersionRange(rangeStr2);
+          VersionRange intersectRange = range1.intersect(range2);
+          
+          if (intersectRange == null)
+          {
+            // No intersection possible.
+            isIntersectSuccessful = false;
+          }
+          else
+          {
+            // Use the intersected version range.
+            mergedAttribs.put(Constants.VERSION_ATTRIBUTE, intersectRange.toString());
+          }
+        }
+        else if (rangeStr1 != null)
+        {
+          mergedAttribs.put(Constants.VERSION_ATTRIBUTE, rangeStr1);
+        }
+        else if (rangeStr2 != null)
+        {
+          mergedAttribs.put(Constants.VERSION_ATTRIBUTE, rangeStr2);
+        }
+        
+        //If both optional, we are optional, otherwise use the default
+        if(p1.isOptional() && p2.isOptional()) 
+        {
+          mergedAttribs.put(OPTIONAL_KEY, Constants.RESOLUTION_OPTIONAL);
+        } 
+        
+        try { 
+          result = (isIntersectSuccessful ? new ImportedPackageImpl(p1.getPackageName(), mergedAttribs) : null);
+        } catch (InvalidAttributeException iax) { 
+          logger.error(iax.getMessage());
+        }
+      }
+    } 
+    logger.debug(LOG_EXIT, "intersectPackage_", result);
+    return result;
+  }
+  
+}

Added: aries/tags/application-0.3/application-modeller/src/main/resources/OSGI-INF/blueprint/app-modeller.xml
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/resources/OSGI-INF/blueprint/app-modeller.xml?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/resources/OSGI-INF/blueprint/app-modeller.xml (added)
+++ aries/tags/application-0.3/application-modeller/src/main/resources/OSGI-INF/blueprint/app-modeller.xml Sun Feb 27 20:20:13 2011
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+    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.
+-->
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0">
+  <bean id="modelledResourceManager" class="org.apache.aries.application.modelling.impl.ModelledResourceManagerImpl">
+    <property name="modellingManager" ref="modellingManager"/>
+    <property name="parserProxy" ref="parserProxy"/>
+  </bean>
+  <service id = "modelledResourceManagerService" ref="modelledResourceManager" interface="org.apache.aries.application.modelling.ModelledResourceManager"/>
+
+  <reference id="parser-service" interface="org.apache.aries.blueprint.ParserService"/>
+  <bean id="parserProxy" class="org.apache.aries.application.modelling.impl.ParserProxyImpl">
+    <property name="parserService" ref="parser-service"/>
+    <property name="bundleContext" ref="blueprintBundleContext"/>
+    <property name="modellingManager" ref="modellingManager"/>
+  </bean>
+  <service id="parserProxyService" ref="parserProxy" interface="org.apache.aries.application.modelling.ParserProxy"/>
+  
+  <bean id="modellingManager" class="org.apache.aries.application.modelling.impl.ModellingManagerImpl"/>
+  <service id="modellingManagerService" ref="modellingManager" interface="org.apache.aries.application.modelling.ModellingManager"/>
+  
+  <bean id="modellingHelper" class="org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl"/>
+  <service id="modellingHelperService" ref="modellingHelper" interface="org.apache.aries.application.modelling.utils.ModellingHelper"/>
+  
+</blueprint>
\ No newline at end of file

Added: aries/tags/application-0.3/application-modeller/src/main/resources/org/apache/aries/application/modelling/messages/APPModellingMessages.properties
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/main/resources/org/apache/aries/application/modelling/messages/APPModellingMessages.properties?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/main/resources/org/apache/aries/application/modelling/messages/APPModellingMessages.properties (added)
+++ aries/tags/application-0.3/application-modeller/src/main/resources/org/apache/aries/application/modelling/messages/APPModellingMessages.properties Sun Feb 27 20:20:13 2011
@@ -0,0 +1,27 @@
+#
+# 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.
+#
+
+MORE_THAN_ONE_FRAG_HOST=APPMODELLING0001W: An internal error occurred. A bundle fragment manifest must define exactly one Fragment-Host entry. The following entry was found {0}.
+TOO_MANY_SYM_NAMES=APPMODELLING0002W: An internal error occurred. A bundle manifest must contain exactly one Bundle-SymbolicName entry. The following entry was found {0}.
+INCORRECT_MANDATORY_HEADERS=APPMODELLING0003W: An internal error occurred. A bundle with symbolic name {0} and manifest version {1} was unable to be processed.
+TOO_MANY_CB_SYM_NAMES=APPMODELLING0004W: An internal error occurred. A composite bundle manifest must contain exactly one Bundle-SymbolicName entry. The following entry was found {0}.
+INCORRECT_CB_MANDATORY_HEADERS=APPMODELLING0005W: An internal error occurred. A composite bundle with symbolic name {0} and manifest version {1} was unable to be processed.
+TOO_MANY_FRAG_HOSTS=APPMODELLING0006W: An internal error occurred. A bundle fragment manifest must define exactly one Fragment-Host entry. The following entry was found {0}.
+INCOMPATIBLE_PACKAGE_VERSION_REQUIREMENTS=APPMODELLING0007W: The asset {0} cannot be resolved. It has incompatible version requirements on the following packages: {1}.
+INVALID_PACKAGE_REQUIREMENT_ATTRIBUTES=APPMODELLING0008W: The asset {0} cannot be resolved. The attribute {1} on an import for package {2} cannot be satisfied at deployment.

Added: aries/tags/application-0.3/application-modeller/src/test/java/org/apache/aries/application/modelling/impl/ParserProxyImplTest.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/test/java/org/apache/aries/application/modelling/impl/ParserProxyImplTest.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/test/java/org/apache/aries/application/modelling/impl/ParserProxyImplTest.java (added)
+++ aries/tags/application-0.3/application-modeller/src/test/java/org/apache/aries/application/modelling/impl/ParserProxyImplTest.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,220 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.aries.application.modelling.ModellingManager;
+import org.apache.aries.application.modelling.ParsedServiceElements;
+import org.apache.aries.application.modelling.ParserProxy;
+import org.apache.aries.application.modelling.WrappedReferenceMetadata;
+import org.apache.aries.application.modelling.WrappedServiceMetadata;
+import org.apache.aries.blueprint.ParserService;
+import org.apache.aries.blueprint.container.NamespaceHandlerRegistry;
+import org.apache.aries.blueprint.container.ParserServiceImpl;
+import org.apache.aries.blueprint.namespace.NamespaceHandlerRegistryImpl;
+import org.apache.aries.mocks.BundleContextMock;
+import org.apache.aries.unittest.mocks.Skeleton;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.osgi.framework.BundleContext;
+
+public class ParserProxyImplTest {
+
+  static ParserProxy _parserProxy;
+  static ModellingManager _modellingManager;
+  
+  @BeforeClass
+  public static void setup() { 
+    BundleContext mockCtx = Skeleton.newMock(new BundleContextMock(), BundleContext.class);
+    NamespaceHandlerRegistry nhri = new NamespaceHandlerRegistryImpl (mockCtx);
+    ParserService parserService = new ParserServiceImpl(nhri);
+    mockCtx.registerService(ParserService.class.getName(), parserService, new Hashtable<String, String>());
+    _parserProxy = new ParserProxyImpl();
+    ((ParserProxyImpl)_parserProxy).setParserService(parserService);
+    ((ParserProxyImpl)_parserProxy).setBundleContext(mockCtx);
+    _modellingManager = new ModellingManagerImpl();
+    ((ParserProxyImpl)_parserProxy).setModellingManager(_modellingManager);
+  }
+  
+  
+  
+  @AfterClass
+  public static void teardown() { 
+    BundleContextMock.clear();
+  }
+  
+  
+  
+  @Test
+  public void basicTest1() throws Exception { 
+    File bpXml = new File ("../src/test/resources", "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bp.xml");
+    File bp2Xml = new File ("../src/test/resources", "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bp2.xml");
+    List<URL> urls = new ArrayList<URL>();
+    urls.add ((bpXml.toURI()).toURL());
+    urls.add ((bp2Xml.toURI()).toURL());
+    
+    List<? extends WrappedServiceMetadata> results = _parserProxy.parse(urls);
+    assertTrue ("Four results expected, not " + results.size(), results.size() == 4);
+    
+    Set<WrappedServiceMetadata> resultSet = new HashSet<WrappedServiceMetadata>(results);
+    Set<WrappedServiceMetadata> expectedResults = getTest1ExpectedResults();
+    assertEquals ("Blueprint parsed xml is not as expected: " + resultSet.toString() + " != " + expectedResults,
+        resultSet, expectedResults);
+  }
+  
+  @Test
+  public void testParseAllServiceElements() throws Exception { 
+    File bpXml = new File ("../src/test/resources", "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bp.xml");
+    File bp2Xml = new File ("../src/test/resources", "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bp2.xml");
+    
+    List<WrappedServiceMetadata> services = new ArrayList<WrappedServiceMetadata>();
+    List<WrappedReferenceMetadata> references = new ArrayList<WrappedReferenceMetadata>();
+    
+    FileInputStream fis = new FileInputStream (bpXml);
+    ParsedServiceElements bpelem = _parserProxy.parseAllServiceElements(fis); 
+    services.addAll(bpelem.getServices());
+    references.addAll(bpelem.getReferences());
+    
+    fis = new FileInputStream (bp2Xml);
+    bpelem = _parserProxy.parseAllServiceElements(fis); 
+    services.addAll(bpelem.getServices());
+    references.addAll(bpelem.getReferences());
+    
+    // We expect:
+    // bp.xml: 3 services and 2 references
+    // bp2.xml: 3 services and a reference list
+    //
+    assertTrue ("Six services expected, not " + services.size(), services.size() == 6);
+    assertTrue ("Three references expected, not " + references.size(), references.size() == 3);
+    
+    Set<WrappedServiceMetadata> expectedServices = getTest2ExpectedServices();
+    // ServiceResultSet will contain some services with autogenerated names starting '.' so we can't 
+    // use a straight Set.equals(). We could add the autogenerated names to the expected results but instead
+    // let's test that differsOnlyByName() works
+    int serviceMatchesFound = 0;
+    for (WrappedServiceMetadata result : services) { 
+      Iterator<WrappedServiceMetadata> it = expectedServices.iterator();
+      while (it.hasNext()) { 
+        WrappedServiceMetadata next = it.next();
+        if (result.equals(next) || result.identicalOrDiffersOnlyByName(next)) { 
+          serviceMatchesFound++;
+          it.remove();
+        }
+      }
+    }
+    
+    assertEquals ("Parsed services are wrong: " + expectedServices + " unmatched ",
+        6, serviceMatchesFound);
+    
+    Set<WrappedReferenceMetadata> expectedReferences = getTest2ExpectedReferences();
+    Set<WrappedReferenceMetadata> results = new HashSet<WrappedReferenceMetadata>(references);
+    assertTrue ("Parsed references are not as we'd expected: " + results.toString() + " != " + expectedReferences,
+        results.equals(expectedReferences));
+  }
+  
+  @Test
+  public void checkMultiValues() throws Exception { 
+    File bpXml = new File ("../src/test/resources", "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bpMultiValues.xml");
+    List<WrappedServiceMetadata> services = new ArrayList<WrappedServiceMetadata>();
+    FileInputStream fis = new FileInputStream (bpXml);
+    ParsedServiceElements bpelem = _parserProxy.parseAllServiceElements(fis); 
+    services.addAll(bpelem.getServices());
+    
+    assertEquals ("Multi valued service not parsed correctly", services.size(), 1);
+    
+    WrappedServiceMetadata wsm = services.get(0);
+    Map<String, Object> props = wsm.getServiceProperties();
+    String [] intents = (String[]) props.get("service.intents");
+    
+    assertEquals ("Service.intents[0] wrong", intents[0], "propagatesTransaction");
+    assertEquals ("Service.intents[1] wrong", intents[1], "confidentiality");
+    
+  }
+  
+  // model
+  // <reference id="fromOutside" interface="foo.bar.MyInjectedService"/>
+  // <reference-list id="refList1" interface="my.logging.services" filter="(active=true)"/>
+  //
+  private Set<WrappedReferenceMetadata> getTest2ExpectedReferences() throws Exception { 
+    Set<WrappedReferenceMetadata> expectedResults = new HashSet<WrappedReferenceMetadata>();
+         
+    expectedResults.add(_modellingManager.getImportedService(false, "foo.bar.MyInjectedService", null, 
+        null, "fromOutside", false));
+    expectedResults.add(_modellingManager.getImportedService(true, "foo.bar.MyInjectedService", null, 
+        null, "anotherOptionalReference", false));
+    expectedResults.add(_modellingManager.getImportedService(false, "my.logging.service", null, "(&(trace=on)(debug=true))", "refList1", true));
+    
+    return expectedResults;
+  }
+  
+  // Test 2 includes anonymous services: the expected results are a superset of test1
+  private Set<WrappedServiceMetadata> getTest2ExpectedServices() { 
+    Set<WrappedServiceMetadata> expectedResults = getTest1ExpectedResults();
+        
+    expectedResults.add(_modellingManager.getExportedService("", 0, Arrays.asList("foo.bar.AnonService"), null));
+    expectedResults.add(_modellingManager.getExportedService("", 0, Arrays.asList("foo.bar.NamedInnerBeanService"), null));
+    return expectedResults;
+  }
+  
+  private Set<WrappedServiceMetadata> getTest1ExpectedResults() { 
+    Set<WrappedServiceMetadata> expectedResults = new HashSet<WrappedServiceMetadata>();
+    Map<String, Object> props = new HashMap<String, Object>();
+    props.put ("priority", "9");
+    props.put("volume", "11");
+    props.put("osgi.service.blueprint.compname", "myBean");
+    expectedResults.add(_modellingManager.getExportedService("myService", 0, Arrays.asList("foo.bar.MyService"), props));
+
+    props = new HashMap<String, Object>();
+    props.put ("priority", "7");
+    props.put ("volume", "11");
+    props.put ("osgi.service.blueprint.compname", "bean1");
+    expectedResults.add(_modellingManager.getExportedService("service1.should.be.exported", 0, Arrays.asList("foo.bar.MyService"), props));
+ 
+    props = new HashMap<String, Object>();
+    props.put ("customer", "pig");
+    props.put ("osgi.service.blueprint.compname", "bean2");
+    expectedResults.add(_modellingManager.getExportedService("service2.should.not.be.exported", 0, Arrays.asList("com.acme.Delivery"), props));
+        
+    props = new HashMap<String, Object>();
+    props.put ("customer", "pig");
+    props.put ("target", "rabbit");
+    props.put ("payload", "excessive");
+    props.put ("osgi.service.blueprint.compname", "bean3");
+    expectedResults.add(_modellingManager.getExportedService("bean3", 0, Arrays.asList("com.acme.Delivery"), props));
+       
+    return expectedResults;
+  } 
+}

Added: aries/tags/application-0.3/application-modeller/src/test/java/org/apache/aries/application/modelling/utils/AbstractBundleResourceTest.java
URL: http://svn.apache.org/viewvc/aries/tags/application-0.3/application-modeller/src/test/java/org/apache/aries/application/modelling/utils/AbstractBundleResourceTest.java?rev=1075132&view=auto
==============================================================================
--- aries/tags/application-0.3/application-modeller/src/test/java/org/apache/aries/application/modelling/utils/AbstractBundleResourceTest.java (added)
+++ aries/tags/application-0.3/application-modeller/src/test/java/org/apache/aries/application/modelling/utils/AbstractBundleResourceTest.java Sun Feb 27 20:20:13 2011
@@ -0,0 +1,222 @@
+/*
+ * 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 WARRANTIESOR 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.aries.application.modelling.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Map;
+
+import org.apache.aries.application.management.ResolverException;
+import org.apache.aries.application.modelling.ExportedPackage;
+import org.apache.aries.application.modelling.ExportedService;
+import org.apache.aries.application.modelling.ImportedBundle;
+import org.apache.aries.application.modelling.ImportedPackage;
+import org.apache.aries.application.modelling.ImportedService;
+import org.apache.aries.application.modelling.ModelledResource;
+import org.apache.aries.application.modelling.ModellingConstants;
+import org.apache.aries.application.utils.manifest.ManifestHeaderProcessor;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+
+
+
+/* This is an abstract class and should not be instantiated, so we have an ignore
+ * annotation to the class.
+ */
+@Ignore
+public abstract class AbstractBundleResourceTest
+{
+  protected ModelledResource bundleResource;
+
+  @Before
+  public void setUp() throws Exception
+  {
+    bundleResource = instantiateBundleResource();
+  }
+
+  /**
+   * @return
+   * @throws ResolverException 
+   * @throws FileNotFoundException 
+   * @throws IOException 
+   * @throws Exception 
+   */
+  protected abstract ModelledResource instantiateBundleResource() throws Exception;
+
+  @Test
+  public void testBundleResource() throws Exception
+  {
+    assertEquals("The bundle symbolic name is wrong.", "test.bundle1", bundleResource.getSymbolicName());
+    assertEquals("The bundle version is wrong.", "2.0.0.build-121", bundleResource.getVersion().toString());
+    assertEquals("The bundle presentation name is wrong.", "Test Bundle", bundleResource.getExportedBundle()
+        .getAttributes().get(ModellingConstants.OBR_PRESENTATION_NAME));
+    
+
+    
+    int count = 0;
+  
+    for (ImportedPackage ip : bundleResource.getImportedPackages()) {
+      String filter = ip.getAttributeFilter();
+      Map<String, String> parsedFilterElements = ManifestHeaderProcessor.parseFilter(filter);
+      
+      if (ip.getPackageName().equals("org.osgi.framework")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "org.osgi.framework");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "1.3.0");
+      } else if (ip.getPackageName().equals("aries.ws.kernel.file")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.kernel.file");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0");
+      } else if (ip.getPackageName().equals("aries.wsspi.application.aries")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.wsspi.application.aries");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0");
+        assertEquals ("Company wrong", parsedFilterElements.get("company"), "yang");
+        assertTrue ("mandatory filter missing", filter.contains("(mandatory:<*company)"));
+      } else if (ip.getPackageName().equals("aries.ws.ffdc")) {
+        count++;
+        assertEquals("The filter is wrong.", "(&(package=aries.ws.ffdc)(version>=0.0.0))", ip.getAttributeFilter());
+        assertTrue ("Optional import not correctly represented", ip.isOptional());
+      } else if (ip.getPackageName().equals("aries.ws.app.framework.plugin")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.app.framework.plugin");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "[1.0.0,2.0.0)");
+      } else if (ip.getPackageName().equals("aries.ejs.ras")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ejs.ras");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0");
+     } else if (ip.getPackageName().equals("aries.ws.event")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.event");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "1.0.0");
+      } else if (ip.getPackageName().equals("aries.wsspi.app.container.aries")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.wsspi.app.container.aries");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0");
+        assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("bundle-symbolic-name"), "B");
+        assertEquals ("Wrong bundle version", parsedFilterElements.get("bundle-version"), "[1.2.0,2.2.0)");
+      } else if (ip.getPackageName().equals("aries.ws.eba.bla")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.bla");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0");
+      } else if (ip.getPackageName().equals("aries.ws.eba.launcher")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.launcher");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "[1.0.0,2.0.0]");
+        assertTrue ("Dynamic-ImportPackage should be optional", ip.isOptional());
+      } else if (ip.getPackageName().equals("aries.ws.eba.bundle4")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.bundle4");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "3.0.0");
+      } else if (ip.getPackageName().equals("aries.ws.eba.bundle5")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.bundle5");
+        assertEquals ("Wrong package version", parsedFilterElements.get("version"), "3.0.0");
+      } else if (ip.getPackageName().equals("aries.ws.eba.bundle6")) {
+        count++;
+        assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.bundle6");
+        
+        assertEquals("The filter is wrong.", "(&(package=aries.ws.eba.bundle6)(version>=0.0.0))", ip.getAttributeFilter());
+      } else if (ip.getPackageName().equals("aries.ws.eba.bundle7")) {
+        count++;
+        assertEquals("The filter is wrong.", "(&(package=aries.ws.eba.bundle7)(version>=0.0.0))", ip.getAttributeFilter());
+      } 
+    }
+      
+    for (ImportedBundle ib : bundleResource.getRequiredBundles()) {
+      String filter = ib.getAttributeFilter();
+      Map<String, String> parsedFilterElements = ManifestHeaderProcessor.parseFilter(filter);
+      if (ib.getSymbolicName().equals("com.acme.facade")) {
+        count++;
+        assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "com.acme.facade");
+        assertEquals ("Wrong bundle version", parsedFilterElements.get("version"), "3.0.0");
+      } else if (ib.getSymbolicName().equals("com.acme.bar")) {
+        count++;
+        assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "com.acme.bar");
+      } else if (ib.getSymbolicName().equals("aries.ws.eba.framework")) {
+        count++;
+        assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "aries.ws.eba.framework");
+        assertEquals ("Wrong bundle version", parsedFilterElements.get("version"), "(3.0.0,4.0.0)");
+      } else if (ib.getSymbolicName().equals("com.de.ba")) {
+        count++;
+        assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "com.de.ba");
+      } else if (ib.getSymbolicName().equals("com.ab.de")) {
+        count++;
+        assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "com.ab.de");
+      }
+    }
+    
+    for(ImportedService svc : bundleResource.getImportedServices()) {
+      if (svc.getInterface().equals("aries.ws.eba.import")) {
+        count++;
+        String filter = svc.getAttributeFilter();
+        Map<String, String> parsedFilterElements = ManifestHeaderProcessor.parseFilter(filter);
+        assertEquals ("Wrong object class", parsedFilterElements.get("objectClass"), "aries.ws.eba.import");
+        assertTrue("(service=service) should be present", svc.getAttributeFilter().contains("(service=service)"));
+        assertTrue("(mandatory:<*service) should be present", svc.getAttributeFilter().contains("(mandatory:<*service)"));        
+      } 
+    }
+    
+    assertEquals("Not all requirements are listed.", bundleResource.getImportedPackages().size() +
+        bundleResource.getImportedServices().size() + bundleResource.getRequiredBundles().size() , count);
+  
+    //verify the capability
+  
+    int verifiedExport = 0;
+    for (ExportedPackage cap : bundleResource.getExportedPackages()) {
+ 
+        if (cap.getPackageName().equals("aries.ws.eba.bundle1")) {
+  
+          verifiedExport++;
+          assertEquals("The export package is not expected.", "2.2.0", cap.getVersion());
+          assertEquals("The export package is not expected.", "test.bundle1", cap.getAttributes().get(
+              "bundle-symbolic-name"));
+          assertEquals("The export package is not expected.", "2.0.0.build-121", cap.getAttributes()
+              .get("bundle-version").toString());
+        } else if (cap.getPackageName().equals("aries.ws.eba.bundle2")) {
+          verifiedExport++;
+          assertEquals("The export package is not expected.", "3", cap.getVersion());
+        } else if (cap.getPackageName().equals("aries.ws.eba.bundle3")) {
+          verifiedExport++;
+          assertEquals("The export package is not expected.", "3", cap.getVersion());
+        }
+    }
+    assertEquals("The number of exports are not expected.", bundleResource.getExportedPackages().size()
+        , verifiedExport);
+    
+
+    // bundle resource
+    assertEquals("The bundle resource is wrong.", "Test Bundle", bundleResource.getExportedBundle().
+        getAttributes().get(ModellingConstants.OBR_PRESENTATION_NAME));
+    assertEquals("The bundle resource is wrong.", "2.0.0.build-121", bundleResource.getExportedBundle().
+        getVersion());
+    assertEquals("The bundle resource is wrong.", "test.bundle1", bundleResource.getExportedBundle().
+        getSymbolicName());
+    
+    
+    for (ExportedService svc : bundleResource.getExportedServices()) {
+      assertEquals("The export service is wrong", "aries.ws.eba.export", svc.getInterfaces().
+          iterator().next());
+    }
+  }
+}



Mime
View raw message