index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aries/application/application-runtime-framework-management/src/main/java/org/apache/aries/application/runtime/framework
Create_ds/aries/application/application-runtime-framework-management/src/main/java/org/apache/aries/application/runtime/framework/management/SharedFrameworkPreResolveHook.java
/* * 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.runtime.framework.management; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import org.apache.aries.application.Content; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.spi.framework.BundleFrameworkManager; import org.apache.aries.application.management.spi.resolve.PreResolveHook; 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.ModellingManager; import org.apache.aries.application.utils.manifest.ContentFactory; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.aries.util.manifest.ManifestProcessor; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.Version; public class SharedFrameworkPreResolveHook implements PreResolveHook { private BundleFrameworkManager fwMgr; private ModellingManager mgr; private static final class BundleInfoImpl implements BundleInfo { private final Bundle compositeBundle; public BundleInfoImpl(Bundle bundle) { compositeBundle = bundle; } @Override public String getSymbolicName() { return compositeBundle.getSymbolicName(); } @Override public Map<String, String> getBundleDirectives() { return Collections.emptyMap(); } @Override public Map<String, String> getBundleAttributes() { return Collections.emptyMap(); } @Override public Version getVersion() { return compositeBundle.getVersion(); } @Override public String getLocation() { return compositeBundle.getLocation(); } @Override public Set<Content> getImportPackage() { return Collections.emptySet(); } @Override public Set<Content> getRequireBundle() { return Collections.emptySet(); } @Override public Set<Content> getExportPackage() { String imports = (String) compositeBundle.getHeaders().get(Constants.IMPORT_PACKAGE); Set<Content> exports = new HashSet<Content>(); Map<String, Map<String, String>> parsedImports = ManifestHeaderProcessor.parseImportString(imports); for (Map.Entry<String, Map<String, String>> anImport : parsedImports.entrySet()) { exports.add(ContentFactory.parseContent(anImport.getKey(), anImport.getValue())); } return exports; } @Override public Set<Content> getImportService() { return Collections.emptySet(); } @Override public Set<Content> getExportService() { return Collections.emptySet(); } @Override public Map<String, String> getHeaders() { Map<String, String> result = new HashMap<String, String>(); @SuppressWarnings("unchecked") Dictionary<String, String> headers = compositeBundle.getHeaders(); Enumeration<String> keys = headers.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); String value = headers.get(key); // if (Constants.IMPORT_PACKAGE.equals(key)) { // result.put(Constants.EXPORT_PACKAGE, value); // } else if (!!!Constants.EXPORT_PACKAGE.equals(key)) { // result.put(key, value); // } result.put(key, value); } return result; } @Override public Attributes getRawAttributes() { return ManifestProcessor.mapToManifest(getHeaders()).getMainAttributes(); } } @Override public void collectFakeResources(Collection<ModelledResource> resources) { Bundle b = fwMgr.getSharedBundleFramework().getIsolatedBundleContext().getBundle(1); BundleInfo info = new BundleInfoImpl(b); Collection<ImportedService> serviceImports = Collections.emptySet(); Collection<ExportedService> serviceExports = Collections.emptySet(); try { resources.add(mgr.getModelledResource(info.getLocation(), info, serviceImports, serviceExports)); } catch (InvalidAttributeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setBundleFrameworkManager(BundleFrameworkManager bfm) { fwMgr = bfm; } public void setModellingManager(ModellingManager manager) { mgr = manager; } }
8,800
0
Create_ds/aries/application/application-runtime-framework-management/src/main/java/org/apache/aries/application/runtime/framework
Create_ds/aries/application/application-runtime-framework-management/src/main/java/org/apache/aries/application/runtime/framework/management/BundleFrameworkManagerImpl.java
/* * 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.runtime.framework.management; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXCEPTION; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.UpdateException; import org.apache.aries.application.management.spi.framework.BundleFramework; import org.apache.aries.application.management.spi.framework.BundleFrameworkConfiguration; import org.apache.aries.application.management.spi.framework.BundleFrameworkConfigurationFactory; import org.apache.aries.application.management.spi.framework.BundleFrameworkFactory; import org.apache.aries.application.management.spi.framework.BundleFrameworkManager; import org.apache.aries.application.management.spi.repository.ContextException; import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion; import org.apache.aries.application.management.spi.update.UpdateStrategy; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.framework.ServiceReference; import org.osgi.framework.FrameworkListener; import org.osgi.framework.FrameworkEvent; public class BundleFrameworkManagerImpl implements BundleFrameworkManager { private static final Logger LOGGER = LoggerFactory.getLogger(BundleFrameworkManagerImpl.class); BundleContext _ctx; BundleFramework _sharedBundleFramework; BundleFrameworkFactory _bundleFrameworkFactory; BundleFrameworkConfigurationFactory _bundleFrameworkConfigurationFactory; Map<Bundle, BundleFramework> _frameworks = new HashMap<Bundle, BundleFramework>(); Map<String, BundleFramework> _frameworksByAppScope = new HashMap<String, BundleFramework>(); private List<UpdateStrategy> _updateStrategies = Collections.emptyList(); public void setUpdateStrategies(List<UpdateStrategy> updateStrategies) { _updateStrategies = updateStrategies; } public void setBundleContext(BundleContext ctx) { _ctx = ctx; } public void setBundleFrameworkFactory(BundleFrameworkFactory bff) { _bundleFrameworkFactory = bff; } public void setBundleFrameworkConfigurationFactory(BundleFrameworkConfigurationFactory bfcf) { _bundleFrameworkConfigurationFactory = bfcf; } public void init() { synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { try { _sharedBundleFramework = SharedBundleFramework.getSharedBundleFramework(_ctx, _bundleFrameworkConfigurationFactory, _bundleFrameworkFactory); _frameworks.put(_sharedBundleFramework.getFrameworkBundle(), _sharedBundleFramework); } catch (ContextException e) { LOGGER.error(LOG_EXCEPTION, e); } } } public void close() { synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { try { _sharedBundleFramework.close(); } catch (BundleException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public BundleFramework getBundleFramework(Bundle frameworkBundle) { BundleFramework framework = null; synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { framework = _frameworks.get(frameworkBundle); } return framework; } public Bundle installIsolatedBundles(Collection<BundleSuggestion> bundlesToInstall, AriesApplication app) throws BundleException { Bundle frameworkBundle = null; synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { // We need to create a new isolated framework for this content and install // the bundles to it BundleFramework isolatedFramework = isolatedInstall(bundlesToInstall, _sharedBundleFramework .getIsolatedBundleContext(), app); _frameworks.put(isolatedFramework.getFrameworkBundle(), isolatedFramework); _frameworksByAppScope.put(app.getApplicationMetadata().getApplicationScope(), isolatedFramework); frameworkBundle = isolatedFramework.getFrameworkBundle(); } return frameworkBundle; } public Collection<Bundle> installSharedBundles(Collection<BundleSuggestion> bundlesToInstall, AriesApplication app) throws BundleException { Collection<Bundle> installedBundles = new ArrayList<Bundle>(); synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { // Shared bundle : Install to the shared bundle framework for (BundleSuggestion suggestion : bundlesToInstall) installedBundles.add(_sharedBundleFramework.install(suggestion, app)); } return installedBundles; } private BundleFramework isolatedInstall(Collection<BundleSuggestion> bundlesToBeInstalled, BundleContext parentCtx, AriesApplication app) throws BundleException { LOGGER.debug(LOG_ENTRY, "isolatedInstall", new Object[] { bundlesToBeInstalled, app }); /** * Build the configuration information for this application framework */ BundleFrameworkConfiguration config = _bundleFrameworkConfigurationFactory .createBundleFrameworkConfig(app.getApplicationMetadata().getApplicationScope(), parentCtx, app); /** * Install and start the new isolated bundle framework */ BundleFramework bundleFramework = _bundleFrameworkFactory.createBundleFramework(parentCtx, config); // We should now have a bundleFramework if (bundleFramework != null) { try { bundleFramework.init(); /** * Install the bundles into the new framework */ BundleContext frameworkBundleContext = bundleFramework.getIsolatedBundleContext(); if (frameworkBundleContext != null) { for (BundleSuggestion suggestion : bundlesToBeInstalled) bundleFramework.install(suggestion, app); } } catch (BundleException be) { bundleFramework.close(); throw be; } catch (RuntimeException re) { bundleFramework.close(); throw re; } } LOGGER.debug(LOG_EXIT, "isolatedInstall", bundleFramework); return bundleFramework; } public BundleFramework getSharedBundleFramework() { synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { return _sharedBundleFramework; } } public void uninstallBundle(Bundle b) throws BundleException { synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { BundleFramework framework = getBundleFramework(b); if (framework != null) { for (Bundle bundle : new ArrayList<Bundle>(framework.getBundles())) { framework.uninstall(bundle); } BundleContext ctx = framework.getIsolatedBundleContext(); ServiceReference ref = ctx.getServiceReference(PackageAdmin.class.getName()); if (ref != null) { try { PackageAdmin pa = (PackageAdmin) ctx.getService(ref); if (pa != null) { final Semaphore sem = new Semaphore(0); FrameworkListener listener = new FrameworkListener() { public void frameworkEvent(FrameworkEvent event) { if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { sem.release(); } } }; ctx.addFrameworkListener(listener); pa.refreshPackages(null); try { sem.tryAcquire(60, TimeUnit.SECONDS); } catch (InterruptedException ie) {} ctx.removeFrameworkListener(listener); } } finally { ctx.ungetService(ref); } } framework.close(); // clean up our maps so we don't leak memory _frameworks.remove(b); Iterator<BundleFramework> it = _frameworksByAppScope.values().iterator(); while (it.hasNext()) { if (it.next().equals(framework)) it.remove(); } } } } public void startBundle(Bundle b) throws BundleException { synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { BundleFramework framework = getBundleFramework(b); // Start all bundles inside the framework if (framework != null) // App Content { framework.start(); for (Bundle bundle : framework.getBundles()) framework.start(bundle); } else // Shared bundle _sharedBundleFramework.start(b); } } public void stopBundle(Bundle b) throws BundleException { synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { BundleFramework framework = getBundleFramework(b); // Stop all bundles inside the framework if (framework != null) // App Content { for (Bundle bundle : new ArrayList<Bundle>(framework.getBundles())) { framework.stop(bundle); } } // Do not stop shared bundles } } public boolean allowsUpdate(DeploymentMetadata newMetadata, DeploymentMetadata oldMetadata) { for (UpdateStrategy strategy : _updateStrategies) { if (strategy.allowsUpdate(newMetadata, oldMetadata)) { return true; } } return false; } public void updateBundles(final DeploymentMetadata newMetadata, final DeploymentMetadata oldMetadata, final AriesApplication app, final BundleLocator locator, final Set<Bundle> bundles, final boolean startBundles) throws UpdateException { UpdateStrategy strategy = null; for (UpdateStrategy us : _updateStrategies) { if (us.allowsUpdate(newMetadata, oldMetadata)) { strategy = us; break; } } if (strategy == null) throw new IllegalArgumentException( "No UpdateStrategy supports the supplied DeploymentMetadata changes."); synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) { final BundleFramework appFwk = _frameworksByAppScope.get(app.getApplicationMetadata().getApplicationScope()); strategy.update(new UpdateStrategy.UpdateInfo() { public void register(Bundle bundle) { bundles.add(bundle); } public void unregister(Bundle bundle) { bundles.remove(bundle); } public Map<DeploymentContent, BundleSuggestion> suggestBundle( Collection<DeploymentContent> bundles) throws BundleException { return locator.suggestBundle(bundles); } public boolean startBundles() { return startBundles; } public BundleFramework getSharedFramework() { return _sharedBundleFramework; } public DeploymentMetadata getOldMetadata() { return oldMetadata; } public DeploymentMetadata getNewMetadata() { return newMetadata; } public AriesApplication getApplication() { return app; } public BundleFramework getAppFramework() { return appFwk; } }); } } }
8,801
0
Create_ds/aries/application/application-runtime-framework-management/src/main/java/org/apache/aries/application/runtime/framework
Create_ds/aries/application/application-runtime-framework-management/src/main/java/org/apache/aries/application/runtime/framework/management/SharedBundleFramework.java
/* * 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.aries.application.runtime.framework.management; import java.util.Properties; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.aries.application.management.spi.framework.BundleFramework; import org.apache.aries.application.management.spi.framework.BundleFrameworkConfiguration; import org.apache.aries.application.management.spi.framework.BundleFrameworkConfigurationFactory; import org.apache.aries.application.management.spi.framework.BundleFrameworkFactory; import org.apache.aries.application.management.spi.repository.ContextException; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; public class SharedBundleFramework { private static final Logger LOGGER = LoggerFactory.getLogger(SharedBundleFramework.class); private static BundleFramework sharedFramework; /** * This is not the right way to make blueprint usable by applications, but * it is all we have time to make work. I have locked down the version * ranges so that this can be fixed properly in the future. NB The * org.osgi.service.blueprint package is deliberately unversioned as it is * not part of the osgi compendium. */ private static final String RUNTIME_PACKAGES = "org.osgi.service.blueprint,org.osgi.service.blueprint.container;version=\"[1.0.0,1.0.1]\",org.osgi.service.blueprint.reflect;version=\"[1.0.0,1.0.1]\",org.apache.aries.transaction.exception;version=\"[1.0.0,2.0.0)\",org.osgi.service.cm;resolution:=optional"; /** * create using any bundle context in EBA App framework as we want to create * a child framework under EBA App framework * * @param bc * @throws BundleException * @throws InvalidSyntaxException */ private static void createSharedBundleFramework(BundleContext bc, BundleFrameworkConfigurationFactory bundleFrameworkConfigFactory, BundleFrameworkFactory bundleFrameworkFactory) throws ContextException { LOGGER.debug(LOG_ENTRY, "createSharedBundleFramework", new Object[] { bc, bundleFrameworkFactory }); try { BundleFrameworkConfiguration config = new SharedBundleFrameworkConfiguration( bundleFrameworkConfigFactory.createBundleFrameworkConfig( BundleFramework.SHARED_BUNDLE_FRAMEWORK, bc)); sharedFramework = bundleFrameworkFactory.createBundleFramework(bc, config); sharedFramework.start(); } catch (BundleException e) { LOGGER.debug(LOG_EXIT, "createSharedBundleFramework", e); throw new ContextException("Unable to create or start the shared framework composite bundle " + sharedFramework, e); } LOGGER.debug(LOG_EXIT, "createSharedBundleFramework"); } /** * pass in the EBA framework bundle context and get the shared bundle * framework associated with the bundle context * * @param bc * any bundle context in EBA framework * @return the composite bundle associated with the shared bundle framework * @throws BundleException * @throws InvalidSyntaxException * @throws SharedFrameworkCreationException */ public synchronized static BundleFramework getSharedBundleFramework(BundleContext bc, BundleFrameworkConfigurationFactory bfcf, BundleFrameworkFactory bff) throws ContextException { LOGGER.debug(LOG_ENTRY, "getSharedBundleFramework", new Object[] { bc, bff }); if (sharedFramework == null) { createSharedBundleFramework(bc, bfcf, bff); } LOGGER.debug(LOG_EXIT, "getSharedBundleFramework", sharedFramework); return sharedFramework; } /** * Wrapper for the basic framework configuration * @author cwilkin * */ private static class SharedBundleFrameworkConfiguration implements BundleFrameworkConfiguration { BundleFrameworkConfiguration basicConfig = null; public SharedBundleFrameworkConfiguration(BundleFrameworkConfiguration basicConfig) { this.basicConfig = basicConfig; } public String getFrameworkID() { return basicConfig.getFrameworkID(); } public Properties getFrameworkManifest() { Properties compositeManifest = basicConfig.getFrameworkManifest(); compositeManifest.put(Constants.BUNDLE_SYMBOLICNAME, BundleFramework.SHARED_BUNDLE_FRAMEWORK); // Add blueprint so that it is available to applications, unless configuration has already been provided. String existingImports = (String) compositeManifest.get(Constants.IMPORT_PACKAGE); if (existingImports == null){ compositeManifest.put(Constants.IMPORT_PACKAGE, RUNTIME_PACKAGES); } return compositeManifest; } public Properties getFrameworkProperties() { return basicConfig.getFrameworkProperties(); } } }
8,802
0
Create_ds/aries/application/application-install/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-install/src/main/java/org/apache/aries/application/install/EBAInstaller.java
/* * 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.install; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.AriesApplicationContext; import org.apache.aries.application.management.AriesApplicationManager; import org.apache.aries.util.filesystem.FileSystem; import org.apache.felix.fileinstall.ArtifactInstaller; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EBAInstaller implements ArtifactInstaller { private static final Logger LOGGER = LoggerFactory.getLogger(EBAInstaller.class); private Map<File, AriesApplicationContext> appContexts = new HashMap<File, AriesApplicationContext>(); private AriesApplicationManager applicationManager; public AriesApplicationManager getApplicationManager() { return applicationManager; } public void setApplicationManager(AriesApplicationManager applicationManager) { this.applicationManager = applicationManager; } public boolean canHandle(File fileToHandlerLocation) { return fileToHandlerLocation.getName().toLowerCase().endsWith(".eba"); } public void install(File applicationLocation) throws Exception { AriesApplication app = applicationManager .createApplication(FileSystem.getFSRoot(applicationLocation)); String appSymName = app.getApplicationMetadata().getApplicationSymbolicName(); Version appVersion = app.getApplicationMetadata().getApplicationVersion(); LOGGER.debug("created app from {} : {} {} with contents {}", new Object[] { applicationLocation.getName(), appSymName, appVersion, app.getApplicationMetadata().getApplicationContents() }); AriesApplicationContext context = applicationManager.install(app); LOGGER.debug("installed app {} {} state: {}", new Object[] { appSymName, appVersion, context.getApplicationState() }); context.start(); LOGGER.debug("started app {} {} state: {}", new Object[] { appSymName, appVersion, context.getApplicationState() }); // Store the application context away because it is the application context we need // to pass to the application manager if we're later asked to uninstall the application appContexts.put(applicationLocation, context); } public void uninstall(File applicationLocation) throws Exception { AriesApplicationContext context = appContexts.get(applicationLocation); String appSymName = context.getApplication().getApplicationMetadata().getApplicationSymbolicName(); Version appVersion = context.getApplication().getApplicationMetadata().getApplicationVersion(); LOGGER.debug("uninstalling {} {} ", new Object[] { appSymName, appVersion }); if (context != null) { context.stop(); applicationManager.uninstall(context); } appContexts.remove(applicationLocation); LOGGER.debug("uninstalled {} {} state: {}", new Object[] { appSymName, appVersion, context.getApplicationState() }); } public void update(File arg0) throws Exception { throw new UnsupportedOperationException("Updating .eba file is not supported"); } }
8,803
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/ApplicationMetadata.java
/* * 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; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.List; import org.osgi.framework.Version; /** * A representation of an APPLICATION.MF file. * */ public interface ApplicationMetadata { /** * get the value of the Application-SymbolicName header * @return the value of the Application-SymbolicName header */ public String getApplicationSymbolicName(); /** * get the value of the Application-Version header * @return the value of the Application-Version header */ public Version getApplicationVersion(); /** * get the name of the application * @return the name of the application */ public String getApplicationName(); /** * get the list of Application contents includes bundle name, * version, directives and attributes * @return the list of the Application contents */ public List<Content> getApplicationContents(); /** * get the value of the Export-Service header * @return the list of ServiceDeclaration */ public List<ServiceDeclaration> getApplicationExportServices(); /** * get the value of the Import-Service header * @return the list of ServiceDeclaration */ public List<ServiceDeclaration> getApplicationImportServices(); /** * get the value of the Application-Scope, which is * calculated from Application-SymbolicName and Application-Version * @return the value of the AppScope */ public String getApplicationScope(); /** * get the list of use-bundle content including bundle symbolic name and version range * @return the collection of use bundles. */ public Collection<Content> getUseBundles(); /** * Persist this metadata. * @param f The file to store this metadata to * @throws IOException */ public void store(File f) throws IOException; /** * Persist this metadata. * @param out The output stream to store this metadata to * @throws IOException */ public void store(OutputStream out) throws IOException; }
8,804
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/InvalidAttributeException.java
/* * 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; public class InvalidAttributeException extends Exception { /** * */ private static final long serialVersionUID = 4889305636433626372L; public InvalidAttributeException (Exception e) { super(e); } public InvalidAttributeException (String s) { super(s); } public InvalidAttributeException (String s, Throwable t) { super(s, t); } }
8,805
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/DeploymentMetadataFactory.java
/* * 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; import java.io.IOException; import java.io.InputStream; import java.util.Set; import java.util.jar.Manifest; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.ResolverException; import org.apache.aries.util.filesystem.IFile; /** * Methods for creating a DeploymentMetadata instance */ public interface DeploymentMetadataFactory { /** * Deprecated. Use parseDeploymentManifest(IFile) to create a DeploymentMetadata from an AriesApplication and its by-value bundles. * * @param app The AriesApplication in question * @param bundleInfo A resolved set of BundleInfo objects * @throws ResolverException * @return DeploymentMetadata instance */ @Deprecated public DeploymentMetadata createDeploymentMetadata (AriesApplication app, Set<BundleInfo> bundleInfo) throws ResolverException; /** * Deprecated. Use parseDeploymentMetadata. * * @param src DEPLOYMENT.MF file, either in an exploded directory or within a jar file. * @throws IOException * @return DeploymentMetadata instance */ @Deprecated public DeploymentMetadata createDeploymentMetadata (IFile src) throws IOException; /** * Extract a DeploymentMetadata instance from an IFile * * @param src DEPLOYMENT.MF file, either in an exploded directory or within a jar file. * @throws IOException * @return DeploymentMetadata instance */ public DeploymentMetadata parseDeploymentMetadata (IFile src) throws IOException; /** * Deprecated. Use parseDeploymentMetadata. * * @param in InputStream * @throws IOException * @return DeploymentMetadata instance */ @Deprecated public DeploymentMetadata createDeploymentMetadata (InputStream in) throws IOException; /** * Extract a DeploymentMetadata instance from InputStream. * * @param in InputStream * @throws IOException * @return DeploymentMetadata instance */ public DeploymentMetadata parseDeploymentMetadata (InputStream in) throws IOException; /** * Extract a DeploymentMetadata instance from Manifest. * * @param manifest Manifest * @throws IOException * @return DeploymentMetadata instance */ public DeploymentMetadata createDeploymentMetadata (Manifest manifest) throws IOException; }
8,806
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/DeploymentContent.java
/* * 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; import org.osgi.framework.Version; /** * An entry in DEPLOYMENT.MF's Deployed-Content header */ public interface DeploymentContent extends Content { /** * get the exact version of the deployment content * this cannot be null * @return the exact version */ public Version getExactVersion(); }
8,807
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/ApplicationMetadataFactory.java
/* * 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; import java.io.IOException; import java.io.InputStream; import java.util.jar.Manifest; /** * Provides various means of generating {@link org.apache.aries.application.ApplicationMetadata * ApplicationMetadata} instances. */ public interface ApplicationMetadataFactory { /** * Parse from the input stream the application manifest. This method is more * lenient than the normal manifest parsing routine and does not limit the * manifest to 76 bytes as a line length. * * @param in the inputstream of the manifest to parse. * @return the parsed application metadata. * */ public ApplicationMetadata parseApplicationMetadata(InputStream in) throws IOException; /** * Create the application metadata from the provided Manifest. This is provided * so application metadata can be created from within the JVM. When reading * from a stream the parseApplication method should be used. * * @param man the manifest to read from * @return the parsed application metadata. */ public ApplicationMetadata createApplicationMetadata(Manifest man); }
8,808
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/ServiceDeclaration.java
/* * 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; import org.osgi.framework.Filter; /** * Represents a service imported or exported by an Aries application. */ public interface ServiceDeclaration { /** * get the interface name for the service * @return The name of the service's interface class. */ public abstract String getInterfaceName(); /** * get the filter for the service * @return the filter for the service or null if there is no filter defined */ public abstract Filter getFilter(); }
8,809
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/DeploymentMetadata.java
/* * 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; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.List; import java.util.Map; import org.osgi.framework.Filter; import org.osgi.framework.Version; /** * Represents the parsed contents of a DEPLOYMENT.MF file * */ public interface DeploymentMetadata { /** * get the value of the Application-SymbolicName header * @return the value of the Application-SymbolicName header */ public String getApplicationSymbolicName(); /** * get the value of the Application-Version header * @return the value of the Application-Version header */ public Version getApplicationVersion(); /** * get the value of the Deployed-Content header * @return the list of the deployed content */ public List<DeploymentContent> getApplicationDeploymentContents(); /** * get the value of the Provision-Bundle header * @return the list of non-app bundles to provision. */ public List<DeploymentContent> getApplicationProvisionBundles(); /** * get the value of Deployed-UseBundle header * * @return the list of bundles to use from the deployment. */ public Collection<DeploymentContent> getDeployedUseBundle(); /** * get the value of Import-Package * @return all the packages to import from non-app content. */ public Collection<Content> getImportPackage(); /** * Get the list of DeployedService-Import * @return DeployedService-Import */ public Collection<Filter> getDeployedServiceImport(); /** * get the contents of deployment manifest in a map * @return the required feature map */ public Map<String, String> getHeaders(); /** * Obtain the associated * {@link org.apache.aries.application.ApplicationMetadata ApplicationMetadata}. * @return The application metadata. */ public ApplicationMetadata getApplicationMetadata(); /** * Persist this metadata as Manifest-formatted text. * @param f The file to store this metadata to * @throws IOException */ public void store(File f) throws IOException; /** * Persist this metadata. * @param out The OutputStream to store this metadata to. * @throws IOException */ public void store(OutputStream out) throws IOException; }
8,810
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/Content.java
/* * 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; import java.util.Map; import org.apache.aries.util.VersionRange; /** * A representation of content metadata such as Application-Content, Import-Package, etc * */ public interface Content { /** * get the content name of the content * @return the content name of the content */ public String getContentName(); /** * get the attributes of the content * @return the attributes of the content */ public Map<String, String> getAttributes(); /** * get the directives of the content * @return the directives of the content */ public Map<String, String> getDirectives(); /** * get the value of the attribute with the specified key * @param key * @return value of the attribute specified by the key */ public String getAttribute(String key); /** * get the value of the directive with the specified key * @param key * @return the value of the directive specified by the key */ public String getDirective(String key); /** * get the version info for the version attribute * @return null if there is no version associated with this content */ public VersionRange getVersion(); /** * get the attribute and directive info in NameValueMap * @return namevalueMap that contains attribute and directive info */ public Map<String, String> getNameValueMap(); }
8,811
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/WrappedReferenceMetadata.java
/* * 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; /** * Information about a parsed blueprint reference */ public interface WrappedReferenceMetadata { /** * Get the properties of the associated blueprint service * @return The filter, or null for no filter */ String getFilter(); /** * Get the interface required by the reference * @return the interface, or null if unspecified */ String getInterface(); /** * Get the component-name attribute. * @return Service name */ String getComponentName(); /** * Is this a reference list or a reference * @return true if a reference list */ boolean isList(); /** * Is this an optional reference * @return true if optional */ boolean isOptional(); /** * Get the reference's id as defined in the blueprint * @return the blueprint reference id */ String getId(); }
8,812
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ExportedPackage.java
/* * 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; /** * Model an exported package. * */ public interface ExportedPackage extends Provider, DeploymentMFElement { /** * The package name * @return The package name */ String getPackageName(); /** * The package version * @return The package version */ String getVersion(); /** * The resource that exports the package. * @return The resource that exports the package. */ ModelledResource getBundle(); }
8,813
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ExportedBundle.java
/* * 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; /** * Model a bundle, required by another bundle. * */ public interface ExportedBundle extends Provider, DeploymentMFElement { /** * The bundle symbolic name * @return the bundle symbolic name */ String getSymbolicName(); /** * The bundle version * @return the bundle version */ String getVersion(); /** * Whether the bundle is fragment * @return true if it is a fragment. */ boolean isFragment(); /** * Get the fragment host. * @return The fragment host that the bundle attaches. */ ImportedBundle getFragmentHost(); }
8,814
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ModelledResourceManager.java
/* * 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; import java.io.IOException; import java.io.InputStream; import org.apache.aries.util.filesystem.IDirectory; public interface ModelledResourceManager { /** * Utility interface for re-presenting a source of InputStreams */ interface InputStreamProvider { /** * Return a fresh input stream */ InputStream open() throws IOException; } /** * Obtain a ModelledResource object. * @param uri The URI to the conceptual location of the bundle, that will be returned from the getLocation method * on {@link ModelledResource} * @param bundle the bundle file * @return the modelled resource. */ ModelledResource getModelledResource(String uri, IDirectory bundle) throws ModellerException; /** * Obtain a ModelledResource object. * * This method is equivalent to calling <pre>getModelledResource(bundle.toURL().toURI().toString(), bundle)</pre> * @param bundle the bundle file * @return the modelled resource. */ ModelledResource getModelledResource(IDirectory bundle) throws ModellerException; /** * Obtain a ModelledResource via InputStreams * * * @param uri The URI to the conceptual location of the bundle, that will be returned from the getLocation method * on {@link ModelledResource} * @param bundle The bundle * @return * @throws ModellerException */ ModelledResource getModelledResource(String uri, InputStreamProvider bundle) throws ModellerException; /** * Parse service and reference elements of a bundle * @param archive * @return * @throws ModellerException */ ParsedServiceElements getServiceElements (IDirectory archive) throws ModellerException; /** * Parse service and reference elements of a bundle * @param archive * @return * @throws ModellerException */ ParsedServiceElements getServiceElements (InputStreamProvider archive) throws ModellerException; }
8,815
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/Provider.java
/* * 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; import java.util.Map; /** Base interface to model a bundle, package or service */ public interface Provider { /** * Get resource type. * @return The resource type. */ ResourceType getType(); /** ResourceType-dependent things. See Capability.getProperties() * Define constants for things like a service's list of interfaces, versions, etc */ Map<String, Object> getAttributes(); }
8,816
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ParsedServiceElements.java
/* * 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; import java.util.Collection; /** * A simple data structure containing two immutable Collections, * one each of ImportedServiceImpl and ExportedServiceImpl */ public interface ParsedServiceElements { /** * Get the ImportedServices * @return imported services */ public Collection<ImportedService> getReferences(); /** * Get the exported services * @return exported services */ public Collection<ExportedService> getServices(); }
8,817
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ModelledResource.java
/* * 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; import java.util.Collection; /** * Model a bundle resource. * */ public interface ModelledResource extends DeploymentMFElement { /** * The resource's symbolic name * @return The resource symbolic name */ String getSymbolicName(); /** * The resource version * @return The resource version */ String getVersion(); /** Returns a String which can be turned into a URL to the bundle binary * @return the location of the bundle */ public String getLocation(); /** * Import-Package header modelled to be a collection of the imported packages objects. * @return a collection of the imported packages. */ Collection<? extends ImportedPackage> getImportedPackages(); /** * Import-Service header modelled to be a collection of imported service objects. * This contains the blueprint service referenced by this resource. * @return a collection of the imported services. */ Collection<? extends ImportedService> getImportedServices(); /** * Export-Package header modelled to be a collection of exported package objects. * @return a collection of exported package objects. */ Collection<? extends ExportedPackage> getExportedPackages(); /** * Export-Service header modelled to be a collection of exported service objects. * This includes the blueprint services supported by this resource. * @return a collection of exported service objects. */ Collection<? extends ExportedService> getExportedServices(); /** * Return the bundle that represents the resource object. * @return the exported bundle */ ExportedBundle getExportedBundle(); /** * The resource type, mainly BUNDLE or other special bundle. * @return The resource type. */ ResourceType getType(); /** * The required bundles modelled as a collection of ImportedBundle objects. * @return a collection of ImportedBundle objects. */ Collection<? extends ImportedBundle> getRequiredBundles(); /** * Whether the resource is fragment. * @return true if it is a fragment. */ boolean isFragment(); /** * The fragment host. * @return The fragment host. */ public ImportedBundle getFragmentHost(); }
8,818
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/WrappedServiceMetadata.java
/* * 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; import java.util.Collection; import java.util.Map; /** * A proxy for org.osgi.service.blueprint.reflect.ServiceMetadata, which we cannot * pass to clients in the outer framework. We'll just expose the methods that we * know we're going to need. * */ public interface WrappedServiceMetadata extends Comparable<WrappedServiceMetadata> { /** * Get the properties of the associated blueprint service * @return Service properties. The values in the Map will be either String or String[]. */ Map<String, Object> getServiceProperties(); /** * Get the interfaces implemented by the service * @return List of interfaces */ Collection<String> getInterfaces(); /** * Get the service name. This we hope will be short, human-readable, and unique. * @return Service name */ String getName(); /** * Get the service ranking * @return ranking */ int getRanking(); /** * Sometimes we want to know if two services are identical except for their names * @param w A wrapped service metadata for comparison. * @return true if the two services are indistinguishable (in the OSGi service registry) - * this will be true if only their names are different, and their interfaces and service * properties the same. */ boolean identicalOrDiffersOnlyByName (WrappedServiceMetadata w); }
8,819
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ImportedPackage.java
/* * 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; import java.util.Map; /** * Model an imported package. */ public interface ImportedPackage extends Consumer, DeploymentMFElement { /** * The imported package name * @return the package name */ String getPackageName(); /** * The imported package version * @return the version range as a string. */ String getVersionRange(); /** * All attributes specified in the import package header * @return the map containing the attributes. */ Map<String, String> getAttributes(); }
8,820
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ServiceModeller.java
/* * 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; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.manifest.BundleManifest; public interface ServiceModeller { /** * Determine whether any additional services will be imported or exported * by this bundle. For example as EJBs, Declarative Services etc * * @param bundle * @return */ public ParsedServiceElements modelServices(BundleManifest manifest, IDirectory bundle) throws ModellerException; }
8,821
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ParserProxy.java
/* * 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; import java.io.InputStream; import java.net.URL; import java.util.List; /** * This interface is implemented by the service which proxies the * Apache Aries blueprint parser. ParserProxy services offer higher * level methods built on top of the Blueprint parser. * */ public interface ParserProxy { /** * Parse blueprint xml files and extract the parsed ServiceMetadata objects * @param blueprintsToParse URLs to blueprint xml files * @return List of (wrapped) ServiceMetadata objects */ public List<? extends WrappedServiceMetadata> parse (List<URL> blueprintsToParse) throws Exception; /** * Parse a blueprint xml files and extract the parsed ServiceMetadata objects * @param blueprintToParse URL to blueprint xml file * @return List of (wrapped) ServiceMetadata objects */ public List<? extends WrappedServiceMetadata> parse (URL blueprintToParse) throws Exception; /** * Parse an InputStream containing blueprint xml and extract the parsed ServiceMetadata objects * @param blueprintToParse InputStream containing blueprint xml data. The caller is responsible * for closing the stream afterwards. * @return List of (wrapped) ServiceMetadata objects */ public List<? extends WrappedServiceMetadata> parse (InputStream blueprintToParse) throws Exception; /** * Parse an InputStream containing blueprint xml and extract Service, Reference and RefList * elements. * @return All parsed Service, Reference and RefList elements */ public ParsedServiceElements parseAllServiceElements (InputStream blueprintToParse) throws Exception; }
8,822
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/Consumer.java
/* * 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; /* Base interface for a model of a requirement, or need for something, such as a bundle, * package or service. */ public interface Consumer { /** * Return the resource type * @return the resource type, such as BUNDLE, PACKAGE, SERVICE, OTHER */ ResourceType getType(); /** * This is not the same as the filter which you might get, say, by parsing a blueprint * reference. It is more specific - and usable at runtime. * * @return String filter matching every property required by this consumer */ String getAttributeFilter(); /** * Whether the resources consumed can be multiple. * @return true if multiple resources can be consumed. */ boolean isMultiple(); /** * Whether the resource consumed can be optional. * @return true if optional. */ boolean isOptional(); /** * Whether the provider object satisfies the consume criteria. * @param capability The provider capability * @return true if the capability satisfies the consuming criteria. */ boolean isSatisfied(Provider capability); }
8,823
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ResourceType.java
/* * 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; public enum ResourceType {BUNDLE, PACKAGE, SERVICE, COMPOSITE, OTHER; /** * An enum class to represent the resource type, such as bundle, package, service etc. */ @Override public String toString() { return super.toString().toLowerCase(); } }
8,824
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ImportedBundle.java
/* * 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; /** * Model a required bundle. * */ public interface ImportedBundle extends Consumer { /** * The imported bundle symbolic name * @return the symbolic name */ String getSymbolicName(); /** * The version range that the imported bundle's version fall into. * @return The version range as a string. */ String getVersionRange(); }
8,825
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ImportedService.java
/* * 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; /** * This interface represents the imported service. It has no other methods apart from the * two super interfaces Consumer, DeploymentMFElement and WrappedReferenceMetadata. */ public interface ImportedService extends Consumer, WrappedReferenceMetadata, DeploymentMFElement { }
8,826
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/DeploymentMFElement.java
/* * 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; public interface DeploymentMFElement { /** * @return String suitable for inclusion in DEPLOYMENT.MF */ public String toDeploymentString(); }
8,827
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ModellingConstants.java
/* * 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; import org.osgi.framework.Constants; public class ModellingConstants { public static final String OBR_SYMBOLIC_NAME = "symbolicname"; public static final String OBR_PRESENTATION_NAME = "presentationname"; public static final String OBR_MANIFEST_VERSION = "manifestversion"; public static final String OBR_BUNDLE = "bundle"; public static final String OBR_PACKAGE = "package"; public static final String OBR_SERVICE = "service"; public static final String OBR_COMPOSITE_BUNDLE = "composite-bundle"; public static final String OBR_UNKNOWN = "unknown"; public static final String OPTIONAL_KEY = Constants.RESOLUTION_DIRECTIVE + ":"; }
8,828
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ExportedService.java
/* * 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; /** * This interface models the exported service. It has no other methods apart from the * two super interfaces Provider and WrappedServiceMetadata. */ public interface ExportedService extends Provider, WrappedServiceMetadata { }
8,829
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ModellerException.java
/* * 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; public class ModellerException extends Exception { public ModellerException (String s) { super(s); } public ModellerException (Exception e) { super (e); } public ModellerException (String s, Throwable t) { super (s, t); } }
8,830
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/DeployedBundles.java
/* * 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; import java.util.Collection; import java.util.Map; import org.apache.aries.application.management.ResolverException; /** A model of a collection of bundles and similar resources */ public interface DeployedBundles { /** Add a modelled resource */ void addBundle(ModelledResource modelledBundle); /** * Get the value corresponding to the Deployed-Content header in the deployment.mf. * @return a manifest entry, or an empty string if there is no content. */ String getContent(); /** * Get the value corresponding to the Deployed-Use-Bundle header in the deployment.mf. * @return a manifest entry, or an empty string if there is no content. */ String getUseBundle(); /** * Get the value corresponding to the Provision-Bundle header in the deployment.mf. * @return a manifest entry, or an empty string if there is no content. */ String getProvisionBundle(); /** * Get the value corresponding to the Import-Package header in the deployment.mf. * @return a manifest entry, or an empty string if there is no content. * @throws ResolverException if the requirements could not be resolved. */ String getImportPackage() throws ResolverException; /** * Get the Deployed-ImportService header. * this.deployedImportService contains all the service import filters for every * blueprint component within the application. We will only write an entry * to Deployed-ImportService if * a) the reference isMultiple(), or * b) the service was not available internally when the app was first deployed * */ String getDeployedImportService(); String toString(); /** * Get the set of bundles that are going to be deployed into an isolated framework * @return a set of bundle metadata */ Collection<ModelledResource> getDeployedContent(); /** * Get the set of bundles that map to Provision-Bundle: these plus * getRequiredUseBundle combined give the bundles that will be provisioned * into the shared bundle space * 'getProvisionBundle' returns the manifest header string, so this method * needs to be called something else. * */ Collection<ModelledResource> getDeployedProvisionBundle (); /** * Get the subset of bundles specified in use-bundle that are actually required to * satisfy direct requirements of deployed content. * @return a set of bundle metadata. * @throws ResolverException if the requirements could not be resolved. */ Collection<ModelledResource> getRequiredUseBundle() throws ResolverException; /** * A local environment extension to Apache Aries may manipulate a DeployedBundles object. * This method returns the extra headers and their values. * @return the extra headers */ Map<String, String> getExtraHeaders(); }
8,831
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/ModellingManager.java
/* * 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; 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; public interface ModellingManager { ExportedBundle getExportedBundle(Map<String, String> attributes, ImportedBundle fragHost); ExportedPackage getExportedPackage(ModelledResource mr, String pkg, Map<String, Object> attributes); ExportedService getExportedService(String name, int ranking, Collection<String> ifaces, Map<String, Object> serviceProperties); ExportedService getExportedService(String ifaceName, Map<String, String> attrs); ImportedBundle getImportedBundle(String filterString, Map<String, String> attributes) throws InvalidAttributeException; ImportedBundle getImportedBundle(String bundleName, String versionRange) throws InvalidAttributeException; ImportedPackage getImportedPackage(String pkg, Map<String, String> attributes) throws InvalidAttributeException; ImportedService getImportedService(boolean optional, String iface, String componentName, String blueprintFilter, String id, boolean isMultiple) throws InvalidAttributeException; ImportedService getImportedService(String ifaceName, Map<String, String> attributes) throws InvalidAttributeException; ModelledResource getModelledResource(String fileURI, BundleInfo bundleInfo, Collection<ImportedService> importedServices, Collection<ExportedService> exportedServices) throws InvalidAttributeException; ModelledResource getModelledResource(String fileURI, Attributes bundleAttributes, Collection<ImportedService> importedServices, Collection<ExportedService> exportedServices) throws InvalidAttributeException; ModelledResource getModelledResource (String fileURI, Attributes bundleAttributes, ExportedBundle exportedBundle, ResourceType resourceType, Collection<ImportedService> importedServices, Collection<ExportedService> exportedServices) throws InvalidAttributeException; ParsedServiceElements getParsedServiceElements( Collection<ExportedService> services, Collection<ImportedService> references); }
8,832
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/modelling/utils/ModellingHelper.java
/** * 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.aries.application.modelling.utils; import java.util.Collection; import java.util.Map; import org.apache.aries.application.InvalidAttributeException; 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.Provider; /** * Useful functions associated with application modelling * */ public interface ModellingHelper { /** * Check that all mandatory attributes from a Provider are specified by the consumer's attributes * @param consumerAttributes * @param p * @return true if all mandatory attributes are present, or no attributes are mandatory */ boolean areMandatoryAttributesPresent(Map<String,String> consumerAttributes, Provider p); /** * Create an ImportedBundle from a Fragment-Host string * @param fragmentHostHeader * @return the imported bundle * @throws InvalidAttributeException */ ImportedBundle buildFragmentHost(String fragmentHostHeader) throws InvalidAttributeException; /** * Create a new ImnportedPackage that is the intersection of the two supplied imports. * @param p1 * @param p2 * @return ImportedPackageImpl representing the intersection, or null. All attributes must match exactly. */ ImportedPackage intersectPackage (ImportedPackage p1, ImportedPackage p2); /** * Factory method for objects implementing the DeployedBundles interface * */ DeployedBundles createDeployedBundles (String assetName, Collection<ImportedBundle> appContentNames, Collection<ImportedBundle> appUseBundleNames, Collection<ModelledResource> fakeServiceProvidingBundles); }
8,833
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/AriesApplicationListener.java
/* * 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.management; /** * A client that wishes to receive AriesApplicationEvents should implement this interface. */ public interface AriesApplicationListener { /** * Receives notification of an application lifecycle event */ public void applicationChanged (AriesApplicationEvent event); }
8,834
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/AriesApplicationManager.java
/* * 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.management; import java.net.URL; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.util.filesystem.IDirectory; import org.osgi.framework.BundleException; /** * An AriesApplicationManager service is used to create, install and uninstall Aries * applications. */ public interface AriesApplicationManager { /** * Create an AriesApplication from a local resource. * The application won't be automatically resolved if the * archive does not contain a deployment manifest. * * @param source .eba file, or exploded directory * @return AriesApplication * @throws ManagementException */ public AriesApplication createApplication(IDirectory source) throws ManagementException; /** * Create an AriesApplication from a remote resource. * The application won't be automatically resolved if the * archive does not contain a deployment manifest. * * @param url * @return the application. * @throws ManagementException */ public AriesApplication createApplication(URL url) throws ManagementException; /** * Install an AriesApplication - i.e. load its bundles into the runtime, but do * not start them. * If the application is not resolved, a call to {@link #resolve(AriesApplication, ResolveConstraint...)} * will be performed and the resolved application will be installed. In such a case the resolved * application can be obtained by calling {@link org.apache.aries.application.management.AriesApplicationContext#getApplication()} * on the returned ApplicationContext. * * @param app Application to install * @return AriesApplicationContext, a handle to an application in the runtime * @throws BundleException * @throws ManagementException */ public AriesApplicationContext install(AriesApplication app) throws BundleException, ManagementException, ResolverException; /** * Uninstall an AriesApplication - i.e. unload its bundles from the runtime. * @param app The installed application to uninstall * @throws BundleException */ public void uninstall(AriesApplicationContext app) throws BundleException; /** * Add an AriesApplicationListener * @param l */ public void addApplicationListener(AriesApplicationListener l); /** * Remove an AriesApplicationListener * @param l */ public void removeApplicationListener(AriesApplicationListener l); /** * Update an application's deployment and apply the changes to the runtime if the application is deployed * @param app The application to change * @param depMf The new deployment metadata * @return {@link AriesApplicationContext} Returns a new application context if the app * is currently deployed, or null if the app is not currently installed * * @throws UpdateException if the deployment changes could not be effected in the runtime * @throws IllegalArgumentException if the deployment metadata does not correspond to the same application * (same symbolic name and same version) */ public AriesApplicationContext update(AriesApplication app, DeploymentMetadata depMf) throws UpdateException; /** * Resolve an AriesApplication against a set of constraints. Each ResolveConstraint * represents a single proposed change to the content of an application. * If no constraints are given, a default resolution will be performed. * * @param originalApp Original application * @param constraints Constraints * @throws ResolverException * @return New AriesApplication */ AriesApplication resolve (AriesApplication originalApp, ResolveConstraint ... constraints) throws ResolverException; }
8,835
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/UpdateException.java
/* * 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.aries.application.management; public class UpdateException extends Exception { private static final long serialVersionUID = -6118824314732969652L; private Exception rollbackFailure; private boolean rolledBack; public UpdateException(String message, Exception e, boolean rolledBack, Exception rollbackException) { super(message, e); this.rollbackFailure = rollbackException; this.rolledBack = rolledBack; } public boolean hasRolledBack() { return rolledBack; } public Exception getRollbackException() { return rollbackFailure; } }
8,836
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/AriesApplicationEvent.java
/* * 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.management; /** * Objects of this type are passed to ApplicationListener clients */ public abstract class AriesApplicationEvent { /** * Get the type of the event * @return the event type. */ abstract public AriesApplicationContext.ApplicationState getType(); /** * Get the associated AriesApplication * @return the application */ abstract public AriesApplication getApplication(); }
8,837
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/BundleInfo.java
/* * 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.management; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import org.osgi.framework.Version; import org.apache.aries.application.Content; /** * Information about a bundle */ public interface BundleInfo { /** Bundle-SymbolicName */ public String getSymbolicName(); /** Returns the directives specified on the symbolic name */ public Map<String, String> getBundleDirectives(); /** Returns the attributes specified on the symbolic name */ public Map<String, String> getBundleAttributes(); /** Bundle-Version: */ public Version getVersion(); /** Returns a String which can be turned into a URL to the bundle binary */ public String getLocation(); /** Import-Package */ public Set<Content> getImportPackage(); /** Require-Bundle */ public Set<Content> getRequireBundle(); /** Export-Package */ public Set<Content> getExportPackage(); /** Import-Service */ public Set<Content> getImportService(); /** Export-Service */ public Set<Content> getExportService(); /** All the headers in the MANIFEST.MF file */ public Map<String, String> getHeaders(); /** The Attribute object in the MANIFEST.MF file */ public Attributes getRawAttributes(); }
8,838
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/ResolveConstraint.java
/* * 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.management; import org.apache.aries.util.VersionRange; /** * An administrator may wish to change the content of an installed application. * A ResolveConstraint records one of the desired elements of the newly re-resolved * application. */ public interface ResolveConstraint { /** * The name of the newly required bundle * @return Bundle name */ public String getBundleName(); /** * The version range of the newly required bundle * @return allowed range */ public VersionRange getVersionRange(); }
8,839
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/AriesApplicationContext.java
/* * 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.management; import java.util.Set; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; /** * Represents an Aries application in the runtime. See the application-runtime module for a * sample implementation. */ public interface AriesApplicationContext { /** * Get the state of a running application. An application is INSTALLED if all its bundles * are installed, RESOLVED if all its bundles are resolved, ACTIVE if all its bundles are * active, and so on. * @return ApplicationState. */ public ApplicationState getApplicationState(); /** * Obtain the associated AriesApplication metadata. * @return AriesApplication */ public AriesApplication getApplication(); /** * Start the application by starting all its constituent bundles as per the DeploymentContent * in the associated AriesApplication's DeploymentMetadata. * @throws BundleException */ public void start() throws BundleException, IllegalStateException; /** * Stop the application by stopping all its constituent bundles. * @throws BundleException */ public void stop() throws BundleException, IllegalStateException; /** * Get the org.osgi.framework.Bundle objects representing the application's runtime * constituents. * @return The application's runtime content. */ public Set<Bundle> getApplicationContent(); public enum ApplicationState { INSTALLED, RESOLVED, STARTING, STOPPING, ACTIVE, UNINSTALLED } }
8,840
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/ResolverException.java
/* * 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.aries.application.management; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.application.modelling.ModellingConstants; /** * Exception thrown by the AriesApplicationResolver interface */ public class ResolverException extends Exception { private static final long serialVersionUID = 8176120468577397671L; private Map<String, String> _unsatisfiedRequirementMessages = new HashMap<String, String>(); /** * Construct from an Exception * @param e */ public ResolverException (Exception e) { super(e); } /** * Construct from a String * @param s */ public ResolverException (String s) { super(s); } public void setUnsatisfiedRequirements (List<String> reqts) { // Assume the type is unknown if we don't get told it for (String reqt : reqts) { _unsatisfiedRequirementMessages.put(reqt, ModellingConstants.OBR_UNKNOWN); } } public List<String> getUnsatisfiedRequirements() { return new ArrayList<String>(_unsatisfiedRequirementMessages.keySet()); } public void setUnsatisfiedRequirementsAndReasons( Map<String, String> unsatisfiedRequirements) { _unsatisfiedRequirementMessages = unsatisfiedRequirements; } public Map<String, String> getUnsatisfiedRequirementsAndReasons() { return _unsatisfiedRequirementMessages; } }
8,841
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/AriesApplication.java
/* * 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.management; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.util.Set; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.DeploymentMetadata; /** * Metadata about an Aries application * */ public interface AriesApplication { /** * Get the application metadata, which is stored in META-INF/APPLICATION.MF. * @return ApplicationMetadata */ public ApplicationMetadata getApplicationMetadata(); /** * Get the deployment metadata, which is stored in META-INF/DEPLOYMENT.MF. * @return DeploymentMetadata */ public DeploymentMetadata getDeploymentMetadata(); /** * @return the set of bundles included in the application by value */ public Set<BundleInfo> getBundleInfo(); /** * Check if the application is resolved or not. * An application is said to be resolved if it has a valid deployment metadata. * During the installation process, an application will be automatically * resolved if it is not already. * * @return if the appplication is resolved or not. * @see org.apache.aries.application.management.AriesApplicationManager#install(AriesApplication) * @see org.apache.aries.application.management.AriesApplicationManager#resolve(AriesApplication, ResolveConstraint...) */ public boolean isResolved(); /** * Persist this metadata. * @param f The file to store this metadata to * @throws IOException */ public void store(File f) throws FileNotFoundException, IOException; /** * Persist this metadata. * @param out The output stream to store this metadata to * @throws IOException */ public void store(OutputStream out) throws FileNotFoundException, IOException; }
8,842
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/ManagementException.java
/* * 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.management; /** * An exception thrown by various methods within this package. */ public class ManagementException extends Exception { private static final long serialVersionUID = 6472726820228618243L; public ManagementException (Exception e) { super(e); } public ManagementException (String s) { super(s); } public ManagementException(String s, Exception e) { super(s, e); } }
8,843
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/repository/ContextException.java
/* * 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.management.spi.repository; /** * An exception thrown by various methods within this package. */ public class ContextException extends Exception { private static final long serialVersionUID = -6613842057223737125L; public ContextException (Exception e) { super(e); } public ContextException (String s) { super(s); } public ContextException(String s, Exception e) { super(s, e); } }
8,844
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/repository/BundleRepositoryManager.java
/* * 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.management.spi.repository; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion; public interface BundleRepositoryManager { /** * Gets a collection of all bundle repositories which can provide bundles to * the given application scope. * @param applicationName * @param applicationVersion * @return the collection of bundle repositories for an app. */ public Collection<BundleRepository> getBundleRepositoryCollection( String applicationName, String applicationVersion); /** * Gets all known bundle repositories * @return all known bundle repositories. */ public Collection<BundleRepository> getAllBundleRepositories(); /** * Get a collection of bundle installation suggestions from repositories * suitable for the given application scope * @param applicationName * @param applicationVersion * @param content * @return the bundle suggestions * @throws ContextException */ public Map<DeploymentContent, BundleSuggestion> getBundleSuggestions( String applicationName, String applicationVersion, Collection<DeploymentContent> content) throws ContextException; /** * Get a collection of bundle installation suggestions from all * known repositories * @param content * @return the bundle suggestions * @throws ContextException */ public Map<DeploymentContent, BundleSuggestion> getBundleSuggestions( Collection<DeploymentContent> content) throws ContextException; /** * Get a collection of bundle installation suggestions from the collection of * given repositories * @param brs * @param content * @return the bundle suggestions * @throws ContextException */ public Map<DeploymentContent, BundleSuggestion> getBundleSuggestions( Collection<BundleRepository> brs, Collection<DeploymentContent> content) throws ContextException; }
8,845
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/repository/BundleRepository.java
/* * 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.management.spi.repository; import java.util.Set; import org.apache.aries.application.Content; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.spi.framework.BundleFramework; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.Version; public interface BundleRepository { /** * Service property denoting the scope of the bundle repository. This can * <ul> * <li>global</li> * <li>&lt;app symbolic name&gt;_&lt;app version&gt;</li> * </ul> */ public static final String REPOSITORY_SCOPE = "repositoryScope"; public static final String GLOBAL_SCOPE = "global"; /** * A suggested bundle to use. */ public interface BundleSuggestion { /** * Install the bundle represented by this suggestion via the given context * * @param framework The context of the framework where the bundle is to be install * @param app The AriesApplication being installed * @return the installed bundle * @throws BundleException */ public Bundle install(BundleFramework framework, AriesApplication app) throws BundleException; /** * Get the imports of the bundle * @return the imported packages */ public Set<Content> getImportPackage(); /** * Get the exports of the bundle * @return the packages to export */ public Set<Content> getExportPackage(); /** * @return the version of the bundle. */ public Version getVersion(); /** * This method can be queried to discover the cost of using this bundle * repository. If two repositories define the same bundle with the same version * then the cheaper one will be used. * * @return the cost of using this repository. */ public int getCost(); } /** * This method attempts to find a bundle in the repository that matches the * specified DeploymentContent specification. If none can be found then null must * be returned. * * @param content the content used to locate a bundle. * @return the bundle suggestion, or null. */ public BundleSuggestion suggestBundleToUse(DeploymentContent content); /** * This method can be queried to discover the cost of using this bundle * repository. If two repositories define the same bundle with the same version * then the cheaper one will be used. * * @return the cost of using this repository. */ public int getCost(); }
8,846
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/repository/RepositoryGenerator.java
/* * 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.management.spi.repository; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.modelling.ModelledResource; public interface RepositoryGenerator { /** * Generate repository and store the content in the output stream. * @param repositoryName The repository name * @param byValueBundles By value bundles * @param os output stream * @throws ResolverException * @throws IOException */ void generateRepository(String repositoryName, Collection<? extends ModelledResource> byValueBundles, OutputStream os) throws ResolverException, IOException; /** * Generate a repository xml for the list of url and store the content in the output stream * @param source the list of url to the bundle archive, for file: protocol, it can be simplified by using relative path or absolute path(e.g. \temp\aa.jar or ..\temp\jars\aa.jar) * @param fout the output stream containing the repository xml * @throws IOException */ void generateRepository(String[] source, OutputStream fout) throws IOException; }
8,847
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/repository/PlatformRepository.java
/* * 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.management.spi.repository; import java.net.URI; import java.util.Collection; /** * This interface allows one to find out information about configured bundle repositories * */ public interface PlatformRepository { /** * Obtain a set of URIs to bundle repositories representing the local platform's capabilities. * These repositories do not represent any bundles but only platform capabilities. * @return URLs to bundle repositories representing the local platform */ Collection<URI> getPlatformRepositoryURLs(); }
8,848
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/update/UpdateStrategy.java
/* * 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.aries.application.management.spi.update; import java.util.Collection; import java.util.Map; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.UpdateException; import org.apache.aries.application.management.spi.framework.BundleFramework; import org.apache.aries.application.management.spi.repository.BundleRepository; import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; /** * Plug point for update implementation */ public interface UpdateStrategy { /** * Are the two deployments subject to update or do they require full reinstall */ public boolean allowsUpdate(DeploymentMetadata newMetadata, DeploymentMetadata oldMetadata); /** * Update an application */ public void update(UpdateInfo paramUpdateInfo) throws UpdateException; /** * Representation for an update request */ public static interface UpdateInfo { /** * Find {@link BundleSuggestion} objects for new bundle requests */ public Map<DeploymentContent, BundleRepository.BundleSuggestion> suggestBundle(Collection<DeploymentContent> bundles) throws BundleException; /** * Register a new bundle with the application (i.e. a new bundle was installed) */ public void register(Bundle bundle); /** * Unregister a bundle from the application (i.e. the bundle was uninstalled) */ public void unregister(Bundle bundle); /** * Get a {@link BundleFramework} object for the shared framework */ public BundleFramework getSharedFramework(); /** * Get a {@link BundleFramework} object for the isolated framework corresponding * to the application to be updated */ public BundleFramework getAppFramework(); /** * Get the {@link DeploymentMetadata} that is currently active and to be phased out */ public DeploymentMetadata getOldMetadata(); /** * Get the {@link DeploymentMetadata} that is to be activated */ public DeploymentMetadata getNewMetadata(); /** * Get the {@link AriesApplication} object being updated */ public AriesApplication getApplication(); /** * Whether to start any newly installed bundles */ public boolean startBundles(); } }
8,849
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/resolve/DeploymentManifestManager.java
/* * 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.management.spi.resolve; import java.util.Collection; import java.util.jar.Manifest; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.Content; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.ResolveConstraint; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.repository.PlatformRepository; import org.apache.aries.application.modelling.DeployedBundles; import org.apache.aries.application.modelling.ModelledResource; public interface DeploymentManifestManager { /** * Generate the deployment manifest map for the application. The method is designed to be used when installing an application. * @param app The Aries application * @param constraints the constraints, used to narrow down the deployment content * @return the deployment manifest * @throws ResolverException */ Manifest generateDeploymentManifest( AriesApplication app, ResolveConstraint... constraints ) throws ResolverException; /** * Generate the deployment manifest map. The method can be used for some advanced scenarios. * @param appMetadata The Aries application metadata * @param byValueBundles By value bundles * @param otherBundles Other bundles to be used to narrow the resolved bundles * @return DeployedBundles model of the deployed application * @throws ResolverException */ DeployedBundles generateDeployedBundles( ApplicationMetadata appMetadata, Collection<ModelledResource> byValueBundles, Collection<Content> otherBundles) throws ResolverException; /** * Generate a Manifest representation of a DEPLOYMENT.MF, * suitable for example to writing to disk * @param appSymbolicName * @param appVersion * @param deployedBundles Such as obtained from generateDeployedBundles() * @return the deployment manifest * @throws ResolverException */ Manifest generateDeploymentManifest ( String appSymbolicName, String appVersion, DeployedBundles deployedBundles) throws ResolverException; }
8,850
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/resolve/PostResolveTransformer.java
/* * 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.management.spi.resolve; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.modelling.DeployedBundles; public interface PostResolveTransformer { /** * This method is to perform any post process after the resolver returns back a collection of bundles. It returns the updated manifest map. * @param appMetaData The application that was resolved * @param deployedBundles A collection of bundles required by this application. * @return Modified collection of bundles * @throws ResolverException */ DeployedBundles postResolveProcess(ApplicationMetadata appMetaData, DeployedBundles deployedBundles) throws ResolverException; }
8,851
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/resolve/PreResolveHook.java
/* * 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.management.spi.resolve; import java.util.Collection; import org.apache.aries.application.modelling.ModelledResource; /** * This interface allows a pre resolve hook to add customizats * into the OBR resolve operation. */ public interface PreResolveHook { /** * Depending on the environment it may be necessary to add * resources to the resolve operation which you do not wish * to provision. These may be resources that already exist * and are available, or are sourced in a different way. Any * resources returned by this method are resolved against, but * not placed in the deployment.mf. This may result in problems * if a fake resource is provided, but the capabilities are not * provided at runtime. * * @param resources A mutable collection of ModelledResources that can have * more elements added or removed. */ public void collectFakeResources(Collection<ModelledResource> resources); }
8,852
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/resolve/AriesApplicationResolver.java
/* * 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.management.spi.resolve; import java.util.Collection; import java.util.Set; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.Content; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.AriesApplicationManager; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.ResolveConstraint; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.modelling.ModelledResource; import org.osgi.framework.Version; /** * An {@code AriesApplicationResolver} is a service used by the {@link AriesApplicationManager} when one of the * {@code createApplication} methods are called. It is used to "deploy" the application. The "deploy" process * generates an Aries Deployment manifest * */ public interface AriesApplicationResolver { /** * Deprecated. Use the method resolve(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException; * Resolve an AriesApplication. The implementation of this method is expected to do the following: * * <ol> * <li>Extract from the {@link AriesApplication}'s the application's content. This is performed * using the {@link AriesApplication#getApplicationMetadata()} method following by calling * {@link ApplicationMetadata#getApplicationContents()}. * </li> * <li>Resolve the application content using any configured repositories for bundles, and the * bundles that are contained by value inside the application. These bundles can be obtained * by calling {@link AriesApplication#getBundleInfo()}. * </li> * </ol> * * The method returns the set of bundle info objects that should be used. * * @param app The application to resolve * @return The additional bundles required to ensure that the application resolves. This * set will not include those provided by value within the application. * @throws ResolverException if the application cannot be resolved. */ @Deprecated Set<BundleInfo> resolve (AriesApplication app, ResolveConstraint... constraints) throws ResolverException ; /** * Return the info for the requested bundle. This method is called when installing * an application to determine where the bundle is located in order to install it. * * <p>If no matching bundle exists in the resolver runtime then null is returned.</p> * * @param bundleSymbolicName the bundle symbolic name. * @param bundleVersion the version of the bundle * @return the BundleInfo for the requested bundle, or null if none could be found. */ BundleInfo getBundleInfo(String bundleSymbolicName, Version bundleVersion); /** * Resolve an AriesApplication. The resolving process will build a repository from by-value bundles. * It then scans all the required bundles and pull the dependencies required to resolve the bundles. * * * Return a collect of modelled resources. This method is called when installing an application * @param appName Application name * @param appVersion application version * @param byValueBundles by value bundles * @param inputs bundle requirement * @return a collection of modelled resource required by this application. * @throws ResolverException */ Collection<ModelledResource> resolve(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException; /** * Resolve an AriesApplication in isolation i.e. without consulting any bundle repositories other than the system repository. This can be used for checking that the application is completely self-contained. * * Return a collect of modelled resources. This method is called when installing an application * @param appName Application name * @param appVersion application version * @param byValueBundles by value bundles * @param inputs bundle requirement * @return a collection of modelled resource required by this application. * @throws ResolverException */ Collection<ModelledResource> resolveInIsolation(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException; }
8,853
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/framework/BundleFrameworkConfigurationFactory.java
/* * 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.management.spi.framework; import org.apache.aries.application.management.AriesApplication; import org.osgi.framework.BundleContext; public interface BundleFrameworkConfigurationFactory { /** * Create a BundleFrameworkConfiguration with basic config * @param parentCtx * @return the framework config */ public BundleFrameworkConfiguration createBundleFrameworkConfig(String frameworkId, BundleContext parentCtx); /** * Create a BundleFrameworkConiguration for an application framework based * on a given AriesApplication. * @param parentCtx * @param app * @return the framework config */ public BundleFrameworkConfiguration createBundleFrameworkConfig(String frameworkId, BundleContext parentCtx, AriesApplication app); }
8,854
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/framework/BundleFrameworkConfiguration.java
/* * 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.management.spi.framework; import java.util.Properties; public interface BundleFrameworkConfiguration { public String getFrameworkID(); public Properties getFrameworkProperties(); public Properties getFrameworkManifest(); }
8,855
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/framework/BundleFrameworkFactory.java
/* * 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.management.spi.framework; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; public interface BundleFrameworkFactory { /** * Creates a new isolated bundle framework with the properties provided. * @param bc The context in which to install the new framework * @param config The BundleFrameworkConfiguration object used to configure the returned framework * @return the bundle framework * @throws BundleException */ public BundleFramework createBundleFramework(BundleContext bc, BundleFrameworkConfiguration config) throws BundleException; }
8,856
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/framework/BundleFramework.java
/* * 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.management.spi.framework; import java.util.List; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; public interface BundleFramework { public static final String SHARED_BUNDLE_FRAMEWORK = "shared.bundle.framework"; /** * Initialises the framework (but does not start the framework bundle) * @throws BundleException */ public void init() throws BundleException; /** * Starts the framework and the framework bundle * @throws BundleException */ public void start() throws BundleException; /** * Closes the framework and any associated resource * @throws BundleException */ public void close() throws BundleException; /** * Installs a bundle to this framework. * @param suggestion The information required to install the bundle * @param app The application with which this install is associated * @return the bundle that was installed * @throws BundleException */ public Bundle install(BundleSuggestion suggestion, AriesApplication app) throws BundleException; /** * Removes a bundle from this framework * @param b The bundle to remove * @throws BundleException */ public void uninstall(Bundle b) throws BundleException; /** * Start a previously installed bundle in this framework. * @param b the bundle to start * @throws BundleException */ public void start(Bundle b) throws BundleException; /** * Stop a previously installed bundle in this framework. * @param b the bundle to stop * @throws BundleException */ public void stop(Bundle b) throws BundleException; /** * Returns the bundle context for the framework. * @return a bundle context representing the framework */ public BundleContext getIsolatedBundleContext(); /** * Returns the OSGi bundle representing the framework * @return a bundle representing the framework */ public Bundle getFrameworkBundle(); /** * Returns a list of bundles currently installed in this framework * @return the bundles in the framework. */ public List<Bundle> getBundles(); }
8,857
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/framework/BundleFrameworkManager.java
/* * 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.management.spi.framework; import java.util.Collection; import java.util.Map; import java.util.Set; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.UpdateException; import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion; public interface BundleFrameworkManager { /** * All additions/removals of frameworks and bundles from the shared bundle framework are * performed under this object lock. Users bypassing this api and performing operations on * the underlying OSGi frameworks should be sure to hold this lock. */ Object SHARED_FRAMEWORK_LOCK = new Object(); /** * Gets the BundleFramework object associated with the given bundle * @param frameworkBundle - The bundle representing the bundle framework * @return the bundle framework */ public BundleFramework getBundleFramework(Bundle frameworkBundle); /** * Gets a reference to the single shared bundle framework. The Shared Bundle * Framework contains bundle shared between applications * @return the shared bundle framework */ public BundleFramework getSharedBundleFramework(); /** * Creates a new framework inside the shared bundle framework and installs a * collection of bundles into the framework. * @param bundlesToInstall The collection of bundles to be installed * @param app The application associated with this install * @return the bundle of the framework * @throws BundleException */ public Bundle installIsolatedBundles( Collection<BundleSuggestion> bundlesToInstall, AriesApplication app) throws BundleException; /** * Installs a collection of shared bundles to the shared bundle framework * @param bundlesToInstall * @param app * @return the collection of installed bundles. * @throws BundleException */ public Collection<Bundle> installSharedBundles( Collection<BundleSuggestion> bundlesToInstall, AriesApplication app) throws BundleException; public boolean allowsUpdate(DeploymentMetadata newMetadata, DeploymentMetadata oldMetadata); public interface BundleLocator { public Map<DeploymentContent, BundleSuggestion> suggestBundle(Collection<DeploymentContent> bundles) throws BundleException; } public void updateBundles( DeploymentMetadata newMetadata, DeploymentMetadata oldMetadata, AriesApplication app, BundleLocator locator, Set<Bundle> bundles, boolean startBundles) throws UpdateException; /** * Starts a previously installed bundle * @param b * @throws BundleException */ public void startBundle(Bundle b) throws BundleException; /** * Stops a previously installed bundle * @param b * @throws BundleException */ public void stopBundle(Bundle b) throws BundleException; /** * Removes a bundle from the runtime * @param b * @throws BundleException */ public void uninstallBundle(Bundle b) throws BundleException; }
8,858
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/runtime/LocalPlatform.java
/* * 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.management.spi.runtime; import java.io.File; import java.io.IOException; /** * This is a difficult interface to name properly. It holds methods that need to * be implemented on a per-application server platform basis. */ public interface LocalPlatform { /** * Obtain a temporary directory * @return Temporary directory * @throws IOException */ public File getTemporaryDirectory() throws IOException; /** * Obtain a temporary file * @return Temporary directory * @throws IOException */ public File getTemporaryFile() throws IOException; }
8,859
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/runtime/AriesApplicationContextManager.java
/* * 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.management.spi.runtime; import java.util.Set; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.AriesApplicationContext; import org.apache.aries.application.management.ManagementException; import org.apache.aries.application.management.UpdateException; import org.osgi.framework.BundleException; /** * An ApplicationContextManager is responsible for managing Aries applications in the * server's OSGi runtime. We expect that many projects consuming this code will provide * their own implementation of this service. */ public interface AriesApplicationContextManager { /** * Obtain an ApplicationContext for an AriesApplication. Applications are stopped and * started via an ApplicationContext. * @param app The applicaton for which to obtain an ApplicationContext. * @return AriesApplicationContext * @throws BundleException * @throws ManagementException */ public AriesApplicationContext getApplicationContext(AriesApplication app) throws BundleException, ManagementException; /** * @return The set of all AriesApplicationContexts. */ public Set<AriesApplicationContext> getApplicationContexts(); /** * Update the AriesApplication and return an updated application context. * @throws UpdateException if the update failed * @throws IllegalArgumentException if the app is not currently installed */ public AriesApplicationContext update(AriesApplication app, DeploymentMetadata oldMetadata) throws UpdateException; /** * Remove the provided AriesApplicationContext from the running system. * * @param app the application to remove. */ public void remove(AriesApplicationContext app) throws BundleException; }
8,860
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/convert/ConversionException.java
/* * 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.management.spi.convert; /** * An Exception thrown by a BundleConverter */ public class ConversionException extends Exception { private static final long serialVersionUID = -5921912484821992252L; public ConversionException (Exception e) { super(e); } public ConversionException (String s) { super(s); } }
8,861
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/convert/BundleConverter.java
/* * 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.management.spi.convert; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; /** * A BundleConverter turns a .jar that is not an OSGi bundle into a well formed OSGi bundle, * or a .war that is not a WAB into a WAB. The first converter to return a non-null result is * taken as having fully converted the bundle. */ public interface BundleConverter { /** * @param parentEba The root of the eba containing the artifact being converted - * a zip format file with .eba suffix, or an exploded directory. * @param fileInEba The object within the eba to convert * @throws ConversionException if conversion was attempted but failed * @return valid input stream or null if this converter does not support conversion of * this artifact type. */ public BundleConversion convert (IDirectory parentEba, IFile fileInEba) throws ConversionException; }
8,862
0
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi
Create_ds/aries/application/application-api/src/main/java/org/apache/aries/application/management/spi/convert/BundleConversion.java
/* * 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.management.spi.convert; import java.io.IOException; import java.io.InputStream; import org.apache.aries.application.management.BundleInfo; /** * A BundleConversion represents a .JAR file which has been converted in to * an well-formed OSGi bundle, or a .WAR file which has been converted into a .WAB * file */ public interface BundleConversion { /** * @return The InputStream to the converted bundle. */ public InputStream getInputStream() throws IOException; /** * @return The bundle information for the converted bundle. */ public BundleInfo getBundleInfo() throws IOException; }
8,863
0
Create_ds/aries/application/application-noop-resolver/src/main/java/org/apache/aries/application/resolver/noop
Create_ds/aries/application/application-noop-resolver/src/main/java/org/apache/aries/application/resolver/noop/impl/NoOpResolver.java
/* * 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.resolver.noop.impl; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.aries.application.Content; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.ResolveConstraint; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.resolve.AriesApplicationResolver; import org.apache.aries.application.modelling.ModelledResource; import org.osgi.framework.Version; /** * AriesApplicationManager requires that there be at least one * AriesApplicationResolver service present. This class provides a null * implementation: it simply returns the bundles that it was provided with - * enough to permit the testing of Aries applications that have no external * dependencies. It is not intended to be used in a production environment, as * the implementation of the AriesApplicationResolver just returns the bundles * included in the application irrespective of what is specified in * application.mf. */ public class NoOpResolver implements AriesApplicationResolver { Set<BundleInfo> resolvedBundles = new HashSet<BundleInfo>(); public Set<BundleInfo> resolve(AriesApplication app, ResolveConstraint... constraints) { resolvedBundles.addAll(app.getBundleInfo()); return app.getBundleInfo(); } public BundleInfo getBundleInfo(String bundleSymbolicName, Version bundleVersion) { BundleInfo result = null; for (BundleInfo info : resolvedBundles) { if (info.getSymbolicName().equals(bundleSymbolicName) && info.getVersion().equals(bundleVersion)) { result = info; } } return result; } public Collection<ModelledResource> resolve(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException { return byValueBundles; } @Override public Collection<ModelledResource> resolveInIsolation(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException { return byValueBundles; } }
8,864
0
Create_ds/aries/application/application-deployment-management/src/test/java/org/apache/aries/application/deployment
Create_ds/aries/application/application-deployment-management/src/test/java/org/apache/aries/application/deployment/management/DeploymentGeneratorTest.java
/* * 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.deployment.management; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.Content; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.deployment.management.impl.DeploymentManifestManagerImpl; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.ResolveConstraint; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.resolve.AriesApplicationResolver; import org.apache.aries.application.management.spi.resolve.PreResolveHook; import org.apache.aries.application.management.spi.runtime.LocalPlatform; import org.apache.aries.application.modelling.DeployedBundles; import org.apache.aries.application.modelling.ExportedPackage; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ModellingManager; import org.apache.aries.application.modelling.impl.ModellingManagerImpl; import org.apache.aries.application.modelling.utils.ModellingHelper; import org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.application.utils.manifest.ContentFactory; import org.apache.aries.mocks.BundleContextMock; import org.apache.aries.unittest.mocks.MethodCall; import org.apache.aries.unittest.mocks.Skeleton; import org.apache.aries.util.VersionRange; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Version; /** * Tests to ensure we generate DEPLOYMENT.MF artifacts correctly. */ public class DeploymentGeneratorTest { private DeploymentManifestManagerImpl deplMFMgr; private AriesApplication app; private ApplicationMetadata appMetadata; private static class MockResolver implements AriesApplicationResolver { boolean returnAppContentNextTime = true; @Override public Collection<ModelledResource> resolve(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException { if (_nextResults != null && !_nextResults.isEmpty()) { Collection<ModelledResource> result = _nextResults.remove(0); return result; } Collection<ModelledResource> res = new ArrayList<ModelledResource>(); if (returnAppContentNextTime) { res.add(CAPABILITY_A.getBundle()); res.add(CAPABILITY_B.getBundle()); } res.add(CAPABILITY_C.getBundle()); res.add(CAPABILITY_E.getBundle()); boolean addD = false; for(Content ib : inputs) { if(ib.getContentName().equals("aries.test.d")) addD = true; } if(addD) { try { res.add(createModelledResource("aries.test.d", "1.0.0", new ArrayList<String>(), new ArrayList<String>())); } catch (InvalidAttributeException e) { fail("Cannot resolve import for d"); } } // deployment manifest manager calls resolve() an extra time, providing // just the shared bundles. // If we added D, then the next resolve will be one trying to winnow D out: // AppContent should be returned in that one. We should not return app content // next time if we did so last time, unless we just added D returnAppContentNextTime = !returnAppContentNextTime || addD; return res; } List<Collection<ModelledResource>> _nextResults = null; // Some tests want to override the default behaviour of the resolve() method public void addResult (Collection<ModelledResource> result) { if (_nextResults == null) { _nextResults = new ArrayList<Collection<ModelledResource>>(); } _nextResults.add(result); } public BundleInfo getBundleInfo(String bundleSymbolicName, Version bundleVersion) { return null; } public Set<BundleInfo> resolve(AriesApplication app, ResolveConstraint... constraints) throws ResolverException { return null; } @Override public Collection<ModelledResource> resolveInIsolation(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException { // TODO Auto-generated method stub return null; } } static MockResolver _resolver = new MockResolver(); static class DummyLocalPlatform implements LocalPlatform { public File getTemporaryDirectory() throws IOException { File f = File.createTempFile("ebaTmp", null); f.delete(); f.mkdir(); return f; } public File getTemporaryFile () throws IOException { // Not used return File.createTempFile("ebaTmp", null); } } static LocalPlatform localPlatform = new DummyLocalPlatform(); static ModellingManager modellingManager = new ModellingManagerImpl(); static ModellingHelper modellingHelper = new ModellingHelperImpl(); @BeforeClass public static void classSetup() throws Exception { BundleContext bc = Skeleton.newMock(BundleContext.class); bc.registerService(AriesApplicationResolver.class.getName(), _resolver, new Hashtable<String, String>()); bc.registerService(ModellingManager.class.getName(), modellingManager, new Hashtable<String, String>()); bc.registerService(ModellingHelper.class.getName(), modellingHelper, new Hashtable<String, String>()); } @AfterClass public static void afterClass() throws Exception { BundleContextMock.clear(); } @Before public void setup() throws Exception { appMetadata = Skeleton.newMock(ApplicationMetadata.class); Skeleton.getSkeleton(appMetadata).setReturnValue( new MethodCall(ApplicationMetadata.class, "getApplicationSymbolicName"), "aries.test"); Skeleton.getSkeleton(appMetadata).setReturnValue( new MethodCall(ApplicationMetadata.class, "getApplicationVersion"), new Version("1.0.0")); Skeleton.getSkeleton(appMetadata).setReturnValue( new MethodCall(ApplicationMetadata.class, "getUseBundles"), Collections.EMPTY_LIST); app = Skeleton.newMock(AriesApplication.class); Skeleton.getSkeleton(app).setReturnValue(new MethodCall(AriesApplication.class, "getApplicationMetadata"), appMetadata); deplMFMgr = new DeploymentManifestManagerImpl(); deplMFMgr.setResolver(_resolver); deplMFMgr.setLocalPlatform(localPlatform); deplMFMgr.setModellingManager(modellingManager); deplMFMgr.setModellingHelper(modellingHelper); deplMFMgr.setPreResolveHooks(new ArrayList<PreResolveHook>()); } private static ExportedPackage CAPABILITY_A; private static ExportedPackage CAPABILITY_B; private static ExportedPackage CAPABILITY_C; private static ExportedPackage CAPABILITY_E; // use bundle private static Content BUNDLE_C; private static Content BUNDLE_D; public static ExportedPackage createExportedPackage (String bundleName, String bundleVersion, String[] exportedPackages, String[] importedPackages ) throws InvalidAttributeException { ModelledResource mb = createModelledResource(bundleName, bundleVersion, Arrays.asList(importedPackages) , Arrays.asList(exportedPackages)); return mb.getExportedPackages().iterator().next(); } static { try { CAPABILITY_A = createExportedPackage ("aries.test.a", "1.0.0", new String[] {"aries.test.a"}, new String[] {"aries.test.c"}); CAPABILITY_B = createExportedPackage("aries.test.b", "1.1.0", new String[] {"aries.test.b"}, new String[] {"aries.test.e"}); BUNDLE_C = ContentFactory.parseContent("aries.test.c","[1.0.0,1.1.0)"); CAPABILITY_C = createExportedPackage("aries.test.c", "1.0.5", new String[] {"aries.test.c"}, new String[] {}); BUNDLE_D = ContentFactory.parseContent("aries.test.d","1.0.0"); // = new ImportedBundleImpl("aries.test.e", "1.0.0"); CAPABILITY_E = createExportedPackage("aries.test.e", "1.0.0", new String[] {"aries.test.e"}, new String[] {}); } catch (InvalidAttributeException iae) { throw new RuntimeException(iae); } } @Test public void testResolve() throws Exception { Skeleton.getSkeleton(appMetadata).setReturnValue(new MethodCall(ApplicationMetadata.class, "getApplicationContents"), Arrays.asList(mockContent("aries.test.a", "1.0.0"), mockContent("aries.test.b", "[1.0.0, 2.0.0)" ))); Skeleton.getSkeleton(appMetadata).setReturnValue(new MethodCall(ApplicationMetadata.class, "getUseBundles"), Arrays.asList(BUNDLE_C, BUNDLE_D)); DeployedBundles deployedBundles = deplMFMgr.generateDeployedBundles (appMetadata, new ArrayList<ModelledResource>(), Collections.<Content>emptyList()); Manifest man = deplMFMgr.generateDeploymentManifest(appMetadata.getApplicationSymbolicName(), appMetadata.getApplicationVersion().toString(), deployedBundles); Attributes attrs = man.getMainAttributes(); assertEquals("aries.test", attrs.getValue(AppConstants.APPLICATION_SYMBOLIC_NAME)); assertEquals("1.0.0", attrs.getValue(AppConstants.APPLICATION_VERSION)); String content = attrs.getValue(AppConstants.DEPLOYMENT_CONTENT); String useBundle = attrs.getValue(AppConstants.DEPLOYMENT_USE_BUNDLE); String provisioned =attrs.getValue(AppConstants.DEPLOYMENT_PROVISION_BUNDLE); assertTrue(content.contains("aries.test.a;deployed-version=1.0.0")); assertTrue(content.contains("aries.test.b;deployed-version=1.1.0")); assertTrue(useBundle.contains("aries.test.c;deployed-version=1.0.5")); assertFalse(useBundle.contains("aries.test.d")); assertTrue(provisioned.contains("aries.test.e;deployed-version=1.0.0")); } @Test public void checkBasicCircularDependenciesDetected() throws Exception { // Override Resolver behaviour. //ImportedBundle isolated = new ImportedBundleImpl ("test.isolated" , "1.0.0"); // When we resolve isolated, we're going to get another bundle which has a dependency on isolated. Collection<ModelledResource> cmr = new ArrayList<ModelledResource>(); ExportedPackage testIsolatedPkg = createExportedPackage ("test.isolated", "1.0.0", new String[] {"test.shared"}, new String[] {"test.isolated.pkg"}); cmr.add (testIsolatedPkg.getBundle()); ExportedPackage testSharedPkg = createExportedPackage ("test.shared", "1.0.0", new String[] {"test.isolated.pkg"}, new String[] {"test.shared"}); cmr.add (testSharedPkg.getBundle()); _resolver.addResult(cmr); // The second time DeploymentGenerator calls the Resolver, it will provide just // test.shared. The resolver will return test.shared _plus_ test.isolated. _resolver.addResult(cmr); Skeleton.getSkeleton(appMetadata).setReturnValue(new MethodCall(ApplicationMetadata.class, "getApplicationContents"), Arrays.asList(mockContent("test.isolated" , "1.0.0"))); try { DeployedBundles deployedBundles = deplMFMgr.generateDeployedBundles (appMetadata, new ArrayList<ModelledResource>(), new ArrayList<Content>()); deplMFMgr.generateDeploymentManifest(appMetadata.getApplicationSymbolicName(), appMetadata.getApplicationVersion().toString(), deployedBundles); } catch (ResolverException rx) { List<String> usr = rx.getUnsatisfiedRequirements(); assertEquals ("One unsatisfied requirement expected, not " + usr.size(), usr.size(), 1); String chkMsg = "Shared bundle test.shared_1.0.0 has a dependency for package " + "test.shared which is exported from application bundle [test.isolated_1.0.0]"; assertTrue (chkMsg + " expected, not " + usr, usr.contains(chkMsg)); return; } fail ("ResolverException expected"); } /** * This method checks that the a more complicated circular dependency issues the correct error message * and checks that the details listed in the exception are correct. * @throws Exception */ @Test public void checkMultipleCircularDependenciesDetected() throws Exception { Collection<ModelledResource> cmr = new ArrayList<ModelledResource>(); ExportedPackage testIsolated1 = createExportedPackage ("test.isolated1", "1.0.0", new String[] {"test.isolated1","test.isolated2"}, new String[] {"test.shared1", "test.shared2"}); cmr.add (testIsolated1.getBundle()); ExportedPackage testIsolated2 = createExportedPackage ("test.isolated2", "1.0.0", new String[] {"test.isolated1","test.isolated2"}, new String[] {"test.shared1", "test.shared2"}); cmr.add (testIsolated2.getBundle()); ExportedPackage testShared1 = createExportedPackage ("test.shared1", "1.0.0", new String[] {"test.shared1", "test.shared2"}, new String[] {"test.isolated1","test.isolated2"}); cmr.add (testShared1.getBundle()); ExportedPackage testShared2 = createExportedPackage ("test.shared2", "1.0.0", new String[] {"test.shared1", "test.shared2"}, new String[] {"test.isolated1","test.isolated2"}); cmr.add (testShared2.getBundle()); _resolver.addResult(cmr); // The second time DeploymentGenerator calls the Resolver, it will provide just // test.shared. The resolver will return test.shared _plus_ test.isolated. _resolver.addResult(cmr); Skeleton.getSkeleton(appMetadata).setReturnValue(new MethodCall(ApplicationMetadata.class, "getApplicationContents"), Arrays.asList(mockContent("test.isolated1" , "1.0.0"), mockContent("test.isolated2" , "1.0.0"))); app = Skeleton.newMock(AriesApplication.class); Skeleton.getSkeleton(app).setReturnValue(new MethodCall(AriesApplication.class, "getApplicationMetadata"), appMetadata); try { DeployedBundles deployedBundles = deplMFMgr.generateDeployedBundles (appMetadata, Arrays.asList(new ModelledResource[] {testIsolated1.getBundle(), testIsolated2.getBundle()}), new ArrayList<Content>()); deplMFMgr.generateDeploymentManifest(appMetadata.getApplicationSymbolicName(), appMetadata.getApplicationVersion().toString(), deployedBundles); } catch (ResolverException rx) { // Get the unsatisfied Requirements List<String> unsatisfiedReqs = rx.getUnsatisfiedRequirements(); // Ensure we've got 4 unsatisfied Requirements assertEquals ("4 unsatisfied requirements expected, but got " + Arrays.toString(unsatisfiedReqs.toArray()), 4, unsatisfiedReqs.size()); List<String> checkMessages = new ArrayList<String>(); // Now load an array with the expected messages. checkMessages.add("Shared bundle test.shared1_1.0.0 has a dependency for package test.isolated1 which " + "is exported from application bundles [test.isolated1_1.0.0, test.isolated2_1.0.0]"); checkMessages.add("Shared bundle test.shared1_1.0.0 has a dependency for package test.isolated2 which " + "is exported from application bundles [test.isolated1_1.0.0, test.isolated2_1.0.0]"); checkMessages.add("Shared bundle test.shared2_1.0.0 has a dependency for package test.isolated1 which " + "is exported from application bundles [test.isolated1_1.0.0, test.isolated2_1.0.0]"); checkMessages.add("Shared bundle test.shared2_1.0.0 has a dependency for package test.isolated2 which " + "is exported from application bundles [test.isolated1_1.0.0, test.isolated2_1.0.0]"); // Loop through the unsatisfied Requirements and compare them to the expected msgs. We trim the strings // because some unsatisfied reqs have spaces at the end of the string. for (String unsatisfiedReq : unsatisfiedReqs) { assertTrue(unsatisfiedReq + " is not an expected msg", checkMessages.contains(unsatisfiedReq.trim())); } } } @Test public void checkBundleInAppContentAndProvisionContent() throws Exception { List<ModelledResource> cmr = new ArrayList<ModelledResource>(); cmr.add(createModelledResource("test.api", "1.1.0", Collections.<String>emptyList(), Arrays.asList("test.api.pack;version=1.1.0"))); cmr.add(createModelledResource("test.api", "1.0.0", Collections.<String>emptyList(), Arrays.asList("test.api.pack;version=1.0.0"))); cmr.add(createModelledResource("test.consumer", "1.0.0", Arrays.asList("test.api.pack;version=\"[1.0.0,2.0.0)\""), Collections.<String>emptyList())); cmr.add(createModelledResource("test.provider", "1.0.0", Arrays.asList("test.api.pack;version=\"[1.0.0,1.1.0)\""), Collections.<String>emptyList())); // The second time DeploymentGenerator calls the Resolver, it will provide just // test.shared. The resolver will return test.shared _plus_ test.isolated. _resolver.addResult(cmr); Skeleton.getSkeleton(appMetadata).setReturnValue( new MethodCall(ApplicationMetadata.class, "getApplicationContents"), Arrays.asList( mockContent("test.api" , "1.1.0"), mockContent("test.consumer" , "1.0.0"), mockContent("test.provider", "1.0.0"))); app = Skeleton.newMock(AriesApplication.class); Skeleton.getSkeleton(app).setReturnValue(new MethodCall(AriesApplication.class, "getApplicationMetadata"), appMetadata); try { DeployedBundles deployedBundles = deplMFMgr.generateDeployedBundles (appMetadata, Arrays.asList(new ModelledResource[] {cmr.get(0), cmr.get(2), cmr.get(3)}), new ArrayList<Content>()); deplMFMgr.generateDeploymentManifest(appMetadata.getApplicationSymbolicName(), appMetadata.getApplicationVersion().toString(), deployedBundles); fail("Expected exception because we can't provision an isolated bundle twice"); } catch (ResolverException rx) {} } /** * Similar to the checkBundleInAppContentAndProvisionContent scenario. However, this time the provisioned bundle does not provide * a package or service to the isolated content, so there is no problem. * @throws Exception */ @Test public void checkBundleInAppContentAndProvisionContentButNothingSharedToIsolatedContent() throws Exception { List<ModelledResource> cmr = new ArrayList<ModelledResource>(); cmr.add(createModelledResource("test.util", "1.1.0", Collections.<String>emptyList(), Arrays.asList("test.api.pack;version=1.1.0"))); cmr.add(createModelledResource("test.bundle", "1.0.0", Arrays.asList("test.api.pack;version=\"[1.1.0,2.0.0)\""), Collections.<String>emptyList())); cmr.add(createModelledResource("test.provisioned", "1.0.0", Arrays.asList("test.api.pack;version=\"[1.0.0,1.1.0)\""), Collections.<String>emptyList())); cmr.add(createModelledResource("test.util", "1.0.0", Collections.<String>emptyList(), Arrays.asList("test.api.pack;version=1.0.0"))); // The second time DeploymentGenerator calls the Resolver, it will provide just // test.shared. The resolver will return test.shared _plus_ test.isolated. _resolver.addResult(cmr); Skeleton.getSkeleton(appMetadata).setReturnValue( new MethodCall(ApplicationMetadata.class, "getApplicationContents"), Arrays.asList( mockContent("test.util" , "1.1.0"), mockContent("test.bundle", "1.0.0"))); app = Skeleton.newMock(AriesApplication.class); Skeleton.getSkeleton(app).setReturnValue(new MethodCall(AriesApplication.class, "getApplicationMetadata"), appMetadata); DeployedBundles deployedBundles = deplMFMgr.generateDeployedBundles (appMetadata, Arrays.asList(new ModelledResource[] {cmr.get(0), cmr.get(1)}), new ArrayList<Content>()); Manifest mf = deplMFMgr.generateDeploymentManifest(appMetadata.getApplicationSymbolicName(), appMetadata.getApplicationVersion().toString(), deployedBundles); assertTrue(mf.getMainAttributes().getValue("Deployed-Content").contains("test.util;deployed-version=1.1.0")); assertTrue(mf.getMainAttributes().getValue("Provision-Bundle").contains("test.util;deployed-version=1.0.0")); } @Test public void checkBundleInAppContentAndUseContent() throws Exception { List<ModelledResource> cmr = new ArrayList<ModelledResource>(); cmr.add(createModelledResource("test.api", "1.1.0", Collections.<String>emptyList(), Arrays.asList("test.api.pack;version=1.1.0"))); cmr.add(createModelledResource("test.api", "1.0.0", Collections.<String>emptyList(), Arrays.asList("test.api.pack;version=1.0.0"))); cmr.add(createModelledResource("test.consumer", "1.0.0", Arrays.asList("test.api.pack;version=\"[1.0.0,2.0.0)\""), Collections.<String>emptyList())); cmr.add(createModelledResource("test.provider", "1.0.0", Arrays.asList("test.api.pack;version=\"[1.0.0,1.1.0)\""), Collections.<String>emptyList())); // The second time DeploymentGenerator calls the Resolver, it will provide just // test.shared. The resolver will return test.shared _plus_ test.isolated. _resolver.addResult(cmr); Skeleton.getSkeleton(appMetadata).setReturnValue( new MethodCall(ApplicationMetadata.class, "getApplicationContents"), Arrays.asList( mockContent("test.api" , "1.1.0"), mockContent("test.consumer" , "1.0.0"), mockContent("test.provider", "1.0.0"))); Skeleton.getSkeleton(appMetadata).setReturnValue( new MethodCall(ApplicationMetadata.class, "getUseBundles"), Arrays.asList(mockContent("test.api", "1.0.0"))); app = Skeleton.newMock(AriesApplication.class); Skeleton.getSkeleton(app).setReturnValue(new MethodCall(AriesApplication.class, "getApplicationMetadata"), appMetadata); DeployedBundles deployedBundles = deplMFMgr.generateDeployedBundles (appMetadata, Arrays.asList(new ModelledResource[] {cmr.get(0), cmr.get(2), cmr.get(3)}), new ArrayList<Content>()); Manifest mf = deplMFMgr.generateDeploymentManifest(appMetadata.getApplicationSymbolicName(), appMetadata.getApplicationVersion().toString(), deployedBundles); mf.write(System.out); assertTrue(mf.getMainAttributes().getValue("Deployed-Content").contains("test.api;deployed-version=1.1.0")); assertTrue(mf.getMainAttributes().getValue("Deployed-Use-Bundle").contains("test.api;deployed-version=1.0.0")); } public static ModelledResource createModelledResource(String bundleName, String bundleVersion, Collection<String> importedPackages, Collection<String> exportedPackages) throws InvalidAttributeException { Attributes att = new Attributes(); att.put(new Attributes.Name(Constants.BUNDLE_SYMBOLICNAME), bundleName); att.put(new Attributes.Name(Constants.BUNDLE_VERSION), bundleVersion); att.put(new Attributes.Name(Constants.BUNDLE_MANIFESTVERSION), "2"); StringBuilder builder = new StringBuilder(); for(String iPackage : importedPackages) { builder.append(iPackage).append(","); } if(builder.length() > 0) { builder.deleteCharAt(builder.length() - 1); att.put(new Attributes.Name(Constants.IMPORT_PACKAGE), builder.toString()); } builder = new StringBuilder(); for(String ePackage : exportedPackages) { builder.append(ePackage).append(","); } if(builder.length() > 0) { builder.deleteCharAt(builder.length() - 1); att.put(new Attributes.Name(Constants.EXPORT_PACKAGE), builder.toString()); } return new ModellingManagerImpl().getModelledResource(null, att, null, null); } private Content mockContent(String symbolicName, String version) { Content bundle = Skeleton.newMock(Content.class); VersionRange vr = new VersionRange(version); Skeleton.getSkeleton(bundle).setReturnValue(new MethodCall(Content.class, "getContentName"), symbolicName); Skeleton.getSkeleton(bundle).setReturnValue(new MethodCall(Content.class, "getVersion"), vr); return bundle; } }
8,865
0
Create_ds/aries/application/application-deployment-management/src/main/java/org/apache/aries/application/deployment/management
Create_ds/aries/application/application-deployment-management/src/main/java/org/apache/aries/application/deployment/management/impl/DefaultPostResolveTransformer.java
/* * 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.deployment.management.impl; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.resolve.PostResolveTransformer; import org.apache.aries.application.modelling.DeployedBundles; public class DefaultPostResolveTransformer implements PostResolveTransformer { @Override public DeployedBundles postResolveProcess(ApplicationMetadata appMetadata, DeployedBundles deployedBundles) throws ResolverException { return deployedBundles; } }
8,866
0
Create_ds/aries/application/application-deployment-management/src/main/java/org/apache/aries/application/deployment/management
Create_ds/aries/application/application-deployment-management/src/main/java/org/apache/aries/application/deployment/management/impl/MessageUtil.java
/* * 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.deployment.management.impl; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class MessageUtil { /** The resource bundle for blueprint messages */ private final static ResourceBundle messages = ResourceBundle.getBundle("org.apache.aries.application.deployment.management.messages.DeploymentManagementMessages"); private static class Message { public String msgKey; public Object[] inserts; public Exception cause; public Message(String msgKey, Exception cause, Object[] inserts) { this.msgKey = msgKey; this.cause = cause; this.inserts = inserts; } } private List<Message> errors = new ArrayList<Message>(); private List<Message> warnings = new ArrayList<Message>(); private final String fileName; public MessageUtil(String fileName) { this.fileName = fileName; } public String getFileName() { return fileName; } public void processMessages() { for (Message m : errors) { //Tr.error(tc, m.msgKey, m.inserts); // use logger } for (Message m : warnings) { //Tr.warning(tc, m.msgKey, m.inserts); // use logger } } public List<String> getErrors() { List<String> result = new ArrayList<String>(warnings.size()); for (Message m : warnings) { result.add(MessageFormat.format(messages.getString(m.msgKey), m.inserts)); } return result; } public List<String> getWarnings() { List<String> result = new ArrayList<String>(warnings.size()); for (Message m : warnings) { result.add(MessageFormat.format(messages.getString(m.msgKey), m.inserts)); } return result; } public void clear() { errors.clear(); warnings.clear(); } public boolean hasErrors() { return !!!errors.isEmpty(); } public void error(String msgKey, Object ... inserts) { errors.add(new Message(msgKey, null, inserts)); } public void error(String msgKey, Exception e, Object ... inserts) { errors.add(new Message(msgKey, e, inserts)); } public void warning(String msgKey, Object ... inserts) { warnings.add(new Message(msgKey, null, inserts)); } public void warning(String msgKey, Exception e, Object ... inserts) { warnings.add(new Message(msgKey, e, inserts)); } /** * 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; } }
8,867
0
Create_ds/aries/application/application-deployment-management/src/main/java/org/apache/aries/application/deployment/management
Create_ds/aries/application/application-deployment-management/src/main/java/org/apache/aries/application/deployment/management/impl/DeploymentManifestManagerImpl.java
/* * 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.deployment.management.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.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.Content; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.ServiceDeclaration; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.ResolveConstraint; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.resolve.AriesApplicationResolver; import org.apache.aries.application.management.spi.resolve.DeploymentManifestManager; import org.apache.aries.application.management.spi.resolve.PostResolveTransformer; import org.apache.aries.application.management.spi.resolve.PreResolveHook; import org.apache.aries.application.management.spi.runtime.LocalPlatform; import org.apache.aries.application.modelling.DeployedBundles; 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.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.utils.ModellingHelper; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.application.utils.manifest.ContentFactory; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.io.IOUtils; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.service.blueprint.container.ServiceUnavailableException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DeploymentManifestManagerImpl implements DeploymentManifestManager { private final Logger _logger = LoggerFactory.getLogger(DeploymentManifestManagerImpl.class); private AriesApplicationResolver resolver; private PostResolveTransformer postResolveTransformer = null; private ModelledResourceManager modelledResourceManager; private LocalPlatform localPlatform; private ModellingManager modellingManager; private ModellingHelper modellingHelper; private List<PreResolveHook> preResolveHooks; public void setModellingManager (ModellingManager m) { modellingManager = m; } public void setModellingHelper (ModellingHelper mh) { modellingHelper = mh; } public LocalPlatform getLocalPlatform() { return localPlatform; } public void setLocalPlatform(LocalPlatform localPlatform) { this.localPlatform = localPlatform; } public void setPreResolveHooks(List<PreResolveHook> hooks) { preResolveHooks = hooks; } public ModelledResourceManager getModelledResourceManager() { return modelledResourceManager; } public void setModelledResourceManager(ModelledResourceManager modelledResourceManager) { this.modelledResourceManager = modelledResourceManager; } public void setPostResolveTransformer(PostResolveTransformer transformer) { postResolveTransformer = transformer; } public void setResolver(AriesApplicationResolver resolver) { this.resolver = resolver; } /** * Perform provisioning to work out the 'freeze dried list' of the eba * @param app - Aries application * @param ResolveConstraint - resolver constraint for limiting the resolving results * @return manifest the generated deployment manifest * @throws ResolverException */ @Override public Manifest generateDeploymentManifest(AriesApplication app, ResolveConstraint... constraints ) throws ResolverException { _logger.debug(LOG_ENTRY, "generateDeploymentManifest", new Object[]{app, constraints}); ApplicationMetadata appMetadata = app.getApplicationMetadata(); Collection<ModelledResource> byValueBundles = null; try { // find out blueprint information byValueBundles = getByValueBundles(app); // find out by value bundles and then by reference bundles } catch (Exception e) { throw new ResolverException (e); } Collection<Content> bundlesToResolve = new ArrayList<Content>(); bundlesToResolve.addAll(appMetadata.getApplicationContents()); bundlesToResolve.addAll(app.getApplicationMetadata().getUseBundles()); //If we pass in provision bundles (e.g. import deployment manifest sanity check), we add them into our bundlesToResolve set. // This is because we want to make sure all bundles we passed into resolver the same as what we are going to get from resolver. List<Content> restrictedReqs = new ArrayList<Content>(); for (ResolveConstraint constraint : constraints ) { Content content = ContentFactory.parseContent(constraint.getBundleName(), constraint.getVersionRange().toString()); restrictedReqs.add(content); } DeployedBundles deployedBundles = generateDeployedBundles (appMetadata, byValueBundles, restrictedReqs); Manifest man = generateDeploymentManifest(appMetadata.getApplicationSymbolicName(), appMetadata.getApplicationVersion().toString(), deployedBundles); _logger.debug(LOG_EXIT, "generateDeploymentManifest", new Object[] {man}); return man; } /** * Perform provisioning to work out the 'freeze dried list' of the eba * @param appContent - the application content in the application.mf * @param useBundleContent - use bundle entry in the application.mf * @param providedByValueBundles - bundles contained in the eba * @return * @throws ResolverException */ @Override public DeployedBundles generateDeployedBundles(ApplicationMetadata appMetadata, Collection<ModelledResource> provideByValueBundles, Collection<Content> otherBundles) throws ResolverException { Collection<Content> useBundleSet = appMetadata.getUseBundles(); Collection<Content> appContent = appMetadata.getApplicationContents(); Collection<Content> bundlesToResolve = new ArrayList<Content>(); Set<ImportedBundle> appContentIB = toImportedBundle(appContent); Set<ImportedBundle> useBundleIB = toImportedBundle(useBundleSet); bundlesToResolve.addAll(useBundleSet); bundlesToResolve.addAll(appContent); bundlesToResolve.addAll(otherBundles); Collection<ModelledResource> byValueBundles = new ArrayList<ModelledResource>(provideByValueBundles); ModelledResource fakeBundleResource; try { fakeBundleResource = createFakeBundle(appMetadata.getApplicationImportServices()); } catch (InvalidAttributeException iax) { ResolverException rx = new ResolverException (iax); _logger.debug(LOG_EXIT, "generateDeploymentManifest", new Object[] {rx}); throw rx; } byValueBundles.add(fakeBundleResource); Collection<ModelledResource> fakeResources = new ArrayList<ModelledResource>(); for (PreResolveHook hook : preResolveHooks) { hook.collectFakeResources(fakeResources); } byValueBundles.addAll(fakeResources); String appSymbolicName = appMetadata.getApplicationSymbolicName(); String appVersion = appMetadata.getApplicationVersion().toString(); String uniqueName = appSymbolicName + "_" + appVersion; DeployedBundles deployedBundles = modellingHelper.createDeployedBundles(appSymbolicName, appContentIB, useBundleIB, Arrays.asList(fakeBundleResource)); Collection<ModelledResource> bundlesToBeProvisioned = resolver.resolve( appSymbolicName, appVersion, byValueBundles, bundlesToResolve); pruneFakeBundlesFromResults (bundlesToBeProvisioned, fakeResources); if (bundlesToBeProvisioned.isEmpty()) { throw new ResolverException(MessageUtil.getMessage("EMPTY_DEPLOYMENT_CONTENT",uniqueName)); } for (ModelledResource rbm : bundlesToBeProvisioned) { deployedBundles.addBundle(rbm); } Collection<ModelledResource> requiredUseBundle = deployedBundles.getRequiredUseBundle(); if (requiredUseBundle.size() < useBundleSet.size()) { // Some of the use-bundle entries were redundant so resolve again with just the good ones. deployedBundles = modellingHelper.createDeployedBundles(appSymbolicName, appContentIB, useBundleIB, Arrays.asList(fakeBundleResource)); bundlesToResolve.clear(); bundlesToResolve.addAll(appContent); Collection<ImportedBundle> slimmedDownUseBundle = narrowUseBundles(useBundleIB, requiredUseBundle); bundlesToResolve.addAll(toContent(slimmedDownUseBundle)); bundlesToBeProvisioned = resolver.resolve(appSymbolicName, appVersion, byValueBundles, bundlesToResolve); pruneFakeBundlesFromResults (bundlesToBeProvisioned, fakeResources); for (ModelledResource rbm : bundlesToBeProvisioned) { deployedBundles.addBundle(rbm); } requiredUseBundle = deployedBundles.getRequiredUseBundle(); } // Check for circular dependencies. No shared bundle can depend on any // isolated bundle. Collection<ModelledResource> sharedBundles = new HashSet<ModelledResource>(); sharedBundles.addAll (deployedBundles.getDeployedProvisionBundle()); sharedBundles.addAll (requiredUseBundle); Collection<ModelledResource> appContentBundles = deployedBundles.getDeployedContent(); Collection<Content> requiredSharedBundles = new ArrayList<Content>(); for (ModelledResource mr : sharedBundles) { String version = mr.getExportedBundle().getVersion(); String exactVersion = "[" + version + "," + version + "]"; Content ib = ContentFactory.parseContent(mr.getExportedBundle().getSymbolicName(), exactVersion); requiredSharedBundles.add(ib); } // This will throw a ResolverException if the shared content does not resolve Collection<ModelledResource> resolvedSharedBundles = resolver.resolve(appSymbolicName, appVersion , byValueBundles, requiredSharedBundles); // we need to find out whether any shared bundles depend on the isolated bundles List<String> suspects = findSuspects (resolvedSharedBundles, sharedBundles, appContentBundles); // If we have differences, it means that we have shared bundles trying to import packages // from isolated bundles. We need to build up the error message and throw a ResolverException if (!suspects.isEmpty()) { StringBuilder msgs = new StringBuilder(); List<String> unsatisfiedRequirements = new ArrayList<String>(); Map<String, List<String>> isolatedBundles = new HashMap<String, List<String>>(); // Find the isolated bundles and store all the packages that they export in a map. for (ModelledResource mr : resolvedSharedBundles) { String mrName = mr.getSymbolicName() + "_" + mr.getExportedBundle().getVersion(); if (suspects.contains(mrName)) { List<String> exportedPackages = new ArrayList<String>(); isolatedBundles.put(mrName, exportedPackages); for (ExportedPackage ep : mr.getExportedPackages()) { exportedPackages.add(ep.getPackageName()); } } } // Now loop through the shared bundles, reading the imported packages, and find which ones // are exported from the isolated bundles. for (ModelledResource mr : resolvedSharedBundles) { String mrName = mr.getSymbolicName() + "_" + mr.getExportedBundle().getVersion(); // if current resource isn't an isolated bundle check it's requirements if (!!! suspects.contains(mrName)) { // Iterate through the imported packages of the current shared bundle. for (ImportedPackage ip : mr.getImportedPackages()) { String packageName = ip.getPackageName(); List<String> bundlesExportingPackage = new ArrayList<String>(); // Loop through each exported package of each isolated bundle, and if we // get a match store the info away. for (Map.Entry<String, List<String>> currBundle : isolatedBundles.entrySet()) { List<String> exportedPackages = currBundle.getValue(); if (exportedPackages != null && exportedPackages.contains(packageName)) { bundlesExportingPackage.add(currBundle.getKey()); } } // If we have found at least one matching entry, we construct the sub message for the // exception. if (!!! bundlesExportingPackage.isEmpty()) { String newMsg; if (bundlesExportingPackage.size() > 1) { newMsg = MessageUtil.getMessage("SHARED_BUNDLE_IMPORTING_FROM_ISOLATED_BUNDLES", new Object[] {mrName, packageName, bundlesExportingPackage}); } else { newMsg = MessageUtil.getMessage("SHARED_BUNDLE_IMPORTING_FROM_ISOLATED_BUNDLE", new Object[] {mrName, packageName, bundlesExportingPackage}); } msgs.append("\n"); msgs.append(newMsg); unsatisfiedRequirements.add(newMsg); } } } } // Once we have iterated over all bundles and have got our translated submessages, // throw the exception. // Well! if the msgs is empty, no need to throw an exception if (msgs.length() !=0) { String message = MessageUtil.getMessage( "SUSPECTED_CIRCULAR_DEPENDENCIES", new Object[] {appSymbolicName, msgs}); ResolverException rx = new ResolverException (message); rx.setUnsatisfiedRequirements(unsatisfiedRequirements); _logger.debug(LOG_EXIT, "generateDeploymentManifest", new Object[] {rx}); throw (rx); } } checkForIsolatedContentInProvisionBundle(appSymbolicName, deployedBundles); if (postResolveTransformer != null) try { deployedBundles = postResolveTransformer.postResolveProcess (appMetadata, deployedBundles); } catch (ServiceUnavailableException e) { _logger.debug(MessageUtil.getMessage("POST_RESOLVE_TRANSFORMER_UNAVAILABLE",e)); } return deployedBundles; } @Override public Manifest generateDeploymentManifest(String appSymbolicName, String appVersion, DeployedBundles deployedBundles) throws ResolverException { _logger.debug (LOG_ENTRY, "generateDeploymentManifest", new Object[]{appSymbolicName, appVersion, deployedBundles}); Map<String, String> deploymentManifestMap = generateDeploymentAttributes(appSymbolicName, appVersion, deployedBundles); Manifest man = convertMapToManifest(deploymentManifestMap); _logger.debug (LOG_EXIT, "generateDeploymentManifest", man); return man; } /** * Returns a Collection of the {@link ImportedBundle} objects that are * satisfied by the contents of the Collection of requiredUseBundles. * * @param useBundleSet * @param requiredUseBundle * @return the collection of ImportedBundle objects */ private Collection<ImportedBundle> narrowUseBundles( Collection<ImportedBundle> useBundleSet, Collection<ModelledResource> requiredUseBundle) { _logger.debug(LOG_ENTRY, "narrowUseBundles", new Object[] {useBundleSet,requiredUseBundle}); Collection<ImportedBundle> result = new HashSet<ImportedBundle>(); outer : for(ImportedBundle ib : useBundleSet) { for(ModelledResource mb : requiredUseBundle) { if(ib.isSatisfied(mb.getExportedBundle())) { result.add(ib); continue outer; } } } _logger.debug(LOG_EXIT, "narrowUseBundles", result); return result; } private Map<String,String> generateDeploymentAttributes(String appSymbolicName, String version, DeployedBundles deployedBundles) throws ResolverException { _logger.debug(LOG_ENTRY, "generateDeploymentAttributes", new Object[] {appSymbolicName, version}); Map<String,String> result = new HashMap<String, String>(); String content = deployedBundles.getContent(); if (!content.isEmpty()) { result.put(AppConstants.DEPLOYMENT_CONTENT, content); } else { throw new ResolverException(MessageUtil.getMessage("EMPTY_DEPLOYMENT_CONTENT", appSymbolicName)); } String useBundle = deployedBundles.getUseBundle(); if (!useBundle.isEmpty()) { result.put(AppConstants.DEPLOYMENT_USE_BUNDLE, useBundle); } String provisionBundle = deployedBundles.getProvisionBundle(); if (!provisionBundle.isEmpty()) { result.put(AppConstants.DEPLOYMENT_PROVISION_BUNDLE, provisionBundle); } String importServices = deployedBundles.getDeployedImportService(); if (!importServices.isEmpty()) { result.put(AppConstants.DEPLOYMENTSERVICE_IMPORT, importServices); } String importPackages = deployedBundles.getImportPackage(); if (!importPackages.isEmpty()) { result.put(Constants.IMPORT_PACKAGE, importPackages); } result.put(AppConstants.APPLICATION_VERSION, version); result.put(AppConstants.APPLICATION_SYMBOLIC_NAME, appSymbolicName); result.putAll(deployedBundles.getExtraHeaders()); _logger.debug(LOG_EXIT, "generateDeploymentAttributes", result); return result; } private Manifest convertMapToManifest(Map<String,String> attributes) { _logger.debug(LOG_ENTRY, "convertMapToManifest", new Object[]{attributes}); Manifest man = new Manifest(); Attributes att = man.getMainAttributes(); att.putValue(Attributes.Name.MANIFEST_VERSION.toString(), AppConstants.MANIFEST_VERSION); for (Map.Entry<String, String> entry : attributes.entrySet()) { att.putValue(entry.getKey(), entry.getValue()); } _logger.debug(LOG_EXIT, "convertMapToManifest", new Object[]{man}); return man; } private static final String FAKE_BUNDLE_NAME = "aries.internal.fake.service.bundle"; // create a 'mock' bundle that does nothing but export services required by // Application-ImportService private ModelledResource createFakeBundle (Collection<ServiceDeclaration> appImportServices) throws InvalidAttributeException { _logger.debug(LOG_ENTRY, "createFakeBundle", new Object[]{appImportServices}); Attributes attrs = new Attributes(); attrs.putValue(Constants.BUNDLE_SYMBOLICNAME, FAKE_BUNDLE_NAME); attrs.putValue(Constants.BUNDLE_VERSION_ATTRIBUTE, "1.0"); attrs.putValue(Constants.BUNDLE_MANIFESTVERSION, "2"); // Build an ExportedService for every Application-ImportService entry Collection<ExportedService> exportedServices = new ArrayList<ExportedService>(); for (ServiceDeclaration sDec : appImportServices) { Collection<String> ifaces = Arrays.asList(sDec.getInterfaceName()); Filter filter = sDec.getFilter(); Map<String, String> serviceProperties; if (filter != null) { serviceProperties = ManifestHeaderProcessor.parseFilter(filter.toString()); } else { serviceProperties = new HashMap<String, String>(); } serviceProperties.put("service.imported", ""); exportedServices.add (modellingManager.getExportedService("", 0, ifaces, new HashMap<String, Object>(serviceProperties))); } ModelledResource fakeBundle = modellingManager.getModelledResource(null, attrs, null, exportedServices); _logger.debug(LOG_EXIT, "createFakeBundle", new Object[]{fakeBundle}); return fakeBundle; } private void pruneFakeBundlesFromResults (Collection<ModelledResource> results, Collection<ModelledResource> fakeResources) { _logger.debug(LOG_ENTRY, "pruneFakeBundleFromResults", new Object[]{results}); List<String> fakeBundles = new ArrayList<String>(); fakeBundles.add(FAKE_BUNDLE_NAME); for (ModelledResource resource : fakeResources) { fakeBundles.add(resource.getSymbolicName()); } Iterator<ModelledResource> it = results.iterator(); while (it.hasNext()) { ModelledResource mr = it.next(); if (fakeBundles.contains(mr.getSymbolicName())) { it.remove(); } } _logger.debug(LOG_EXIT, "pruneFakeBundleFromResults"); } /** * We've done a sanity check resolve on our sharedBundles and received back * resolvedSharedBundles. The resolvedSharedBundles should not contain any bundles listed in the isolated bundle list. * If this is not true, we've found a case of shared bundles depending on isolated bundles. * This method extracts the name_versions of those bundles in resolvedSharedBundles * that do not appear in sharedBundles. * @param resolvedSharedBundles What we got back from the resolver * @param sharedBundles What we expected to get back from the resolver * @param appContentBundles The isolated bundles * @return The isolated bundles depended by the shared bundles */ private List<String> findSuspects (Collection<ModelledResource> resolvedSharedBundles, Collection<ModelledResource> sharedBundles, Collection<ModelledResource> appContentBundles){ _logger.debug(LOG_ENTRY, "findSuspects", new Object[]{resolvedSharedBundles,sharedBundles, appContentBundles }); Set<String> expectedBundles = new HashSet<String>(); Set<String> isolatedBundles = new HashSet<String>(); for (ModelledResource sb : sharedBundles) { expectedBundles.add(sb.getExportedBundle().getSymbolicName() + "_" + sb.getExportedBundle().getVersion()); } for (ModelledResource sb : appContentBundles) { isolatedBundles.add(sb.getExportedBundle().getSymbolicName() + "_" + sb.getExportedBundle().getVersion()); } List<String> suspects = new ArrayList<String>(); for (ModelledResource mr : resolvedSharedBundles) { String thisBundle = mr.getExportedBundle().getSymbolicName() + "_" + mr.getExportedBundle().getVersion(); if (!expectedBundles.contains(thisBundle) && (isolatedBundles.contains(thisBundle))) { suspects.add(thisBundle); } } _logger.debug(LOG_EXIT, "findSuspects", new Object[]{suspects}); return suspects; } /** * Check whether there are isolated bundles deployed into both deployed content and provision bundles. This almost * always indicates a resolution problem hence we throw a ResolverException. * Note that we check provision bundles rather than provision bundles and deployed use bundles. So in any corner case * where the rejected deployment is actually intended, it can still be achieved by introducing a use bundle clause. * * @param applicationSymbolicName * @param appContentBundles * @param provisionBundles * @throws ResolverException */ private void checkForIsolatedContentInProvisionBundle(String applicationSymbolicName, DeployedBundles db) throws ResolverException { for (ModelledResource isolatedBundle : db.getDeployedContent()) { for (ModelledResource provisionBundle : db.getDeployedProvisionBundle()) { if (isolatedBundle.getSymbolicName().equals(provisionBundle.getSymbolicName()) && providesPackage(provisionBundle, db.getImportPackage())) { throw new ResolverException( MessageUtil.getMessage("ISOLATED_CONTENT_PROVISIONED", applicationSymbolicName, isolatedBundle.getSymbolicName(), isolatedBundle.getVersion(), provisionBundle.getVersion())); } } } } /** * Can the modelled resource provide a package against the given import specificiation * @param bundle * @param importPackages * @return */ private boolean providesPackage(ModelledResource bundle, String importPackages) { Map<String, Map<String, String>> imports = ManifestHeaderProcessor.parseImportString(importPackages); try { for (Map.Entry<String, Map<String,String>> e : imports.entrySet()) { ImportedPackage importPackage = modellingManager.getImportedPackage(e.getKey(), e.getValue()); for (ExportedPackage export : bundle.getExportedPackages()) { if (importPackage.isSatisfied(export)) return true; } } } catch (InvalidAttributeException iae) { _logger.error(MessageUtil.getMessage("UNEXPECTED_EXCEPTION_PARSING_IMPORTS", iae, importPackages), iae); } return false; } /** * Covert a collection of contents to a collection of ImportedBundle objects * @param content a collection of content * @return a collection of ImportedBundle objects * @throws ResolverException */ private Set<ImportedBundle> toImportedBundle(Collection<Content> content) throws ResolverException { _logger.debug(LOG_ENTRY, "toImportedBundle", new Object[]{content}); Set<ImportedBundle> result = new HashSet<ImportedBundle>(); for (Content c : content) { try { result.add(modellingManager.getImportedBundle(c.getContentName(), c.getVersion().toString())); } catch (InvalidAttributeException iax) { ResolverException rx = new ResolverException (iax); _logger.debug(LOG_EXIT, "toImportedBundle", new Object[]{rx}); throw rx; } } _logger.debug(LOG_EXIT, "toImportedBundle", new Object[]{result}); return result; } private Collection<Content> toContent(Collection<ImportedBundle> ibs) { Collection<Content> contents = new ArrayList<Content>(); for (ImportedBundle ib : ibs) { contents.add(ContentFactory.parseContent(ib.getSymbolicName(), ib.getVersionRange())); } return contents; } /** * Get a list of bundles included by value in this application. * @param app The Aries Application * @return a list of by value bundles * @throws IOException * @throws InvalidAttributeException * @throws ModellerException */ private Collection<ModelledResource> getByValueBundles(AriesApplication app) throws IOException, InvalidAttributeException, ModellerException { _logger.debug(LOG_ENTRY, "getByValueBundles", new Object[]{app}); Collection<BundleInfo> bundles = app.getBundleInfo(); Collection<ModelledResource> result = new ArrayList<ModelledResource>(); for (BundleInfo bundleInfo: bundles) { // find out the eba directory String bundleLocation = bundleInfo.getLocation(); String bundleFileName = bundleLocation.substring(bundleLocation.lastIndexOf('/') + 1); // just the portion of root directory excluding ! URL jarUrl = new URL(bundleLocation); URLConnection jarCon = jarUrl.openConnection(); jarCon.connect(); InputStream in = jarCon.getInputStream(); File dir = getLocalPlatform().getTemporaryDirectory(); File temp = new File(dir, bundleFileName); OutputStream out = new FileOutputStream(temp); IOUtils.copy(in, out); IOUtils.close(out); result.add(modelledResourceManager.getModelledResource(null, FileSystem.getFSRoot(temp))); // delete the temp file temp.delete(); IOUtils.deleteRecursive(dir); } _logger.debug(LOG_EXIT, "getByValueBundles", new Object[]{result}); return result; } }
8,868
0
Create_ds/aries/application/application-runtime/src/main/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-runtime/src/main/java/org/apache/aries/application/runtime/impl/ApplicationContextImpl.java
/* * 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.runtime.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.AriesApplicationContext; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.ManagementException; import org.apache.aries.application.management.spi.resolve.AriesApplicationResolver; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceException; import org.osgi.framework.ServiceReference; import org.osgi.framework.Version; import org.osgi.service.packageadmin.PackageAdmin; public class ApplicationContextImpl implements AriesApplicationContext { private AriesApplication _application; private Map<BundleInfo, Bundle> _bundles; private ApplicationState _state; private BundleContext _bundleContext; public ApplicationContextImpl (BundleContext b, AriesApplication app) throws BundleException, ManagementException { _bundleContext = b; _application = app; _bundles = new HashMap<BundleInfo, Bundle>(); DeploymentMetadata meta = _application.getDeploymentMetadata(); AriesApplicationResolver resolver = null; PackageAdmin packageAdmin = null; ServiceReference resolverRef = b.getServiceReference(AriesApplicationResolver.class.getName()); ServiceReference packageAdminRef = b.getServiceReference(PackageAdmin.class.getName()); try { resolver = getService(resolverRef, AriesApplicationResolver.class); packageAdmin = getService(packageAdminRef, PackageAdmin.class); List<DeploymentContent> bundlesToInstall = new ArrayList<DeploymentContent>(meta.getApplicationDeploymentContents()); bundlesToInstall.addAll(meta.getApplicationProvisionBundles()); bundlesToInstall.addAll(meta.getDeployedUseBundle()); for (DeploymentContent content : bundlesToInstall) { String bundleSymbolicName = content.getContentName(); Version bundleVersion = content.getExactVersion(); // Step 1: See if bundle is already installed in the framework if (findBundleInFramework(packageAdmin, bundleSymbolicName, bundleVersion) != null) { continue; } // Step 2: See if the bundle is included in the application BundleInfo bundleInfo = findBundleInfoInApplication(bundleSymbolicName, bundleVersion); if (bundleInfo == null) { // Step 3: Lookup bundle location using the resolver bundleInfo = findBundleInfoUsingResolver(resolver, bundleSymbolicName, bundleVersion); } if (bundleInfo == null) { throw new ManagementException("Cound not find bundles: " + bundleSymbolicName + "_" + bundleVersion); } Bundle bundle = _bundleContext.installBundle(bundleInfo.getLocation()); _bundles.put(bundleInfo, bundle); } } catch (BundleException be) { for (Bundle bundle : _bundles.values()) { bundle.uninstall(); } _bundles.clear(); throw be; } finally { if (resolver != null) { b.ungetService(resolverRef); } if (packageAdmin != null) { b.ungetService(packageAdminRef); } } _state = ApplicationState.INSTALLED; } private <T> T getService(ServiceReference ref, Class<T> type) throws ManagementException { Object service = null; if (ref != null) { service = _bundleContext.getService(ref); } if (service == null) { throw new ManagementException(new ServiceException(type.getName(), ServiceException.UNREGISTERED)); } return type.cast(service); } private Bundle findBundleInFramework(PackageAdmin admin, String symbolicName, Version version) { String exactVersion = "[" + version + "," + version + "]"; Bundle[] bundles = admin.getBundles(symbolicName, exactVersion); if (bundles != null && bundles.length == 1) { return bundles[0]; } else { return null; } } private BundleInfo findBundleInfoInApplication(String symbolicName, Version version) { for (BundleInfo info : _application.getBundleInfo()) { if (info.getSymbolicName().equals(symbolicName) && info.getVersion().equals(version)) { return info; } } return null; } private BundleInfo findBundleInfoUsingResolver(AriesApplicationResolver resolver, String symbolicName, Version version) { return resolver.getBundleInfo(symbolicName, version); } public AriesApplication getApplication() { return _application; } public Set<Bundle> getApplicationContent() { Set<Bundle> result = new HashSet<Bundle>(); for (Map.Entry<BundleInfo, Bundle> entry : _bundles.entrySet()) { result.add (entry.getValue()); } return result; } public ApplicationState getApplicationState() { return _state; } public void start() throws BundleException { _state = ApplicationState.STARTING; List<Bundle> bundlesWeStarted = new ArrayList<Bundle>(); try { for (Bundle b : _bundles.values()) { if (b.getState() != Bundle.ACTIVE) { b.start(Bundle.START_ACTIVATION_POLICY); bundlesWeStarted.add(b); } } } catch (BundleException be) { for (Bundle b : bundlesWeStarted) { try { b.stop(); } catch (BundleException be2) { // we are doing tidyup here, so we don't want to replace the bundle exception // that occurred during start with one from stop. We also want to try to stop // all the bundles we started even if some bundles wouldn't stop. } } _state = ApplicationState.INSTALLED; throw be; } _state = ApplicationState.ACTIVE; } public void stop() throws BundleException { for (Map.Entry<BundleInfo, Bundle> entry : _bundles.entrySet()) { Bundle b = entry.getValue(); b.stop(); } _state = ApplicationState.RESOLVED; } public void setState(ApplicationState state) { _state = state; } }
8,869
0
Create_ds/aries/application/application-runtime/src/main/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-runtime/src/main/java/org/apache/aries/application/runtime/impl/ApplicationContextManagerImpl.java
/* * 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.runtime.impl; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.AriesApplicationContext; import org.apache.aries.application.management.ManagementException; import org.apache.aries.application.management.UpdateException; import org.apache.aries.application.management.AriesApplicationContext.ApplicationState; import org.apache.aries.application.management.spi.runtime.AriesApplicationContextManager; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; public class ApplicationContextManagerImpl implements AriesApplicationContextManager { private ConcurrentMap<AriesApplication, ApplicationContextImpl> _appToContextMap; private BundleContext _bundleContext; public ApplicationContextManagerImpl () { _appToContextMap = new ConcurrentHashMap<AriesApplication, ApplicationContextImpl>(); } public void setBundleContext (BundleContext b) { _bundleContext = b; } public AriesApplicationContext getApplicationContext(AriesApplication app) throws BundleException, ManagementException { ApplicationContextImpl result; if (_appToContextMap.containsKey(app)) { result = _appToContextMap.get(app); } else { result = new ApplicationContextImpl (_bundleContext, app); ApplicationContextImpl previous = _appToContextMap.putIfAbsent(app, result); if (previous != null) { result = previous; } } return result; } public Set<AriesApplicationContext> getApplicationContexts() { Set<AriesApplicationContext> result = new HashSet<AriesApplicationContext>(); for (Map.Entry<AriesApplication, ApplicationContextImpl> entry: _appToContextMap.entrySet()) { result.add (entry.getValue()); } return result; } public void remove(AriesApplicationContext app) { Iterator<Map.Entry<AriesApplication, ApplicationContextImpl>> it = _appToContextMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<AriesApplication, ApplicationContextImpl> entry = it.next(); ApplicationContextImpl potentialMatch = entry.getValue(); if (potentialMatch == app) { it.remove(); uninstall(potentialMatch); break; } } } private void uninstall(ApplicationContextImpl app) { Set<Bundle> bundles = app.getApplicationContent(); for (Bundle b : bundles) { try { b.uninstall(); } catch (BundleException be) { // TODO ignoring this feels wrong, but I'm not sure how to communicate to the caller multiple failures. } } app.setState(ApplicationState.UNINSTALLED); } public void close() { for (ApplicationContextImpl ctx : _appToContextMap.values()) { uninstall(ctx); } _appToContextMap.clear(); } public AriesApplicationContext update(AriesApplication app, DeploymentMetadata oldMetadata) throws UpdateException { ApplicationContextImpl oldCtx = _appToContextMap.get(app); if (oldCtx == null) { throw new IllegalArgumentException("AriesApplication "+ app.getApplicationMetadata().getApplicationSymbolicName() + "/" + app.getApplicationMetadata().getApplicationVersion() + " cannot be updated because it is not installed"); } uninstall(oldCtx); try { AriesApplicationContext newCtx = getApplicationContext(app); if (oldCtx.getApplicationState() == ApplicationState.ACTIVE) { newCtx.start(); } return newCtx; } catch (BundleException e) { throw new UpdateException("Update failed: "+e.getMessage(), e, false, null); } catch (ManagementException e) { throw new UpdateException("Update failed: "+e.getMessage(), e, false, null); } } }
8,870
0
Create_ds/aries/application/application-modeller-standalone/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-standalone/src/main/java/org/apache/aries/application/modelling/standalone/OfflineModellingFactory.java
/** * 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.aries.application.modelling.standalone; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Set; import javax.xml.validation.Schema; import org.apache.aries.application.modelling.ModelledResourceManager; import org.apache.aries.application.modelling.ParserProxy; import org.apache.aries.application.modelling.ServiceModeller; import org.apache.aries.application.modelling.impl.AbstractParserProxy; import org.apache.aries.application.modelling.impl.ModelledResourceManagerImpl; import org.apache.aries.application.modelling.impl.ModellingManagerImpl; import org.apache.aries.blueprint.ComponentDefinitionRegistry; import org.apache.aries.blueprint.NamespaceHandler; import org.apache.aries.blueprint.ParserContext; import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl; import org.apache.aries.blueprint.parser.NamespaceHandlerSet; import org.apache.aries.blueprint.parser.Parser; import org.osgi.service.blueprint.reflect.ComponentMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.service.blueprint.reflect.NullMetadata; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; public class OfflineModellingFactory { private static final NamespaceHandlerSet DUMMY_HANDLER_SET = new NamespaceHandlerSet() { public NamespaceHandler getNamespaceHandler(URI arg0) { return new NamespaceHandler() { public Metadata parse(Element arg0, ParserContext arg1) { return NullMetadata.NULL; } public URL getSchemaLocation(String arg0) { return null; } public Set<Class> getManagedClasses() { return Collections.emptySet(); } public ComponentMetadata decorate(Node arg0, ComponentMetadata arg1, ParserContext arg2) { return arg1; } }; } public Set<URI> getNamespaces() { return Collections.emptySet(); } public Schema getSchema() throws SAXException, IOException { return null; } public boolean isComplete() { return true; } public void addListener(Listener arg0) {} public void removeListener(Listener arg0) {} public void destroy() {} }; private static class OfflineParserProxy extends AbstractParserProxy { protected ComponentDefinitionRegistry parseCDR(List<URL> blueprintsToParse) throws Exception { Parser parser = new Parser(); parser.parse(blueprintsToParse); return getCDR(parser); } protected ComponentDefinitionRegistry parseCDR(InputStream blueprintToParse) throws Exception { Parser parser = new Parser(); parser.parse(blueprintToParse); return getCDR(parser); } private ComponentDefinitionRegistry getCDR(Parser parser) { ComponentDefinitionRegistry cdr = new ComponentDefinitionRegistryImpl(); parser.populate(DUMMY_HANDLER_SET, cdr); return cdr; } }; public static ParserProxy getOfflineParserProxy() { ModellingManagerImpl modellingManager = new ModellingManagerImpl(); OfflineParserProxy parserProxy = new OfflineParserProxy(); parserProxy.setModellingManager(modellingManager); return parserProxy; } public static ModelledResourceManager getModelledResourceManager() { ModellingManagerImpl modellingManager = new ModellingManagerImpl(); OfflineParserProxy parserProxy = new OfflineParserProxy(); parserProxy.setModellingManager(modellingManager); ModelledResourceManagerImpl result = new ModelledResourceManagerImpl(); result.setModellingManager(modellingManager); result.setParserProxy(parserProxy); List<ServiceModeller> plugins = new ArrayList<ServiceModeller>(); ClassLoader cl = OfflineModellingFactory.class.getClassLoader(); try { Enumeration<URL> e = cl.getResources( "META-INF/services/" + ServiceModeller.class.getName()); while(e.hasMoreElements()) { BufferedReader reader = new BufferedReader(new InputStreamReader( e.nextElement().openStream())); try { plugins.add((ServiceModeller) Class.forName(reader.readLine(), true, cl).newInstance()); } catch (Exception e1) { e1.printStackTrace(System.err); } } } catch (IOException e) { e.printStackTrace(System.err); } result.setModellingPlugins(plugins); return result; } }
8,871
0
Create_ds/aries/application/application-resolve-transform-cm-itests/src/test/java/org/apache/aries/application/resolve/transform/cm
Create_ds/aries/application/application-resolve-transform-cm-itests/src/test/java/org/apache/aries/application/resolve/transform/cm/itest/ConfigurationPostResolverTest.java
/* * 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.aries.application.resolve.transform.cm.itest; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.vmOption; import static org.ops4j.pax.exam.CoreOptions.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Map; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.resolve.PostResolveTransformer; import org.apache.aries.application.modelling.DeployedBundles; 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.Provider; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.itest.RichBundleContext; import org.apache.aries.unittest.mocks.Skeleton; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; @RunWith(PaxExam.class) public class ConfigurationPostResolverTest extends AbstractIntegrationTest { /** * This test validates that the transformer is correctly detecting the config admin package. Checks * are performed to validate that an existing import package is still honored etc. * * @throws Exception */ @Test public void validatePostResolveTransform() throws Exception { RichBundleContext ctx = new RichBundleContext(bundleContext); PostResolveTransformer transformer = ctx.getService(PostResolveTransformer.class); Assert.assertNotNull("Unable to locate transformer", transformer); /** * Try processing deployed content that doesn't have any import for the * org.osgi.service.cm package, the resultant imports should be unaffected. */ ApplicationMetadata mockApplicationMetadata = Skeleton.newMock(ApplicationMetadata.class); MockDeployedBundles originalDeployedBundles = new MockDeployedBundles(); originalDeployedBundles.setDeployedContent(getNonConfigModelledResources()); DeployedBundles transformedDeployedBundles = transformer.postResolveProcess(mockApplicationMetadata, originalDeployedBundles); Assert.assertNotNull("An instance should have been returned", transformedDeployedBundles); Assert.assertEquals(originalDeployedBundles.getImportPackage(), transformedDeployedBundles.getImportPackage()); /** * Now try processing a deployed bundles instances that has an import for the org.osgi.service.cm package in multiple * modelled resources with an empty import package set in the mock deployed bundles instance. */ originalDeployedBundles = new MockDeployedBundles(); originalDeployedBundles.setDeployedContent(getConfigModelledResources()); transformedDeployedBundles = transformer.postResolveProcess(mockApplicationMetadata, originalDeployedBundles); Assert.assertNotNull("An instance should have been returned", transformedDeployedBundles); Assert.assertNotSame("Missing config package", originalDeployedBundles.getImportPackage(), transformedDeployedBundles.getImportPackage()); Assert.assertEquals("Missing config package", "org.osgi.service.cm;version=\"1.2.0\"", transformedDeployedBundles.getImportPackage()); /** * Now try processing a deployed bundles instances that has an import for the org.osgi.service.cm package in multiple * modelled resources with a populated import package set in the mock deployed bundles instance. */ originalDeployedBundles = new MockDeployedBundles(); originalDeployedBundles.setDeployedContent(getConfigModelledResources()); originalDeployedBundles.setImportPackage("org.foo.bar;version=\1.0.0\",org.bar.foo;version=\"1.0.0\""); transformedDeployedBundles = transformer.postResolveProcess(mockApplicationMetadata, originalDeployedBundles); Assert.assertNotNull("An instance should have been returned", transformedDeployedBundles); Assert.assertNotSame("Missing config package", originalDeployedBundles.getImportPackage(), transformedDeployedBundles.getImportPackage()); Assert.assertEquals("Missing config package", "org.foo.bar;version=\1.0.0\",org.bar.foo;version=\"1.0.0\",org.osgi.service.cm;version=\"1.2.0\"", transformedDeployedBundles.getImportPackage()); } private static Collection<ModelledResource> getNonConfigModelledResources() { Collection<ModelledResource> modelledResources = new ArrayList<ModelledResource>(); MockModelledResource ms1 = new MockModelledResource(); ms1.setImportedPackages(Arrays.asList(new MockImportedPackage("org.foo.bar", "1.0.0"), new MockImportedPackage("org.bar.foo", "1.0.0"))); return modelledResources; } private static Collection<ModelledResource> getConfigModelledResources() { Collection<ModelledResource> resources = getNonConfigModelledResources(); MockModelledResource mmr1 = new MockModelledResource(); mmr1.setImportedPackages(Arrays.asList(new MockImportedPackage("org.osgi.service.cm", "1.2.0"))); resources.add(mmr1); MockModelledResource mmr2 = new MockModelledResource(); mmr2.setImportedPackages(Arrays.asList(new MockImportedPackage("org.osgi.service.cm", "1.2.0"))); resources.add(mmr2); return resources; } public Option baseOptions() { String localRepo = System.getProperty("maven.repo.local"); if (localRepo == null) { localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository"); } return composite( junitBundles(), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject() ); } /** * Create the configuration for the PAX container * * @return the various required options * @throws Exception */ @Configuration public Option[] configuration() throws Exception { return options( baseOptions(), mavenBundle("org.osgi", "org.osgi.compendium").versionAsInProject(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint").versionAsInProject(), mavenBundle("org.ow2.asm", "asm-all").versionAsInProject(), mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(), mavenBundle("org.osgi", "org.osgi.compendium").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolve.transform.cm").versionAsInProject() ); } private static class MockDeployedBundles implements DeployedBundles { private Collection<ModelledResource> deployedContent; private String importPackage; public void addBundle(ModelledResource arg0) { } public String getContent() { return null; } public Collection<ModelledResource> getDeployedContent() { return deployedContent; } public void setDeployedContent(Collection<ModelledResource> deployedContent) { this.deployedContent = deployedContent; } public String getDeployedImportService() { return null; } public Collection<ModelledResource> getDeployedProvisionBundle() { return null; } public Map<String, String> getExtraHeaders() { return null; } public void setImportPackage(String importPackage) { this.importPackage = importPackage; } /** * Used to reflect external packages required */ public String getImportPackage() throws ResolverException { return importPackage; } public String getProvisionBundle() { return null; } public Collection<ModelledResource> getRequiredUseBundle() throws ResolverException { return null; } public String getUseBundle() { return null; } } private static class MockModelledResource implements ModelledResource { private Collection<? extends ImportedPackage> importedPackages; public String toDeploymentString() { return null; } public ExportedBundle getExportedBundle() { return null; } public Collection<? extends ExportedPackage> getExportedPackages() { return null; } public Collection<? extends ExportedService> getExportedServices() { return null; } public ImportedBundle getFragmentHost() { return null; } public Collection<? extends ImportedPackage> getImportedPackages() { return importedPackages; } public void setImportedPackages(Collection<? extends ImportedPackage> importedPackages) { this.importedPackages = importedPackages; } public Collection<? extends ImportedService> getImportedServices() { return null; } public String getLocation() { return null; } public Collection<? extends ImportedBundle> getRequiredBundles() { return null; } public String getSymbolicName() { return null; } public ResourceType getType() { return null; } public String getVersion() { return null; } public boolean isFragment() { return false; } } private static class MockImportedPackage implements ImportedPackage { private String packageName; private String versionRange; public MockImportedPackage(String packageName, String versionRange) { this.packageName = packageName; this.versionRange = versionRange; } public String getAttributeFilter() { return null; } public ResourceType getType() { return null; } public boolean isMultiple() { return false; } public boolean isOptional() { return false; } public boolean isSatisfied(Provider provider) { return false; } public String toDeploymentString() { return packageName + ";version=\"" + versionRange + "\""; } public Map<String, String> getAttributes() { return null; } public String getPackageName() { return packageName; } public String getVersionRange() { return versionRange; } } }
8,872
0
Create_ds/aries/application/application-resolve-transform-cm/src/main/java/org/apache/aries/application/resolve/transform
Create_ds/aries/application/application-resolve-transform-cm/src/main/java/org/apache/aries/application/resolve/transform/cm/ConfigurationPostResolveTransformerImpl.java
/* * 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.aries.application.resolve.transform.cm; import java.util.Collection; import java.util.Map; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.resolve.PostResolveTransformer; import org.apache.aries.application.modelling.DeployedBundles; import org.apache.aries.application.modelling.ImportedPackage; import org.apache.aries.application.modelling.ModelledResource; public class ConfigurationPostResolveTransformerImpl implements PostResolveTransformer { /* * (non-Javadoc) * @see org.apache.aries.application.management.spi.resolve.PostResolveTransformer#postResolveProcess(org.apache.aries.application.ApplicationMetadata, org.apache.aries.application.modelling.DeployedBundles) */ public DeployedBundles postResolveProcess(ApplicationMetadata appMetaData, DeployedBundles deployedBundles) throws ResolverException { return new ConfigAwareDeployedBundles(deployedBundles); } /** * This class serves as a wrapper for a DeployedBundles instance, if the delegate instance * does not import the configuration management package and the deployed content contains the * configuration admin bundle, then the necessary import will be added. This is required so that the * blueprint-cm bundle will not encounter class casting issues from a ConfigurationAdmin service * that has been loaded in an isolated application scope, rather all *.cm related classes are * referenced by the same class loader. * * * @version $Rev$ $Date$ */ private static class ConfigAwareDeployedBundles implements DeployedBundles { private static final String CONFIG_PACKAGE = "org.osgi.service.cm"; private DeployedBundles deployedBundles; public ConfigAwareDeployedBundles(DeployedBundles deployedBundles) { this.deployedBundles = deployedBundles; } public void addBundle(ModelledResource resource) { deployedBundles.addBundle(resource); } public String getContent() { return deployedBundles.getContent(); } public Collection<ModelledResource> getDeployedContent() { return deployedBundles.getDeployedContent(); } public String getDeployedImportService() { return deployedBundles.getDeployedImportService(); } public Collection<ModelledResource> getDeployedProvisionBundle() { return deployedBundles.getDeployedProvisionBundle(); } public Map<String, String> getExtraHeaders() { return deployedBundles.getExtraHeaders(); } public String getImportPackage() throws ResolverException { String currentImportPackage = deployedBundles.getImportPackage(); StringBuffer rawImportPackage = new StringBuffer((currentImportPackage != null ? currentImportPackage : "")); if (! rawImportPackage.toString().contains(CONFIG_PACKAGE)) { Collection<ModelledResource> deployedContent = deployedBundles.getDeployedContent(); if (deployedContent != null) { modelledResourceCheck: for (ModelledResource mr : deployedContent) { Collection<? extends ImportedPackage> importedPackages = mr.getImportedPackages(); if (importedPackages != null) { for (ImportedPackage importedPackage : importedPackages) { if (CONFIG_PACKAGE.equals(importedPackage.getPackageName())) { if (rawImportPackage.length() > 0) { rawImportPackage.append(","); } rawImportPackage.append(importedPackage.toDeploymentString()); break modelledResourceCheck; } } } } } } return (rawImportPackage.length() > 0 ? rawImportPackage.toString() : currentImportPackage); } public String getProvisionBundle() { return deployedBundles.getProvisionBundle(); } public Collection<ModelledResource> getRequiredUseBundle() throws ResolverException { return deployedBundles.getRequiredUseBundle(); } public String getUseBundle() { return deployedBundles.getUseBundle(); } } }
8,873
0
Create_ds/aries/application/application-obr-resolver/src/test/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/test/java/org/apache/aries/application/resolver/obr/impl/AriesResolverTest.java
/* * 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.resolver.obr.impl; import static junit.framework.Assert.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.application.resolver.obr.OBRAriesResolver; import org.apache.aries.unittest.mocks.Skeleton; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Reason; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resolver; import org.apache.felix.bundlerepository.Resource; import org.junit.Before; import org.junit.Test; import org.osgi.framework.Version; public class AriesResolverTest extends OBRAriesResolver { Resolver resolver; ResolverMock resolverMock; public AriesResolverTest() { super(Skeleton.newMock(RepositoryAdmin.class)); } static class ResolverMock { private final List<Resource> resources = new ArrayList<Resource>(); private final Map<String, List<Requirement>> requirements = new HashMap<String, List<Requirement>>(); private String curRes; private ResourceMock curResMock; private RequirementMock curReqMock; public Reason[] getReason(Resource r) { Requirement[] reqs = requirements.get(r.getSymbolicName() + "_" + r.getVersion()).toArray(new Requirement[0]); Reason[] reasons = new Reason[reqs.length]; int i=0; for (Requirement req : reqs) { reasons[i++] = new ReasonMock(r, req); } return reasons; } public Resource[] getRequiredResources() { return resources.toArray(new Resource[0]); } public ResolverMock res(String name, String version) { curRes = name + "_" + version; curResMock = new ResourceMock(name,version); resources.add(Skeleton.newMock(curResMock, Resource.class)); requirements.put(curRes, new ArrayList<Requirement>()); return this; } public ResolverMock optional() { curReqMock.optional = true; return this; } public ResolverMock req(String name) { // requirements are based on String, so that we have valid equals and hashCode implementations curReqMock = new RequirementMock(name); requirements.get(curRes).add(Skeleton.newMock(curReqMock, Requirement.class)); curResMock.addCapability(name); return this; } } static class CapabilityMock { private final String cap; CapabilityMock(String cap) { this.cap = cap; } @Override public String toString() { return cap; } } static class RequirementMock { private final String req; public boolean optional = false; RequirementMock(String req) { this.req = req; } public boolean isSatisfied(Capability c) { return c.toString().equals(req); } public boolean isOptional() { return optional; } } static class ReasonMock implements Reason{ private final Resource res; private final Requirement req; ReasonMock (Resource res, Requirement req) { this.res = res; this.req = req; } public Resource getResource() { return this.res; } public Requirement getRequirement() { return this.req; } } static class ResourceMock { private final String name; private final Version version; private final List<Capability> capabilities; ResourceMock(String name, String version) { this.name = name; this.version = new Version(version); capabilities = new ArrayList<Capability>(); } public void addCapability(String cap) { capabilities.add(Skeleton.newMock(new CapabilityMock(cap), Capability.class)); } public Capability[] getCapabilities() { return capabilities.toArray(new Capability[0]); } public Version getVersion() { return version; } public String getSymbolicName() { return name; } } @Before public void before() { resolverMock = new ResolverMock(); resolver = Skeleton.newMock(resolverMock, Resolver.class); } @Test public void testIncompatible() { resolverMock .res("com.ibm.test", "0.0.0") .req("a") .req("b") .res("com.ibm.test", "1.0.0") .req("a") .req("c"); List<Resource> res = retrieveRequiredResources(resolver); assertEquals(2, res.size()); assertResource(res.get(0), "com.ibm.test", "0.0.0"); assertResource(res.get(1), "com.ibm.test", "1.0.0"); } @Test public void testLeftRedundant() { resolverMock .res("com.ibm.test", "0.0.0") .req("a") .req("b") .res("com.ibm.test", "1.0.0") .req("a") .req("b") .req("c"); List<Resource> res = retrieveRequiredResources(resolver); assertEquals(1, res.size()); assertResource(res.get(0), "com.ibm.test", "1.0.0"); } @Test public void testRightRedundant() { resolverMock .res("com.ibm.test", "0.0.0") .req("a") .req("b") .req("c") .res("com.ibm.test", "1.0.0") .req("a") .req("c"); List<Resource> res = retrieveRequiredResources(resolver); assertEquals(1, res.size()); assertResource(res.get(0), "com.ibm.test", "0.0.0"); } @Test public void testEquivalent() { resolverMock .res("com.ibm.test", "0.0.0") .req("a") .req("b") .res("com.ibm.test", "2.0.0") .req("a") .req("b") .res("com.ibm.test", "1.0.0") .req("a") .req("b"); List<Resource> res = retrieveRequiredResources(resolver); assertEquals(1, res.size()); assertResource(res.get(0), "com.ibm.test", "2.0.0"); } @Test public void testEquivalentWithOptionals() { // 1.1.0 and 1.0.0 are incompatible if we leave aside that "c" is optional. // "bundle" is the downgrade dependency on 1.0.0, "c" is the optional service requirement for the CommentService resolverMock .res("com.ibm.test", "1.0.0") .req("a") .req("b") .req("bundle") .res("com.ibm.test", "1.1.0") .req("a") .req("b") .req("c").optional(); List<Resource> res = retrieveRequiredResources(resolver); assertEquals(1, res.size()); assertResource(res.get(0), "com.ibm.test", "1.0.0"); } private void assertResource(Resource r, String name, String version) { assertEquals(name, r.getSymbolicName()); assertEquals(version, r.getVersion().toString()); } }
8,874
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/internal/MessageUtil.java
/* * 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.resolver.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.resolver.messages.ResolverMessages"); /** * 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; } }
8,875
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/internal/DefaultPlatformRepository.java
/* * 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.resolver.internal; import java.net.URI; import java.util.Collection; import org.apache.aries.application.management.spi.repository.PlatformRepository; public class DefaultPlatformRepository implements PlatformRepository { public Collection<URI> getPlatformRepositoryURLs() { return null; } }
8,876
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/OBRAriesResolver.java
/* * 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.aries.application.resolver.obr; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.Content; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.ResolveConstraint; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.repository.PlatformRepository; import org.apache.aries.application.management.spi.resolve.AriesApplicationResolver; import org.apache.aries.application.modelling.ImportedBundle; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ModellingConstants; import org.apache.aries.application.modelling.ModellingManager; import org.apache.aries.application.modelling.utils.ModellingHelper; import org.apache.aries.application.resolver.internal.MessageUtil; import org.apache.aries.application.resolver.obr.ext.ModelledBundleResource; import org.apache.aries.application.resolver.obr.impl.ApplicationResourceImpl; import org.apache.aries.application.resolver.obr.impl.OBRBundleInfo; import org.apache.aries.application.resolver.obr.impl.RepositoryGeneratorImpl; import org.apache.aries.application.resolver.obr.impl.ResourceWrapper; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.application.utils.manifest.ContentFactory; import org.apache.aries.util.VersionRange; import org.apache.aries.util.io.IOUtils; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.DataModelHelper; import org.apache.felix.bundlerepository.Reason; import org.apache.felix.bundlerepository.Repository; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resolver; import org.apache.felix.bundlerepository.Resource; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @version $Rev$ $Date$ */ public class OBRAriesResolver implements AriesApplicationResolver { private static Logger log = LoggerFactory.getLogger(OBRAriesResolver.class); private final RepositoryAdmin repositoryAdmin; private boolean returnOptionalResources = true; private PlatformRepository platformRepository; private ModellingManager modellingManager; private ModellingHelper modellingHelper; public void setModellingManager (ModellingManager m) { modellingManager = m; } public void setModellingHelper (ModellingHelper mh) { modellingHelper = mh; } public PlatformRepository getPlatformRepository() { return platformRepository; } public RepositoryAdmin getRepositoryAdmin() { return this.repositoryAdmin; } public void setPlatformRepository(PlatformRepository platformRepository) { this.platformRepository = platformRepository; } public OBRAriesResolver(RepositoryAdmin repositoryAdmin) { this.repositoryAdmin = repositoryAdmin; } public void setReturnOptionalResources(boolean optional) { this.returnOptionalResources = optional; } public boolean getReturnOptionalResources() { return returnOptionalResources; } /** * Resolve a list of resources from the OBR bundle repositories by OBR * resolver. * * @param appName - application name * @param appVersion - application version * @param byValueBundles - by value bundles * @param inputs - other constraints * @param platformRepository - a platform repository to use instead of the one provided as a service * @return a collection of modelled resources required by this application * @throws ResolverException */ @Override public Collection<ModelledResource> resolve(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException { log.debug(LOG_ENTRY, "resolve", new Object[]{appName, appVersion,byValueBundles, inputs}); Collection<ImportedBundle> importedBundles = toImportedBundle(inputs); Resolver obrResolver = getConfiguredObrResolver(appName, appVersion, byValueBundles, false); // add a resource describing the requirements of the application metadata. obrResolver.add(createApplicationResource( appName, appVersion, importedBundles)); log.debug(LOG_EXIT, "resolve"); return doResolve(obrResolver, appName); } private Collection<ModelledResource> doResolve(Resolver obrResolver, String appName) throws ResolverException { log.debug(LOG_ENTRY, "doResolve"); Collection<ModelledResource> toReturn = new ArrayList<ModelledResource>(); if (obrResolver.resolve()) { List<Resource> requiredResources = retrieveRequiredResources(obrResolver); if (requiredResources == null) { log.debug("resolver.getRequiredResources() returned null"); } else { for (Resource r : requiredResources) { Map<String, String> attribs = new HashMap<String, String>(); attribs.put(Constants.VERSION_ATTRIBUTE, "[" + r.getVersion() + ',' + r.getVersion() + "]"); ModelledResource modelledResourceForThisMatch = null; // OBR may give us back the global capabilities. Typically these do not have a bundle symbolic name - they're a // list of packages available in the target runtime environment. If the resource has no symbolic name, we can ignore it if (r.getSymbolicName() != null) { try { modelledResourceForThisMatch = new ModelledBundleResource (r, modellingManager, modellingHelper); } catch (InvalidAttributeException iax) { ResolverException re = new ResolverException("Internal error occurred: " + iax); log.debug(LOG_EXIT, "doResolve", re); throw re; } toReturn.add(modelledResourceForThisMatch); } } } log.debug(LOG_EXIT, toReturn); return toReturn; } else { Reason[] reasons = obrResolver.getUnsatisfiedRequirements(); // let's refine the list by removing the indirect unsatisfied bundles that are caused by unsatisfied packages or other bundles Map<String,Set<String>> refinedReqs = refineUnsatisfiedRequirements(obrResolver, reasons); StringBuffer reqList = new StringBuffer(); Map<String, String> unsatisfiedRequirements = extractConsumableMessageInfo(refinedReqs); for (String reason : unsatisfiedRequirements.keySet()) { reqList.append('\n'); reqList.append(reason); } ResolverException re = new ResolverException(MessageUtil.getMessage("RESOLVER_UNABLE_TO_RESOLVE", new Object[] { appName, reqList })); re.setUnsatisfiedRequirementsAndReasons(unsatisfiedRequirements); log.debug(LOG_EXIT, "doResolve", re); throw re; } } @Override public Collection<ModelledResource> resolveInIsolation(String appName, String appVersion, Collection<ModelledResource> byValueBundles, Collection<Content> inputs) throws ResolverException { log.debug(LOG_ENTRY, "resolve", new Object[]{appName, appVersion,byValueBundles, inputs}); Collection<ImportedBundle> importedBundles = toImportedBundle(inputs); Resolver obrResolver = getConfiguredObrResolver(appName, appVersion, byValueBundles, true); // add a resource describing the requirements of the application metadata. obrResolver.add(createApplicationResource( appName, appVersion, importedBundles)); log.debug(LOG_EXIT, "resolve"); return doResolve(obrResolver, appName); } private Resolver getConfiguredObrResolver(String appName, String appVersion, Collection<ModelledResource> byValueBundles, boolean noExtraRepositories) throws ResolverException { log.debug(LOG_ENTRY, "getConfiguredObrResolver", new Object[]{appName, appVersion,byValueBundles }); DataModelHelper helper = repositoryAdmin.getHelper(); Repository appRepo; try { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); RepositoryGeneratorImpl.generateRepository(repositoryAdmin, appName + "_" + appVersion, byValueBundles, bytesOut); appRepo = helper.readRepository(new InputStreamReader(new ByteArrayInputStream(bytesOut.toByteArray()))); } catch (Exception e) { throw new ResolverException(e); } List<Repository> resolveRepos = new ArrayList<Repository>(); // add system repository resolveRepos.add(repositoryAdmin.getSystemRepository()); // add application repository resolveRepos.add(appRepo); if (!!!noExtraRepositories) { // add local repository if configured if (!(excludeLocalRuntime())) { resolveRepos.add(getLocalRepository(repositoryAdmin)); } // Need to refresh the repositories added to repository admin // add user-defined repositories Repository[] repos = repositoryAdmin.listRepositories(); for (Repository r : repos) { resolveRepos.add(r); } } Resolver obrResolver = repositoryAdmin.resolver(resolveRepos.toArray(new Repository[resolveRepos.size()])); addPlatformRepositories (obrResolver, appName, platformRepository); log.debug(LOG_EXIT, "getConfiguredObrResolver", obrResolver); return obrResolver; } @Deprecated @Override public Set<BundleInfo> resolve(AriesApplication app, ResolveConstraint... constraints) throws ResolverException { log.trace("resolving {}", app); ApplicationMetadata appMeta = app.getApplicationMetadata(); String appName = appMeta.getApplicationSymbolicName(); Version appVersion = appMeta.getApplicationVersion(); List<Content> appContent = appMeta.getApplicationContents(); Collection<Content> useBundleContent = appMeta.getUseBundles(); List<Content> contents = new ArrayList<Content>(); contents.addAll(appContent); contents.addAll(useBundleContent); if ((constraints != null ) && (constraints.length > 0 )) { for (ResolveConstraint con: constraints) { contents.add(ContentFactory.parseContent(con.getBundleName(), con.getVersionRange().toString())); } } Resolver obrResolver = getConfiguredObrResolver(appName, appVersion.toString(), toModelledResource(app.getBundleInfo()), false); // add a resource describing the requirements of the application metadata. obrResolver.add(createApplicationResource( appName, appVersion, contents)); if (obrResolver.resolve()) { Set<BundleInfo> result = new HashSet<BundleInfo>(); List<Resource> requiredResources = retrieveRequiredResources(obrResolver); for (Resource resource: requiredResources) { BundleInfo bundleInfo = toBundleInfo(resource, false); result.add(bundleInfo); } if (returnOptionalResources) { for (Resource resource: obrResolver.getOptionalResources()) { BundleInfo bundleInfo = toBundleInfo(resource, true); result.add(bundleInfo); } } return result; } else { Reason[] reasons = obrResolver.getUnsatisfiedRequirements(); //refine the list by removing the indirect unsatisfied bundles that are caused by unsatisfied packages or other bundles Map<String,Set<String>> refinedReqs = refineUnsatisfiedRequirements(obrResolver, reasons); StringBuffer reqList = new StringBuffer(); Map<String, String> unsatisfiedRequirements = extractConsumableMessageInfo(refinedReqs); for (String reason : unsatisfiedRequirements.keySet()) { reqList.append('\n'); reqList.append(reason); } ResolverException re = new ResolverException(MessageUtil.getMessage("RESOLVER_UNABLE_TO_RESOLVE", new Object[] { app.getApplicationMetadata().getApplicationName(), reqList })); re.setUnsatisfiedRequirementsAndReasons(unsatisfiedRequirements); log.debug(LOG_EXIT, "resolve", re); throw re; } } @Override public BundleInfo getBundleInfo(String bundleSymbolicName, Version bundleVersion) { Map<String, String> attribs = new HashMap<String, String>(); // bundleVersion is an exact version - so ensure right version filter is generated VersionRange range = ManifestHeaderProcessor.parseVersionRange(bundleVersion.toString(), true); attribs.put(Resource.VERSION, range.toString()); String filterString = ManifestHeaderProcessor.generateFilter(Resource.SYMBOLIC_NAME, bundleSymbolicName, attribs); Resource[] resources; try { resources = repositoryAdmin.discoverResources(filterString); if (resources != null && resources.length > 0) { return toBundleInfo(resources[0], false); } else { return null; } } catch (InvalidSyntaxException e) { log.error("Invalid filter", e); return null; } } /* A 'platform repository' describes capabilities of the target runtime environment * These should be added to the resolver without being listed as coming from a particular * repository or bundle. */ private void addPlatformRepositories (Resolver obrResolver, String appName, PlatformRepository platformRepository) { log.debug(LOG_ENTRY, "addPlatformRepositories", new Object[]{obrResolver, appName}); DataModelHelper helper = repositoryAdmin.getHelper(); if (platformRepository != null) { Collection<URI> uris = platformRepository.getPlatformRepositoryURLs(); if ((uris != null) && (!uris.isEmpty())) { for (URI uri : uris) { InputStream is = null; try { is = uri.toURL().openStream(); Reader repoReader = new InputStreamReader(is); Repository aPlatformRepo = helper.readRepository(repoReader); Resource resources[] = aPlatformRepo.getResources(); for (Resource r : resources) { Capability[] caps = r.getCapabilities(); for (Capability c : caps) { obrResolver.addGlobalCapability(c); } } } catch (Exception e) { // not a big problem log.error(MessageUtil.getMessage("RESOLVER_UNABLE_TO_READ_REPOSITORY_EXCEPTION", new Object[]{appName, uri}) ); } finally { IOUtils.close(is); } } } } log.debug(LOG_EXIT, "addPlatformRepositories"); } private Resource createApplicationResource( String appName, Version appVersion, List<Content> appContent) { return new ApplicationResourceImpl(appName, appVersion, appContent); } private Resource createApplicationResource( String appName, String appVersion, Collection<ImportedBundle> inputs) { return new ApplicationResourceImpl(appName, Version.parseVersion(appVersion), inputs); } private BundleInfo toBundleInfo(Resource resource, boolean optional) { Map<String, String> directives = null; if (optional) { directives = new HashMap<String, String>(); directives.put(Constants.RESOLUTION_DIRECTIVE, Constants.RESOLUTION_OPTIONAL); } return new OBRBundleInfo(resource.getSymbolicName(), resource.getVersion(), resource.getURI(), null, null, null, null, null, null, directives, null); } /** * Get the list of resources returned by the resolver * @param resolver OBR resolver * @return a list of required resources */ protected List<Resource> retrieveRequiredResources(Resolver resolver) { log.debug(LOG_ENTRY,"retrieveRequiredResources", resolver); Map<String, List<Resource>> resourcesByName = new HashMap<String, List<Resource>>(); for (Resource r : resolver.getRequiredResources()) { resourcesByName.put(r.getSymbolicName(), mergeResource(resolver, r, resourcesByName.get(r .getSymbolicName()))); } List<Resource> result = new ArrayList<Resource>(); for (List<Resource> res : resourcesByName.values()) { result.addAll(res); } log.debug(LOG_EXIT, "retrieveRequiredResources", result); return result; } /** * Get rid of the redundant resources * @param resolver OBR resolver * @param r a resource * @param list similar resources * @return the list of minimum resources */ protected List<Resource> mergeResource(Resolver resolver, Resource r, List<Resource> list) { log.debug(LOG_ENTRY, "mergeResource", new Object[]{resolver, r, list}); if (list == null) { log.debug(LOG_EXIT, "mergeResource", Arrays.asList(r)); return Arrays.asList(r); } else { List<Resource> result = new ArrayList<Resource>(); for (Resource old : list) { boolean oldRedundant = satisfiesAll(r, resolver.getReason(old)); boolean newRedundant = satisfiesAll(old, resolver.getReason(r)); if (oldRedundant && newRedundant) { int comp = old.getVersion().compareTo(r.getVersion()); oldRedundant = comp < 0; newRedundant = comp >= 0; } if (newRedundant) { log.debug(LOG_EXIT, "mergeResource", list); return list; } else if (oldRedundant) { // do nothing -> so don't add the old resource to the new list } else { result.add(old); } } result.add(r); log.debug(LOG_EXIT, "mergeResource", result); return result; } } protected boolean satisfiesAll(Resource res, Reason[] reasons) { log.debug(LOG_ENTRY,"satisfiesAll", new Object[] {res, Arrays.toString(reasons)}); //Let's convert the reason to requirement List<Requirement> reqs = new ArrayList<Requirement>(); for (Reason reason : reasons) { reqs.add(reason.getRequirement()); } boolean result = true; outer: for (Requirement r : reqs) { boolean found = false; inner: for (Capability c : res.getCapabilities()) { if (r.isSatisfied(c)) { found = true; break inner; } } if (!!!found && !!!r.isOptional()) { result = false; break outer; } } log.debug(LOG_EXIT, "satisfiesAll", result); return result; } private static final Set<String> SPECIAL_FILTER_ATTRS = Collections .unmodifiableSet(new HashSet<String>(Arrays.asList(ModellingConstants.OBR_PACKAGE, ModellingConstants.OBR_SYMBOLIC_NAME, ModellingConstants.OBR_SERVICE, Constants.VERSION_ATTRIBUTE))); /** * Turn a requirement into a human readable String for debug. * @param filter The filter that is failing * @param bundlesFailing For problems with a bundle, the set of bundles that have a problem * @return human readable form */ private Map<String, String> extractConsumableMessageInfo( Map<String, Set<String>> refinedReqs) { log.debug(LOG_ENTRY, "extractConsumableMessageInfo", refinedReqs); Map<String, String> unsatisfiedRequirements = new HashMap<String, String>(); for (Map.Entry<String, Set<String>> filterEntry : refinedReqs.entrySet()) { String filter = filterEntry.getKey(); Set<String> bundlesFailing = filterEntry.getValue(); log.debug("unable to satisfy the filter , filter = " + filter + "required by " + Arrays.toString(bundlesFailing.toArray())); Map<String, String> attrs = ManifestHeaderProcessor.parseFilter(filter); Map<String, String> customAttrs = new HashMap<String, String>(); for (Map.Entry<String, String> e : attrs.entrySet()) { if (!SPECIAL_FILTER_ATTRS.contains(e.getKey())) { customAttrs.put(e.getKey(), e.getValue()); } } StringBuilder msgKey = new StringBuilder(); List<Object> inserts = new ArrayList<Object>(); final String type; boolean unknownType = false; if (attrs.containsKey(ModellingConstants.OBR_PACKAGE)) { type = ModellingConstants.OBR_PACKAGE; msgKey.append("RESOLVER_UNABLE_TO_RESOLVE_PACKAGE"); inserts.add(attrs.get(ModellingConstants.OBR_PACKAGE)); } else if (attrs.containsKey(ModellingConstants.OBR_SYMBOLIC_NAME)) { type = ModellingConstants.OBR_SYMBOLIC_NAME; msgKey.append("RESOLVER_UNABLE_TO_RESOLVE_BUNDLE"); inserts.add(attrs.get(ModellingConstants.OBR_SYMBOLIC_NAME)); } else if (attrs.containsKey(ModellingConstants.OBR_SERVICE)) { type = ModellingConstants.OBR_SERVICE; msgKey.append("RESOLVER_UNABLE_TO_RESOLVE_SERVICE"); // No insert for service name as the name must be "*" to match any // Service capability } else { type = ModellingConstants.OBR_UNKNOWN; unknownType = true; msgKey.append("RESOLVER_UNABLE_TO_RESOLVE_FILTER"); inserts.add(filter); } if (bundlesFailing != null && bundlesFailing.size() != 0) { msgKey.append("_REQUIRED_BY_BUNDLE"); if (bundlesFailing.size() == 1) inserts.add(bundlesFailing.iterator().next()); // Just take the string // if there's only one // of them else inserts.add(bundlesFailing.toString()); // Add the whole set if there // isn't exactly one } if (!unknownType && !customAttrs.isEmpty()) { msgKey.append("_WITH_ATTRS"); inserts.add(customAttrs); } if (!unknownType && attrs.containsKey(Constants.VERSION_ATTRIBUTE)) { msgKey.append("_WITH_VERSION"); VersionRange vr = ManifestHeaderProcessor.parseVersionRange(attrs .get(Constants.VERSION_ATTRIBUTE)); inserts.add(vr.getMinimumVersion()); if (!!!vr.isExactVersion()) { msgKey.append(vr.isMinimumExclusive() ? "_LOWEX" : "_LOW"); if (vr.getMaximumVersion() != null) { msgKey.append(vr.isMaximumExclusive() ? "_UPEX" : "_UP"); inserts.add(vr.getMaximumVersion()); } } } String msgKeyStr = msgKey.toString(); String msg = MessageUtil.getMessage(msgKeyStr, inserts.toArray()); unsatisfiedRequirements.put(msg, type); } log.debug(LOG_EXIT, "extractConsumableMessageInfo", unsatisfiedRequirements); return unsatisfiedRequirements; } /** * Refine the unsatisfied requirements ready for later human comsumption * * @param resolver The resolver to be used to refine the requirements * @param reasons The reasons * @return A map of the unsatifiedRequirement to the set of bundles that have that requirement unsatisfied (values associated with the keys can be null) */ private Map<String,Set<String>> refineUnsatisfiedRequirements(Resolver resolver, Reason[] reasons) { log.debug(LOG_ENTRY, "refineUnsatisfiedRequirements", new Object[]{resolver, Arrays.toString(reasons)}); Map<Requirement,Set<String>> req_resources = new HashMap<Requirement,Set<String>>(); // add the reasons to the map, use the requirement as the key, the resources required the requirement as the values Set<Resource> resources = new HashSet<Resource>(); for (Reason reason: reasons) { resources.add(reason.getResource()); Requirement key = reason.getRequirement(); String value = reason.getResource().getSymbolicName()+"_" + reason.getResource().getVersion().toString(); Set<String> values = req_resources.get(key); if (values == null) { values = new HashSet<String>(); } values.add(value); req_resources.put(key, values); } // remove the requirements that can be satisifed by the resources. It is listed because the resources are not satisfied by other requirements. // For an instance, the unsatisfied reasons are [package a, required by bundle aa], [package b, required by bundle bb] and [package c, required by bundle cc], // If the bundle aa exports the package a and c. In our error message, we only want to display package a is needed by bundle aa. // Go through each requirement and find out whether the requirement can be satisfied by the reasons. Set<Capability> caps = new HashSet<Capability>(); for (Resource res : resources) { if ((res !=null) && (res.getCapabilities() != null)) { List<Capability> capList = Arrays.asList(res.getCapabilities()); if (capList != null) { caps.addAll(capList); } } } Iterator<Map.Entry<Requirement, Set<String>>> iterator = req_resources.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Requirement, Set<String>> entry = iterator.next(); Requirement req = entry.getKey(); for (Capability cap :caps) { if (req.isSatisfied(cap)){ // remove the key from the map iterator.remove(); break; } } } //Now the map only contains the necessary missing requirements Map<String,Set<String>> result = new HashMap<String, Set<String>>(); for (Map.Entry<Requirement, Set<String>> req_res : req_resources.entrySet()) { result.put(req_res.getKey().getFilter(), req_res.getValue()); } log.debug(LOG_EXIT, "refineUnsatisfiedRequirements", new Object[]{result}); return result; } private Collection<ImportedBundle> toImportedBundle(Collection<Content> content) throws ResolverException { log.debug(LOG_ENTRY, "toImportedBundle", content); List<ImportedBundle> result = new ArrayList<ImportedBundle>(); for (Content c : content) { try { result.add(modellingManager.getImportedBundle(c.getContentName(), c.getVersion().toString())); } catch (InvalidAttributeException iae) { throw new ResolverException(iae); } } log.debug(LOG_EXIT, "toImportedBundle", result); return result; } private Collection<ModelledResource> toModelledResource(Collection<BundleInfo> bundleInfos) throws ResolverException{ Collection<ModelledResource> result = new ArrayList<ModelledResource>(); if ((bundleInfos != null) && (!!!bundleInfos.isEmpty())) { for (BundleInfo bi : bundleInfos) { try { result.add(modellingManager.getModelledResource(null, bi, null, null)); } catch (InvalidAttributeException iae) { throw new ResolverException(iae); } } } return result; } private Repository getLocalRepository(RepositoryAdmin admin) { Repository localRepository = repositoryAdmin.getLocalRepository(); Resource[] resources = localRepository.getResources(); Resource[] newResources = new Resource[resources.length]; for (int i = 0; i < resources.length; i++) { newResources[i] = new ResourceWrapper(resources[i]); } return repositoryAdmin.getHelper().repository(newResources); } private boolean excludeLocalRuntime() { return Boolean.parseBoolean(System.getProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP)); } }
8,877
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/impl/MapToDictionary.java
/* * 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.aries.application.resolver.obr.impl; import java.util.Dictionary; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; /** * @version $Rev$ $Date$ */ public class MapToDictionary extends Dictionary { /** * Map source. */ private final Map m_map; public MapToDictionary(Map map) { m_map = map; } public Enumeration elements() { if (m_map == null) { return null; } return new IteratorToEnumeration(m_map.values().iterator()); } public Object get(Object key) { if (m_map == null) { return null; } return m_map.get(key); } public boolean isEmpty() { if (m_map == null) { return true; } return m_map.isEmpty(); } public Enumeration keys() { if (m_map == null) { return null; } return new IteratorToEnumeration(m_map.keySet().iterator()); } public Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public Object remove(Object key) { throw new UnsupportedOperationException(); } public int size() { if (m_map == null) { return 0; } return m_map.size(); } @Override public String toString() { return m_map != null ? m_map.toString() : "null"; } private static class IteratorToEnumeration implements Enumeration { private final Iterator m_iter; public IteratorToEnumeration(Iterator iter) { m_iter = iter; } public boolean hasMoreElements() { if (m_iter == null) return false; return m_iter.hasNext(); } public Object nextElement() { if (m_iter == null) return null; return m_iter.next(); } } }
8,878
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/impl/RepositoryGeneratorImpl.java
/* * 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.aries.application.resolver.obr.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.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.repository.RepositoryGenerator; import org.apache.aries.application.management.spi.runtime.LocalPlatform; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ModelledResourceManager; import org.apache.aries.application.resolver.obr.ext.BundleResource; import org.apache.aries.application.resolver.obr.ext.BundleResourceTransformer; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.filesystem.FileUtils; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.io.IOUtils; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Property; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resource; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; public final class RepositoryGeneratorImpl implements RepositoryGenerator { private RepositoryAdmin repositoryAdmin; private ModelledResourceManager modelledResourceManager; private LocalPlatform tempDir; private static Logger logger = LoggerFactory.getLogger(RepositoryGeneratorImpl.class); private static Collection<BundleResourceTransformer> bundleResourceTransformers = new ArrayList<BundleResourceTransformer>(); private static final String MANDATORY_DIRECTIVE = Constants.MANDATORY_DIRECTIVE + ":"; public void setModelledResourceManager( ModelledResourceManager modelledResourceManager) { this.modelledResourceManager = modelledResourceManager; } public void setTempDir(LocalPlatform tempDir) { this.tempDir = tempDir; } public void setBundleResourceTransformers (List<BundleResourceTransformer> brts) { bundleResourceTransformers = brts; } public RepositoryGeneratorImpl(RepositoryAdmin repositoryAdmin) { this.repositoryAdmin = repositoryAdmin; } private static void addProperty(Document doc, Element capability, String name, String value, String type) { logger.debug(LOG_ENTRY, "addProperty", new Object[]{doc, capability, name, value, type}); Element p = doc.createElement("p"); p.setAttribute("n", name); p.setAttribute("v", value); if (type != null) p.setAttribute("t", type); capability.appendChild(p); logger.debug(LOG_ENTRY, "addProperty", new Object[]{}); } /** * Write out the resource element * * @param r * resource * @param writer * buffer writer * @throws IOException */ private static void writeResource(Resource r, String uri, Document doc, Element root) throws IOException { logger.debug(LOG_ENTRY, "writeResource", new Object[]{r, uri, doc, root}); Element resource = doc.createElement("resource"); resource.setAttribute(Resource.VERSION, r.getVersion().toString()); resource.setAttribute("uri", r.getURI()); resource.setAttribute(Resource.SYMBOLIC_NAME, r.getSymbolicName()); resource.setAttribute(Resource.ID, r.getSymbolicName() + "/" + r.getVersion()); resource.setAttribute(Resource.PRESENTATION_NAME, r.getPresentationName()); root.appendChild(resource); for (Capability c : r.getCapabilities()) writeCapability(c, doc, resource); for (Requirement req : r.getRequirements()) { writeRequirement(req, doc, resource); } logger.debug(LOG_EXIT, "writeResource"); } /** * Write out the capability * * @param c capability * @param writer buffer writer * @throws IOException */ private static void writeCapability(Capability c, Document doc, Element resource) throws IOException { logger.debug(LOG_ENTRY, "writeCapability", new Object[]{c, doc, resource}); Element capability = doc.createElement("capability"); capability.setAttribute("name", c.getName()); resource.appendChild(capability); Property[] props = c.getProperties(); for (Property entry : props) { String name = (String) entry.getName(); String objectAttrs = entry.getValue(); String type = (entry.getType() == null) ? getType(name) : entry.getType(); // remove the beginning " and tailing " if (objectAttrs.startsWith("\"") && objectAttrs.endsWith("\"")) objectAttrs = objectAttrs.substring(1, objectAttrs.length() - 1); addProperty(doc, capability, name, objectAttrs, type); } logger.debug(LOG_EXIT, "writeCapability"); } /** * write the requirement * * @param req * requirement * @param writer * buffer writer * @throws IOException */ private static void writeRequirement(Requirement req, Document doc, Element resource) throws IOException { logger.debug(LOG_ENTRY, "writeRequirement", new Object[]{req, doc, resource}); Element requirement = doc.createElement("require"); requirement.setAttribute("name", req.getName()); requirement.setAttribute("extend", String.valueOf(req.isExtend())); requirement.setAttribute("multiple", String.valueOf(req.isMultiple())); requirement.setAttribute("optional", String.valueOf(req.isOptional())); requirement.setAttribute("filter", req.getFilter()); requirement.setTextContent(req.getComment()); resource.appendChild(requirement); logger.debug(LOG_EXIT, "writeRequirement"); } public void generateRepository(String repositoryName, Collection<? extends ModelledResource> byValueBundles, OutputStream os) throws ResolverException, IOException { logger.debug(LOG_ENTRY, "generateRepository", new Object[]{repositoryName, byValueBundles, os}); generateRepository(repositoryAdmin, repositoryName, byValueBundles, os); logger.debug(LOG_EXIT, "generateRepository"); } public static void generateRepository (RepositoryAdmin repositoryAdmin, String repositoryName, Collection<? extends ModelledResource> byValueBundles, OutputStream os) throws ResolverException, IOException { logger.debug(LOG_ENTRY, "generateRepository", new Object[]{repositoryAdmin, repositoryName, byValueBundles, os}); Document doc; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException pce) { throw new ResolverException(pce); } Element root = doc.createElement("repository"); root.setAttribute("name", repositoryName); doc.appendChild(root); for (ModelledResource mr : byValueBundles) { BundleResource bundleResource = new BundleResource(mr, repositoryAdmin); if (bundleResourceTransformers.size() > 0) { for (BundleResourceTransformer brt : bundleResourceTransformers) { bundleResource = brt.transform (bundleResource); } } writeResource (bundleResource, mr.getLocation(), doc, root); } try { Transformer trans = TransformerFactory.newInstance().newTransformer(); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.transform(new DOMSource(doc), new StreamResult(os)); } catch (TransformerException te) { logger.debug(LOG_EXIT, "generateRepository", te); throw new ResolverException(te); } logger.debug(LOG_EXIT, "generateRepository"); } private static String getType(String name) { logger.debug(LOG_ENTRY, "getType", new Object[]{name}); String type = null; if (Constants.VERSION_ATTRIBUTE.equals(name) || (Constants.BUNDLE_VERSION_ATTRIBUTE.equals(name))) { type = "version"; } else if (Constants.OBJECTCLASS.equals(name) || MANDATORY_DIRECTIVE.equals(name)) type = "set"; logger.debug(LOG_EXIT, "getType", new Object[]{type}); return type; } public void generateRepository(String[] source, OutputStream fout) throws IOException{ logger.debug(LOG_ENTRY, "generateRepository", new Object[]{source, fout}); List<URI> jarFiles = new ArrayList<URI>(); InputStream in = null; OutputStream out = null; File wstemp = null; Set<ModelledResource> mrs = new HashSet<ModelledResource>(); if (source != null) { try { for (String urlString : source) { // for each entry, we need to find out whether it is in local file system. If yes, we would like to // scan the bundles recursively under that directory URI entry; try { File f = new File(urlString); if (f.exists()) { entry = f.toURI(); } else { entry = new URI(urlString); } if ("file".equals(entry.toURL().getProtocol())) { jarFiles.addAll(FileUtils.getBundlesRecursive(entry)); } else { jarFiles.add(entry); } } catch (URISyntaxException use) { throw new IOException(urlString + " is not a valide uri."); } } for (URI jarFileURI : jarFiles) { String uriString = jarFileURI.toString(); File f = null; if ("file".equals(jarFileURI.toURL().getProtocol())) { f = new File(jarFileURI); } else { int lastIndexOfSlash = uriString.lastIndexOf("/"); String fileName = uriString.substring(lastIndexOfSlash + 1); //we need to download this jar/war to wstemp and work on it URLConnection jarConn = jarFileURI.toURL().openConnection(); in = jarConn.getInputStream(); if (wstemp == null) { wstemp = new File(tempDir.getTemporaryDirectory(), "generateRepositoryXML_" + System.currentTimeMillis()); boolean created = wstemp.mkdirs(); if (created) { logger.debug("The temp directory was created successfully."); } else { logger.debug("The temp directory was NOT created."); } } //Let's open the stream to download the bundles from remote f = new File(wstemp, fileName); out = new FileOutputStream(f); IOUtils.copy(in, out); } IDirectory jarDir = FileSystem.getFSRoot(f); mrs.add(modelledResourceManager.getModelledResource(uriString, jarDir)); } generateRepository("Resource Repository", mrs, fout); } catch (Exception e) { logger.debug(LOG_EXIT, "generateRepository"); throw new IOException(e); } finally { IOUtils.close(in); IOUtils.close(out); if (wstemp != null) { IOUtils.deleteRecursive(wstemp); } } } else { logger.debug("The URL list is empty"); } logger.debug(LOG_EXIT, "generateRepository"); } }
8,879
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/impl/OBRCapability.java
/* * 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.aries.application.resolver.obr.impl; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.application.modelling.Provider; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.DataModelHelper; import org.apache.felix.bundlerepository.Property; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Common code for handling OBR Capabilities. */ public class OBRCapability implements Capability { private Logger logger = LoggerFactory.getLogger(OBRCapability.class); private final Provider _provider; private final RepositoryAdmin repositoryAdmin; /** * Property map for this Capability. */ private final Map<String, Object> _props; /** * Construct a Capability specifying the OBR name to use. * @param type the value to be used for the Capability name in OBR. */ public OBRCapability(Provider provider, RepositoryAdmin repositoryAdmin){ logger.debug(LOG_ENTRY, "OBRCapability", provider); _provider = provider; _props = new HashMap<String, Object>(provider.getAttributes()); this.repositoryAdmin = repositoryAdmin; logger.debug(LOG_EXIT, "OBRCapability"); } public String getName() { logger.debug(LOG_ENTRY, "getName"); String name = _provider.getType().toString(); logger.debug(LOG_EXIT, "getName", name); return name; } public Property[] getProperties() { logger.debug(LOG_ENTRY, "getProperties"); DataModelHelper helper = repositoryAdmin.getHelper(); List<Property> properties = new ArrayList<Property>(); // Felix BundleRepository doesn't appear to correctly cope with String[] value properties // as a result we can't do multi value service properties. OBR doesn't really like implementations // of its interfaces that it didn't generate, but it is a little weird when it does and doesn't. // so we create a Property implemenation which we use to generate the OBR xml for a property which // we then get OBR to parse. This is really convoluted and nasty. for (final Map.Entry<String, Object> entry : _props.entrySet()) { String propXML = helper.writeProperty(new Property() { @Override public String getValue() { Object value = entry.getValue(); if (value instanceof String[]) { String newValue = Arrays.toString((String[])value); value = newValue.substring(1, newValue.length() - 1); } else if (value instanceof Collection) { //We can't rely on Collections having a sensible toString() as it isn't //part of the API (although all base Java ones do). We can use an array //to get consistency String newValue = Arrays.toString(((Collection<?>)value).toArray()); value = newValue.substring(1, newValue.length() - 1); } return String.valueOf(value); } @Override public String getType() { String name = entry.getKey(); String type = null; if (Constants.VERSION_ATTRIBUTE.equals(name) || (Constants.BUNDLE_VERSION_ATTRIBUTE.equals(name))) { type = "version"; } else if (Constants.OBJECTCLASS.equals(name) || (Constants.MANDATORY_DIRECTIVE + ":").equals(name) || entry.getValue() instanceof String[] || entry.getValue() instanceof Collection) type = "set"; return type; } @Override public String getName() { return entry.getKey(); } @Override public Object getConvertedValue() { return null; } }); try { properties.add(helper.readProperty(propXML)); } catch (Exception e) { // Do nothing and hope it OBR doesn't generate XML it can't parse. } } logger.debug(LOG_EXIT, "getProperties", properties); return properties.toArray(new Property[properties.size()]); } public Map getPropertiesAsMap() { logger.debug(LOG_ENTRY, "getPropertiesAsMap"); logger.debug(LOG_ENTRY, "getPropertiesAsMap", new Object[]{_props}); return _props; } }
8,880
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/impl/ResourceWrapper.java
/* * 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.aries.application.resolver.obr.impl; import java.util.Map; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resource; import org.osgi.framework.Version; /** * @version $Rev$ $Date$ */ public class ResourceWrapper implements Resource { private final Resource resource; public ResourceWrapper(Resource resource) { this.resource = resource; } public Capability[] getCapabilities() { return resource.getCapabilities(); } public String[] getCategories() { return resource.getCategories(); } public String getId() { return resource.getId(); } public String getPresentationName() { return resource.getPresentationName(); } public Map getProperties() { return resource.getProperties(); } public Requirement[] getRequirements() { return resource.getRequirements(); } public Long getSize() { return resource.getSize(); } public String getSymbolicName() { return resource.getSymbolicName(); } public String getURI() { return resource.getURI(); } public Version getVersion() { return resource.getVersion(); } public boolean isLocal() { return false; } public String toString() { return resource.toString(); } }
8,881
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/impl/OBRBundleInfo.java
/* * 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.aries.application.resolver.obr.impl; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import org.apache.aries.application.Content; import org.apache.aries.application.management.BundleInfo; import org.osgi.framework.Version; public class OBRBundleInfo implements BundleInfo { private final String symbolicName; private final Version version; private final String location; private final Set<Content> importPackage; private final Set<Content> exportPackage; private final Set<Content> importService; private final Set<Content> exportService; private final Map<String, String> headers; private final Set<Content> requireBundle; private final Map<String, String> attributes; private final Map<String, String> directives; public OBRBundleInfo(String symbolicName, Version version, String location, Set<Content> importPackage, Set<Content> exportPackage, Set<Content> importService, Set<Content> exportService, Set<Content> requireBundle, Map<String, String> attributes, Map<String, String> directives, Map<String, String> headers) { this.symbolicName = symbolicName; this.version = version; this.location = location; this.importPackage = importPackage; this.exportPackage = exportPackage; this.importService = importService; this.exportService = exportService; this.headers = headers; this.requireBundle = requireBundle; this.attributes = attributes; this.directives = directives; } public String getSymbolicName() { return symbolicName; } public Version getVersion() { return version; } public String getLocation() { return location; } public Set<Content> getImportPackage() { return importPackage; } public Set<Content> getExportPackage() { return exportPackage; } public Set<Content> getImportService() { return importService; } public Set<Content> getExportService() { return exportService; } public Map<String, String> getHeaders() { return headers; } public Map<String, String> getBundleAttributes() { return attributes; } public Map<String, String> getBundleDirectives() { return directives; } public Set<Content> getRequireBundle() { return requireBundle; } public String toString() { return symbolicName + "_" + version; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + symbolicName.hashCode(); result = prime * result + version.hashCode(); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) { return false; } OBRBundleInfo other = (OBRBundleInfo) obj; return (symbolicName.equals(other.symbolicName) && version.equals(other.version)); } public Attributes getRawAttributes() { Attributes _attributes = new Attributes(); _attributes.putAll(attributes); _attributes.putAll(directives); return _attributes; } }
8,882
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/impl/ApplicationResourceImpl.java
/* * 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.aries.application.resolver.obr.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Dictionary; import java.util.List; import java.util.Map; import org.apache.aries.application.Content; import org.apache.aries.application.modelling.ImportedBundle; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resource; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.Version; public class ApplicationResourceImpl implements Resource { private String _symbolicName; private Version _version; private List<Requirement> _requirements = new ArrayList<Requirement>(); private static class FilterWrapper implements Filter { private Filter delgate; public FilterWrapper(Filter f) { delgate = f; } public boolean match(ServiceReference reference) { return delgate.match(reference); } public boolean match(Dictionary dictionary) { boolean result = delgate.match(dictionary); return result; } public boolean matchCase(Dictionary dictionary) { return delgate.matchCase(dictionary); } public boolean matches(Map<java.lang.String,?> map) { return delgate.matches(map); } public String toString() { return delgate.toString(); } } public ApplicationResourceImpl(String appName, Version appVersion, List<Content> appContent) { _symbolicName = appName; _version = appVersion; for (int i = 0; i < appContent.size(); i++) { Content c = appContent.get(i); String comment = "Requires " + Resource.SYMBOLIC_NAME + " " + c.getContentName() + " with attributes " + c.getAttributes(); String resolution = c.getDirective("resolution"); boolean optional = Boolean.valueOf(resolution); String f = ManifestHeaderProcessor.generateFilter(Resource.SYMBOLIC_NAME, c.getContentName(), c.getAttributes()); Filter filter; try { filter = FrameworkUtil.createFilter(f); _requirements.add(new RequirementImpl("bundle", new FilterWrapper(filter), false, optional, false, comment)); } catch (InvalidSyntaxException e) { // TODO work out what to do if this happens. If it does our filter generation code is bust. } } } public ApplicationResourceImpl(String appName, Version appVersion, Collection<ImportedBundle> inputs) { _symbolicName = appName; _version = appVersion; for (ImportedBundle match : inputs) { _requirements.add(new RequirementImpl(match)); } } public Capability[] getCapabilities() { return null; } public String[] getCategories() { return null; } public String getId() { return _symbolicName; } public String getPresentationName() { return _symbolicName; } public Map getProperties() { return null; } public Requirement[] getRequirements() { if (_requirements!= null) { Requirement[] reqs = new Requirement[_requirements.size()]; int index =0; for (Requirement req: _requirements) { reqs[index++] = req; } return reqs; } else { return null; } } public String getSymbolicName() { return _symbolicName; } public java.net.URL getURL() { return null; } public Version getVersion() { return _version; } public Long getSize() { return 0l; } public String getURI() { return null; } public boolean isLocal() { return false; } }
8,883
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/impl/RequirementImpl.java
/* * 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.aries.application.resolver.obr.impl; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.Hashtable; import java.util.Map; import org.apache.aries.application.modelling.Consumer; import org.apache.aries.application.utils.FilterUtils; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Requirement; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RequirementImpl implements Requirement { private final Logger logger = LoggerFactory.getLogger(RequirementImpl.class); private final Consumer consumer; private final String name; private final String filter; private final boolean multiple; private final boolean optional; private final boolean extend; private final String comment; public RequirementImpl(String name, Filter filter, boolean multiple, boolean optional, boolean extend, String comment) { this.name = name; this.filter = filter.toString(); this.multiple = multiple; this.optional = optional; this.extend = extend; this.comment = comment; this.consumer = null; } public RequirementImpl(Consumer consumer) { this.consumer = consumer; this.name = getName(); this.filter= getFilter(); this.multiple= isMultiple(); this.optional= isOptional(); this.extend = false; this.comment = getComment(); } public String getComment() { logger.debug(LOG_ENTRY,"getComment" ); if (consumer!= null) { String cleanFilter = FilterUtils.removeMandatoryFilterToken(consumer.getAttributeFilter()); Map<String, String> atts = ManifestHeaderProcessor.parseFilter(cleanFilter); String comment = "Requires " + consumer.getType().toString() + " with attributes " + atts; logger.debug(LOG_EXIT,"getComment", comment ); return comment; } else { logger.debug(LOG_EXIT,"getComment", this.comment ); return this.comment; } } public String getFilter() { String result; if (consumer != null) { result = consumer.getAttributeFilter(); } else { result = this.filter; } return result; } public String getName() { String result; if (consumer != null) { result = consumer.getType().toString(); } else { result = this.name; } return result; } public boolean isExtend() { return this.extend; } public boolean isMultiple() { boolean result; if (consumer != null ) { result = consumer.isMultiple(); } else { result = this.multiple; } return result; } public boolean isOptional() { boolean result; if (consumer != null) { result = consumer.isOptional(); } else { result = this.optional; } return result; } @SuppressWarnings("unchecked") public boolean isSatisfied(Capability cap) { logger.debug(LOG_ENTRY,"isSatisfied", cap ); boolean result = false; String name = getName(); if (name.equals(cap.getName())) { String filterToCreate = getFilter(); try { Filter f = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(filterToCreate)); Hashtable<String, Object> hash = new Hashtable<String, Object>(); Map<String, String> props = cap.getPropertiesAsMap(); if ((props != null) && (!!!props.isEmpty())) { for (Map.Entry<String, String> propertyPair : props.entrySet()) { hash.put(propertyPair.getKey(), propertyPair.getValue()); } } result = f.match(hash); } catch (InvalidSyntaxException e) { logger.error(e.getMessage()); } } logger.debug(LOG_EXIT,"isSatisfied", result ); return result; } }
8,884
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/ext/BundleResource.java
/* * 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.aries.application.resolver.obr.ext; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Map; 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.resolver.obr.impl.OBRCapability; import org.apache.aries.application.resolver.obr.impl.RequirementImpl; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resource; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BundleResource implements Resource { private final ModelledResource _modelledBundle; private final Collection<Capability> _capabilities; private final Collection<Requirement> _requirements; private final String _displayName; private Logger logger = LoggerFactory.getLogger(BundleResource.class); /** * Build a BundleResource from another BundleResource and some optional extra capabilities and requirements * @param br * @param extraCapabilities can be null * @param extraRequirements can be null */ public BundleResource (BundleResource br, Collection<Capability> extraCapabilities, Collection<Requirement> extraRequirements) { _modelledBundle = br._modelledBundle; _capabilities = new ArrayList<Capability> (br._capabilities); _requirements = new ArrayList<Requirement> (br._requirements); _displayName = new String (br._displayName); if (extraCapabilities != null) _capabilities.addAll(extraCapabilities); if (extraRequirements != null) _requirements.addAll(extraRequirements); } public BundleResource (ModelledResource mb, RepositoryAdmin repositoryAdmin) { logger.debug(LOG_ENTRY,"BundleResource", mb); _modelledBundle = mb; _capabilities = new ArrayList<Capability>(); _capabilities.add(new OBRCapability(_modelledBundle.getExportedBundle(), repositoryAdmin)); for (ExportedPackage pkg : _modelledBundle.getExportedPackages()) { _capabilities.add(new OBRCapability(pkg, repositoryAdmin)); } for (ExportedService svc : _modelledBundle.getExportedServices()) { _capabilities.add(new OBRCapability(svc, repositoryAdmin)); } _requirements = new ArrayList<Requirement>(); for (ImportedPackage pkg : _modelledBundle.getImportedPackages()) { _requirements.add(new RequirementImpl(pkg)); } for (ImportedService svc : _modelledBundle.getImportedServices()) { _requirements.add(new RequirementImpl(svc)); } for (ImportedBundle requiredBundle : _modelledBundle.getRequiredBundles()) { _requirements.add(new RequirementImpl(requiredBundle)); } if(mb.isFragment()) _requirements.add(new RequirementImpl(mb.getFragmentHost())); String possibleDisplayName = (String) mb.getExportedBundle().getAttributes().get( ModellingConstants.OBR_PRESENTATION_NAME); if (possibleDisplayName == null) { _displayName = mb.getSymbolicName(); } else { _displayName = possibleDisplayName; } logger.debug(LOG_EXIT,"BundleResource"); } public ModelledResource getModelledResource() { return _modelledBundle; } public Capability[] getCapabilities() { logger.debug(LOG_ENTRY,"getCapabilities"); Capability [] result = _capabilities.toArray(new Capability[_capabilities.size()]); logger.debug(LOG_EXIT,"getCapabilities", result); return result; } public String[] getCategories() { logger.debug(LOG_ENTRY,"getCategories"); logger.debug(LOG_EXIT,"getCategories", null); return null; } public String getId() { logger.debug(LOG_ENTRY,"getId"); String id = _modelledBundle.getSymbolicName() + '/' + _modelledBundle.getVersion(); logger.debug(LOG_EXIT,"getId", id); return id; } public String getPresentationName() { logger.debug(LOG_ENTRY,"getPresentationName"); logger.debug(LOG_EXIT,"getPresentationName", _displayName); return _displayName; } @SuppressWarnings("unchecked") public Map getProperties() { logger.debug(LOG_ENTRY,"getProperties"); logger.debug(LOG_EXIT,"getProperties", null); return null; } public Requirement[] getRequirements() { logger.debug(LOG_ENTRY,"getRequirements"); Requirement [] result = _requirements.toArray(new Requirement[_requirements.size()]); logger.debug(LOG_EXIT,"getRequirements", result); return result; } public String getSymbolicName() { logger.debug(LOG_ENTRY,"getSymbolicName"); String result = _modelledBundle.getSymbolicName(); logger.debug(LOG_EXIT,"getSymbolicName", result); return result; } public URL getURL() { logger.debug(LOG_ENTRY,"getURL"); URL url = null; try { URI uri = new URI(_modelledBundle.getLocation()); url = uri.toURL(); } catch (URISyntaxException e) { logger.error(e.getMessage()); } catch (MalformedURLException e) { logger.error(e.getMessage()); } logger.debug(LOG_EXIT,"getURL", url); return url; } public Version getVersion() { logger.debug(LOG_ENTRY,"getVersion"); Version v = new Version(_modelledBundle.getVersion()); logger.debug(LOG_EXIT,"getVersion", v); return v; } public Long getSize() { logger.debug(LOG_ENTRY,"getSize"); logger.debug(LOG_EXIT,"getSize", 5l); return 5l; } public String getURI() { logger.debug(LOG_ENTRY,"getURI"); String uri = _modelledBundle.getLocation(); logger.debug(LOG_EXIT,"getURI", uri); return uri; } public boolean isLocal() { logger.debug(LOG_ENTRY,"isLocal"); logger.debug(LOG_EXIT,"isLocal", false); return false; } }
8,885
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/ext/ModelledBundleResource.java
/* * 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.resolver.obr.ext; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.apache.aries.application.InvalidAttributeException; 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.ModellingConstants; import org.apache.aries.application.modelling.ModellingManager; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.application.modelling.utils.ModellingHelper; import org.apache.aries.application.resolver.internal.MessageUtil; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Property; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resource; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ModelledBundleResource implements ModelledResource { private final Resource resource; private final ExportedBundle exportedBundle; private final Collection<ImportedPackage> packageRequirements; private final Collection<ImportedService> serviceRequirements; private final Collection<ExportedPackage> packageCapabilities; private final Collection<ExportedService> serviceCapabilties; private final Collection<ImportedBundle> bundleRequirements; private final ResourceType type; private final ModellingManager modellingManager; private final ModellingHelper modellingHelper; private final Logger logger = LoggerFactory.getLogger(ModelledBundleResource.class); public ModelledBundleResource (Resource r, ModellingManager mm, ModellingHelper mh) throws InvalidAttributeException { logger.debug(LOG_ENTRY, "ModelledBundleResource", new Object[]{r, mm, mh}); resource = r; modellingManager = mm; modellingHelper = mh; List<ExportedBundle> exportedBundles = new ArrayList<ExportedBundle>(); ResourceType thisResourceType = ResourceType.BUNDLE; // We'll iterate through our Capabilities a second time below. We do this since we later // build an ExportedPackageImpl for which 'this' is the ModelledResource. for (Capability cap : r.getCapabilities()) { String capName = cap.getName(); if (capName.equals(ResourceType.BUNDLE.toString())) { @SuppressWarnings("unchecked") Property[] props = cap.getProperties(); Map<String,String> sanitizedMap = new HashMap<String, String>(); for(Property entry : props) { sanitizedMap.put(entry.getName(), entry.getValue()); } exportedBundles.add (modellingManager.getExportedBundle(sanitizedMap, modellingHelper.buildFragmentHost( sanitizedMap.get(Constants.FRAGMENT_HOST)))); } else if (cap.getName().equals(ResourceType.COMPOSITE.toString())) { thisResourceType = ResourceType.COMPOSITE; } } type = thisResourceType; if (exportedBundles.size() == 0) { throw new InvalidAttributeException(MessageUtil.getMessage("NO_EXPORTED_BUNDLE", new Object[0])); } else if (exportedBundles.size() == 1) { exportedBundle = exportedBundles.get(0); } else { throw new InvalidAttributeException(MessageUtil.getMessage("TOO_MANY_EXPORTED_BUNDLES", new Object[0])); } packageCapabilities = new HashSet<ExportedPackage>(); packageRequirements = new HashSet<ImportedPackage>(); serviceCapabilties = new HashSet<ExportedService>(); serviceRequirements = new HashSet<ImportedService>(); bundleRequirements = new HashSet<ImportedBundle>(); for (Requirement requirement : r.getRequirements()) { String reqName = requirement.getName(); // Build ImportedPackageImpl, ImportedServiceImpl objects from the Resource's requirments. // Parse the Requirement's filter and remove from the parsed Map all the entries // that we will pass in as explicit parameters to the ImportedServiceImpl or ImportedPackageImpl // constructor. // (This does mean that we remove 'package=package.name' entries but not 'service=service' - // the latter is not very useful :) if (ResourceType.PACKAGE.toString().equals(reqName)) { Map<String, String> filter = ManifestHeaderProcessor.parseFilter(requirement.getFilter()); // Grab and remove the package name, leaving only additional attributes. String name = filter.remove(ResourceType.PACKAGE.toString()); if (requirement.isOptional()) { filter.put(Constants.RESOLUTION_DIRECTIVE + ":", Constants.RESOLUTION_OPTIONAL); } ImportedPackage info = modellingManager.getImportedPackage(name, filter); packageRequirements.add(info); } else if (ResourceType.SERVICE.toString().equals(requirement.getName())) { boolean optional = requirement.isOptional(); String iface; String componentName; String blueprintFilter; String id = null; boolean isMultiple = requirement.isMultiple(); /* It would be much better to pull these keys out of ImportedServiceImpl, * or even values via static methods */ Map<String, String> attrs = ManifestHeaderProcessor.parseFilter(requirement.getFilter()); iface = attrs.get(Constants.OBJECTCLASS); componentName = attrs.get ("osgi.service.blueprint.compname"); blueprintFilter = requirement.getFilter(); ImportedService svc = modellingManager.getImportedService(optional, iface, componentName, blueprintFilter, id, isMultiple); serviceRequirements.add(svc); } else if (ResourceType.BUNDLE.toString().equals(requirement.getName())) { String filter =requirement.getFilter(); Map<String,String> atts = ManifestHeaderProcessor.parseFilter(filter); if (requirement.isOptional()) { atts.put(Constants.RESOLUTION_DIRECTIVE + ":", Constants.RESOLUTION_OPTIONAL); } bundleRequirements.add(modellingManager.getImportedBundle(filter, atts)); } } for (Capability capability : r.getCapabilities()) { Map<String, Object> props = new HashMap<String, Object>(); Property[] properties = capability.getProperties(); for (Property prop : properties) { props.put(prop.getName(), prop.getValue()); } if (ResourceType.PACKAGE.toString().equals(capability.getName())) { // Grab and remove the package name, leaving only additional attributes. Object pkg = props.remove(ResourceType.PACKAGE.toString()); // bundle symbolic name and version will be in additionalProps, so do not // need to be passed in separately. ExportedPackage info = modellingManager.getExportedPackage(this, pkg.toString(), props); packageCapabilities.add(info); } else if (ResourceType.SERVICE.toString().equals(capability.getName())) { String name = null; // we've lost this irretrievably int ranking = 0; Collection<String> ifaces; String rankingText = (String) props.remove(Constants.SERVICE_RANKING); if (rankingText != null) ranking = Integer.parseInt(rankingText); // objectClass may come out as a String or String[] Object rawObjectClass = props.remove (Constants.OBJECTCLASS); if (rawObjectClass == null) { // get it from service ifaces = Arrays.asList((String)props.get(ModellingConstants.OBR_SERVICE)); } else { if (rawObjectClass.getClass().isArray()) { ifaces = Arrays.asList((String[])rawObjectClass); } else { ifaces = Arrays.asList((String)rawObjectClass); } } ExportedService svc = modellingManager.getExportedService(name, ranking, ifaces, props); serviceCapabilties.add(svc); } } logger.debug(LOG_EXIT, "ModelledBundleResource"); } public ExportedBundle getExportedBundle() { logger.debug(LOG_ENTRY, "AbstractExportedBundle"); logger.debug(LOG_EXIT, "AbstractExportedBundle",exportedBundle ); return exportedBundle; } public Collection<? extends ExportedPackage> getExportedPackages() { logger.debug(LOG_ENTRY, "getExportedPackages"); logger.debug(LOG_EXIT, "getExportedPackages", packageCapabilities ); return Collections.unmodifiableCollection(packageCapabilities); } public Collection<? extends ExportedService> getExportedServices() { logger.debug(LOG_ENTRY, "getExportedServices"); logger.debug(LOG_EXIT, "getExportedServices", serviceCapabilties ); return Collections.unmodifiableCollection(serviceCapabilties); } public Collection<? extends ImportedPackage> getImportedPackages() { logger.debug(LOG_ENTRY, "getImportedPackages"); logger.debug(LOG_EXIT, "getImportedPackages", packageRequirements ); return Collections.unmodifiableCollection(packageRequirements); } public Collection<? extends ImportedService> getImportedServices() { logger.debug(LOG_ENTRY, "getImportedServices"); logger.debug(LOG_EXIT, "getImportedServices", serviceRequirements ); return Collections.unmodifiableCollection(serviceRequirements); } public Collection<? extends ImportedBundle> getRequiredBundles() { logger.debug(LOG_ENTRY, "getRequiredBundles"); logger.debug(LOG_EXIT, "getRequiredBundles", bundleRequirements ); return Collections.unmodifiableCollection(bundleRequirements); } public String getSymbolicName() { logger.debug(LOG_ENTRY, "getSymbolicName"); String result = resource.getSymbolicName(); logger.debug(LOG_EXIT, "getSymbolicName", result ); return result; } public String getLocation() { logger.debug(LOG_ENTRY, "getLocation"); logger.debug(LOG_EXIT, "getLocation", resource.getURI()); return resource.getURI(); } public String getVersion() { logger.debug(LOG_ENTRY, "getVersion"); String result = resource.getVersion().toString(); logger.debug(LOG_EXIT, "getVersion", result); return result; } public String toDeploymentString() { logger.debug(LOG_ENTRY, "toDeploymentString"); String result = getSymbolicName() + ";" + AppConstants.DEPLOYMENT_BUNDLE_VERSION + "=" + getVersion(); logger.debug(LOG_EXIT, "toDeploymentString", result); return result; } public String toString() { logger.debug(LOG_ENTRY, "toString"); String result = toDeploymentString() + " uri=" + getLocation(); logger.debug(LOG_EXIT, "toString", result); return result; } public ResourceType getType() { logger.debug(LOG_ENTRY, "getType"); logger.debug(LOG_EXIT, "getType", type); return type; } public ImportedBundle getFragmentHost() { logger.debug(LOG_ENTRY, "getFragmentHost"); ImportedBundle result = exportedBundle.getFragmentHost(); logger.debug(LOG_EXIT, "getFragmentHost", result); return result; } public boolean isFragment() { logger.debug(LOG_ENTRY, "isFragment"); boolean result = exportedBundle.isFragment(); logger.debug(LOG_EXIT, "isFragment", result); return result; } }
8,886
0
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr
Create_ds/aries/application/application-obr-resolver/src/main/java/org/apache/aries/application/resolver/obr/ext/BundleResourceTransformer.java
/** * 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.aries.application.resolver.obr.ext; public interface BundleResourceTransformer { BundleResource transform (BundleResource b); }
8,887
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ImportedServiceImpl.java
/* * 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.modelling.ResourceType.SERVICE; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.regex.Pattern; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.modelling.ImportedService; import org.apache.aries.application.modelling.ModellingConstants; import org.apache.aries.application.modelling.Provider; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.application.modelling.WrappedReferenceMetadata; import org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl; import org.apache.aries.application.utils.FilterUtils; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * an Import-Service entry */ public class ImportedServiceImpl implements ImportedService { private final static String DEPRECATED_FILTER_ATTRIBUTE = "filter"; private final boolean _optional; private final String _iface; private final String _componentName; private final String _blueprintFilter; private final Filter _attributeFilter; private final boolean _isMultiple; private final String _id; private final Map<String, String> _attributes; private String _toString; private String _attribFilterString; // The manner in which we set means it can't be final private final static Pattern SERVICE_EQUALS_SERVICE = Pattern.compile("\\(" + ResourceType.SERVICE.toString() + "=" + ResourceType.SERVICE.toString() + "\\)"); private final Logger logger = LoggerFactory.getLogger(ImportedServiceImpl.class); /** * Build an ImportedServiceImpl from its elements * @param optional * @param iface * @param componentName * @param blueprintFilter * @param id * @param isMultiple * @throws InvalidAttributeException */ public ImportedServiceImpl (boolean optional, String iface, String componentName, String blueprintFilter, String id, boolean isMultiple) throws InvalidAttributeException { _optional = optional; _iface = iface; _componentName = componentName; _blueprintFilter = FilterUtils.removeMandatoryFilterToken(blueprintFilter); _id = id; _isMultiple = isMultiple; _attributes = new HashMap<String, String>(); _attributeFilter = generateAttributeFilter (_attributes); } private Filter generateAttributeFilter (Map<String, String> attrsToPopulate) throws InvalidAttributeException { logger.debug(LOG_ENTRY, "generateAttributeFilter", new Object[]{attrsToPopulate}); Filter result = null; try { attrsToPopulate.put(ModellingConstants.OBR_SERVICE, ModellingConstants.OBR_SERVICE); if (_blueprintFilter != null) { // We may get blueprint filters of the form (&(a=b)(c=d)). We can't put these in 'whole' because we'll // end up generating a filter of the form (&(objectClass=foo)(&(a=b)(c=d)) which subsequent calls to // parseFilter will choke on. So as an interim fix we'll strip off a leading &( and trailing ) if present. String reducedBlueprintFilter; if (_blueprintFilter.startsWith("(&")) { reducedBlueprintFilter = _blueprintFilter.substring(2, _blueprintFilter.length() - 1); } else { reducedBlueprintFilter = _blueprintFilter; } attrsToPopulate.put(ManifestHeaderProcessor.NESTED_FILTER_ATTRIBUTE, reducedBlueprintFilter); } if (_componentName != null) { attrsToPopulate.put ("osgi.service.blueprint.compname", _componentName); } if (_iface != null) { attrsToPopulate.put (Constants.OBJECTCLASS, _iface); } _attribFilterString = ManifestHeaderProcessor.generateFilter(_attributes); if (! "".equals(_attribFilterString)) { result = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(_attribFilterString)); } } catch (InvalidSyntaxException isx) { InvalidAttributeException iax = new InvalidAttributeException( "A syntax error occurred attempting to parse the blueprint filter string '" + _blueprintFilter + "' for element with id " + _id + ": " + isx.getLocalizedMessage(), isx); logger.debug(LOG_EXIT, "generateAttributeFilter", new Object[]{isx}); throw iax; } logger.debug(LOG_EXIT, "generateAttributeFilter", new Object[]{result}); return result; } /** * Deprecated constructor for building these from deprecated Export-Service manifest headers. Do not use this * constructor for any other purpose. * @param ifaceName * @param attributes * @throws InvalidAttributeException */ @Deprecated public ImportedServiceImpl (String ifaceName, Map<String, String> attributes) throws InvalidAttributeException { _optional = ("optional".equals(attributes.get("availability:"))); _iface = ifaceName; _isMultiple = false; _componentName = null; _id = null; _attributes = new HashMap<String, String>(attributes); // The syntax for this deprecated header allows statements of the form, // ImportService: myService;filter="(a=b") _blueprintFilter = _attributes.remove(DEPRECATED_FILTER_ATTRIBUTE); _attributeFilter = generateAttributeFilter (_attributes); } public String getFilter() { logger.debug(LOG_ENTRY, "getFilter"); logger.debug(LOG_EXIT, "getFilter", _blueprintFilter); return _blueprintFilter; } public ResourceType getType() { logger.debug(LOG_ENTRY, "getType"); logger.debug(LOG_EXIT, "getType", ResourceType.SERVICE); return ResourceType.SERVICE; } public boolean isMultiple() { logger.debug(LOG_ENTRY, "isMultiple"); logger.debug(LOG_EXIT, "isMultiple", _isMultiple); return _isMultiple; } public boolean isOptional() { logger.debug(LOG_ENTRY, "isOptional"); logger.debug(LOG_EXIT, "isOptional", _optional); return _optional; } public boolean isSatisfied(Provider capability) { logger.debug(LOG_ENTRY, "isSatisfied", capability); if (capability.getType() != SERVICE) { logger.debug(LOG_EXIT, "isSatisfied", false); return false; } Dictionary<String, Object> dict = new Hashtable<String, Object> (capability.getAttributes()); // If there's a value for ObjectClass, it may be a comma separated list. String objectClass = (String) dict.get(Constants.OBJECTCLASS); if (objectClass != null) { String [] split = objectClass.split (","); dict.put (Constants.OBJECTCLASS, split); } if (_attributeFilter == null) { logger.debug(LOG_EXIT, "isSatisfied", true); return true; } boolean allPresent = ModellingHelperImpl.areMandatoryAttributesPresent_(_attributes, capability); boolean result = allPresent && _attributeFilter.match(dict); logger.debug(LOG_EXIT, "isSatisfied", result); return result; } public String getComponentName() { logger.debug(LOG_ENTRY, "getComponentName"); logger.debug(LOG_EXIT, "getComponentName", _componentName); return _componentName; } public String getId() { logger.debug(LOG_ENTRY, "getId"); logger.debug(LOG_EXIT, "getId", _id); return _id; } public String getInterface() { logger.debug(LOG_ENTRY, "getInterface"); logger.debug(LOG_EXIT, "getInterface", _iface); return _iface; } public boolean isList() { logger.debug(LOG_ENTRY, "isList"); boolean result = isMultiple(); logger.debug(LOG_EXIT, "isList", result); return result; } public String getAttributeFilter() { logger.debug(LOG_ENTRY, "getAttributeFilter"); logger.debug(LOG_EXIT, "getAttributeFilter", _attribFilterString); return _attribFilterString; } @Override public boolean equals (Object o) { boolean equal = false; if (o==null) { equal = false; } else if (o==this) { equal = true; } else if (!(o instanceof WrappedReferenceMetadata)) { equal = false; } else { equal = toString().equals(o.toString()); } return equal; } @Override public int hashCode() { int result = toString().hashCode(); return result; } @Override public String toString() { logger.debug(LOG_ENTRY, "toString"); if (_toString != null) { logger.debug(LOG_EXIT, "toString", _toString); return _toString; } StringBuffer buf = new StringBuffer("<reference>"); buf.append("<componentName>" + _componentName + "</componentName>"); buf.append("<id>" + _id + "</id>"); buf.append("<interface>" + _iface + "</interface>"); buf.append("<isList>" + _isMultiple + "</isList>"); buf.append("<isOptional>" + _optional + "</isOptional>"); // We don't have a method for writing filters in a canonical form buf.append("<filter>" + _blueprintFilter + "</filter>"); _toString = buf.toString(); logger.debug(LOG_EXIT, "toString", _toString); return _toString; } /** * A String suitable for use in DeployedImport-Service */ public String toDeploymentString() { logger.debug(LOG_ENTRY, "toDeploymentString"); String baseFilter = getAttributeFilter(); // We may have one or more (service=service) elements that must be removed. String reducedFilter = SERVICE_EQUALS_SERVICE.matcher(baseFilter).replaceAll(""); // now trim off mandatory:<*service occurrences String result = FilterUtils.removeMandatoryFilterToken(reducedFilter); logger.debug(LOG_EXIT, "toDeploymentString", result); return result; } }
8,888
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ExportedServiceImpl.java
/* * 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.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.TreeSet; import org.apache.aries.application.modelling.ExportedService; import org.apache.aries.application.modelling.ModellingConstants; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.application.modelling.WrappedServiceMetadata; import org.apache.aries.application.utils.service.ExportedServiceHelper; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A service exported by a bundle. Provides an entry to DEPLOYMENT.MF */ public class ExportedServiceImpl implements ExportedService { private final Logger logger = LoggerFactory.getLogger(ExportedServiceImpl.class); private final Map<String, Object> _attributes; private final Collection<String> _interfaces; private final Map<String, Object> _serviceProperties; private final String _name; private final int _ranking; private String _toString = null; /** * Constructor. * @param name "" will be changed to null * @param ranking Service ranking * @param ifaces Interfaces offered by the service * @param serviceProperties Service properties. * We expect that osgi.service.blueprint.compname has been set if possible */ public ExportedServiceImpl (String name, int ranking, Collection<String> ifaces, Map<String, Object> serviceProperties ) { logger.debug(LOG_ENTRY,"ExportedServiceImpl", new Object[]{name, ranking, ifaces}); _interfaces = new TreeSet<String>(ifaces); if (!"".equals(name)) { _name = name; } else { _name = null; } _ranking = ranking; if (serviceProperties == null) { _serviceProperties = new HashMap<String, Object>(); } else { _serviceProperties = new HashMap<String, Object>(serviceProperties); } // Construct _attributes _attributes = new HashMap<String, Object>(_serviceProperties); // Turn interfaces into a comma separated String StringBuilder sb = new StringBuilder(); for (String i : _interfaces) { sb.append(i + ","); } sb = sb.deleteCharAt(sb.length()-1); _attributes.put(Constants.OBJECTCLASS, sb.toString()); _attributes.put (Constants.SERVICE_RANKING, String.valueOf(_ranking)); _attributes.put(ModellingConstants.OBR_SERVICE, ModellingConstants.OBR_SERVICE); logger.debug(LOG_EXIT,"ExportedServiceImpl"); } /** * This constructor is for building ExportedServices from Export-Service manifest headers, * which are deprecated in OSGi. * @param ifaceName * @param attrs */ @Deprecated public ExportedServiceImpl (String ifaceName, Map<String, String> attrs) { logger.debug(LOG_ENTRY,"ExportedServiceImpl", new Object[]{ ifaceName, attrs}); _interfaces = new TreeSet<String> (Arrays.asList(ifaceName)); _ranking = 0; _attributes = new HashMap<String, Object> (attrs); _attributes.put(Constants.OBJECTCLASS, ifaceName); _attributes.put (Constants.SERVICE_RANKING, String.valueOf(_ranking)); _attributes.put(ModellingConstants.OBR_SERVICE, ModellingConstants.OBR_SERVICE); _serviceProperties = new HashMap<String, Object>(); _name = null; logger.debug(LOG_EXIT,"ExportedServiceImpl"); } public Map<String, Object> getAttributes() { logger.debug(LOG_ENTRY,"getAttributes"); logger.debug(LOG_EXIT, "getAttributes", _attributes); return Collections.unmodifiableMap(_attributes); } public ResourceType getType() { logger.debug(LOG_ENTRY,"getType"); logger.debug(LOG_EXIT, "getType", ResourceType.SERVICE); return ResourceType.SERVICE; } public Collection<String> getInterfaces() { logger.debug(LOG_ENTRY,"getInterfaces"); logger.debug(LOG_EXIT, "getInterfaces", _interfaces); return Collections.unmodifiableCollection(_interfaces); } public String getName() { logger.debug(LOG_ENTRY,"getName"); logger.debug(LOG_EXIT, "getName", _name); return _name; } public int getRanking() { logger.debug(LOG_ENTRY,"getRanking"); logger.debug(LOG_EXIT, "getRanking", _ranking); return _ranking; } public Map<String, Object> getServiceProperties() { logger.debug(LOG_ENTRY,"getServiceProperties"); logger.debug(LOG_EXIT, "getServiceProperties", _serviceProperties); return Collections.unmodifiableMap(_serviceProperties); } public int compareTo(WrappedServiceMetadata o) { logger.debug(LOG_ENTRY, "compareTo", o); int result = ExportedServiceHelper.portableExportedServiceCompareTo(this, o); logger.debug(LOG_EXIT,"compareTo", result); return result; } @Override public boolean equals (Object o) { logger.debug(LOG_ENTRY, "equals", o); boolean eq = ExportedServiceHelper.portableExportedServiceEquals(this, o); logger.debug(LOG_EXIT, "equals", eq); return eq; } @Override public int hashCode() { logger.debug(LOG_ENTRY, "hashCode"); int result = ExportedServiceHelper.portableExportedServiceHashCode(this); logger.debug(LOG_EXIT, "hashCode", result); return result; } @Override public String toString() { if (_toString == null) { _toString = ExportedServiceHelper.generatePortableExportedServiceToString(this); } return _toString; } public boolean identicalOrDiffersOnlyByName(WrappedServiceMetadata wsmi) { logger.debug(LOG_ENTRY,"identicalOrDiffersOnlyByName", wsmi); boolean result = ExportedServiceHelper. portableExportedServiceIdenticalOrDiffersOnlyByName(this, wsmi); logger.debug(LOG_EXIT, "identicalOrDiffersOnlyByName", result); return result; } }
8,889
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModelledResourceImpl.java
/* * 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 static org.osgi.framework.Constants.BUNDLE_VERSION_ATTRIBUTE; import static org.osgi.framework.Constants.DYNAMICIMPORT_PACKAGE; import static org.osgi.framework.Constants.EXPORT_PACKAGE; import static org.osgi.framework.Constants.EXPORT_SERVICE; import static org.osgi.framework.Constants.IMPORT_PACKAGE; import static org.osgi.framework.Constants.IMPORT_SERVICE; import static org.osgi.framework.Constants.REQUIRE_BUNDLE; import static org.osgi.framework.Constants.RESOLUTION_DIRECTIVE; import static org.osgi.framework.Constants.RESOLUTION_OPTIONAL; import static org.osgi.framework.Constants.VERSION_ATTRIBUTE; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; 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.ModellingConstants; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.aries.util.manifest.ManifestHeaderProcessor.NameValuePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A model of a bundle or composite. Used for example to supply information to * RepositoryGenerator.generateRepository() * */ public class ModelledResourceImpl implements ModelledResource { private final Logger logger = LoggerFactory.getLogger(ModelledResourceImpl.class); private final String _fileURI; private final Collection<ImportedService> _importedServices; private final Collection<ExportedService> _exportedServices; private final Collection<ExportedPackage> _exportedPackages; private final Collection<ImportedPackage> _importedPackages; private final Collection<ImportedBundle> _requiredBundles; private final ExportedBundle _exportedBundle; private final ResourceType _resourceType; /** * Construct a new {@link ModelledResourceImpl} for the following manifest and services * @param fileURI The location of the bundle, may be null, which indicates a by value bundle * @param bundleInfo The bundle info object * @param importedServices The blueprint references defined by the bundle. May be null * @param exportedServices The blueprint services exported by the bundle. May be null * @throws InvalidAttributeException */ public ModelledResourceImpl (String fileURI, BundleInfo bundleInfo, Collection<ImportedService> importedServices, Collection<ExportedService> exportedServices) throws InvalidAttributeException { this(fileURI, bundleInfo.getRawAttributes(), importedServices, exportedServices); } /** * Construct a new {@link ModelledResourceImpl} for the following manifest and services * @param fileURI The location of the bundle, may be null, which indicates a by value bundle * @param bundleAttributes The bundle manifest, must not be null * @param importedServices The blueprint references defined by the bundle. May be null * @param exportedServices The blueprint services exported by the bundle. May be null * @throws InvalidAttributeException */ @SuppressWarnings("deprecation") public ModelledResourceImpl (String fileURI, Attributes bundleAttributes, ExportedBundle exportedBundle, ResourceType resourceType, Collection<ImportedService> importedServices, Collection<ExportedService> exportedServices) throws InvalidAttributeException { this (fileURI, bundleAttributes, resourceType, exportedBundle, importedServices, exportedServices); logger.debug(LOG_ENTRY, "ModelledResourceImpl", new Object[]{fileURI, bundleAttributes, importedServices, exportedServices}); logger.debug(LOG_EXIT, "ModelledResourceImpl"); } /** * Construct a new {@link ModelledResourceImpl} for the following manifest and services * @param fileURI The location of the bundle, may be null, which indicates a by value bundle * @param bundleAttributes The bundle manifest, must not be null * @param importedServices The blueprint references defined by the bundle. May be null * @param exportedServices The blueprint services exported by the bundle. May be null * @throws InvalidAttributeException */ @SuppressWarnings("deprecation") public ModelledResourceImpl (String fileURI, Attributes bundleAttributes, Collection<ImportedService> importedServices, Collection<ExportedService> exportedServices) throws InvalidAttributeException { this (fileURI, bundleAttributes, ResourceType.BUNDLE, null, importedServices, exportedServices ); logger.debug(LOG_ENTRY, "ModelledResourceImpl", new Object[]{fileURI, bundleAttributes, importedServices, exportedServices}); logger.debug(LOG_EXIT, "ModelledResourceImpl"); } public ModelledResourceImpl (String fileURI, Attributes bundleAttributes, ResourceType resourceType, ExportedBundle exportedBundle, Collection<ImportedService> importedServices, Collection<ExportedService> exportedServices ) throws InvalidAttributeException { logger.debug(LOG_ENTRY, "ModelledResourceImpl", new Object[]{fileURI, bundleAttributes, importedServices, exportedServices, resourceType}); if (exportedBundle == null) { _exportedBundle = new ExportedBundleImpl (bundleAttributes); } else { _exportedBundle = exportedBundle; } _resourceType = resourceType; _fileURI = fileURI; if(importedServices != null) _importedServices = new ArrayList<ImportedService> (importedServices); else _importedServices = new ArrayList<ImportedService>(); if(exportedServices != null) _exportedServices = new ArrayList<ExportedService> (exportedServices); else _exportedServices = new ArrayList<ExportedService>(); _exportedPackages = new ArrayList<ExportedPackage>(); String packageExports = bundleAttributes.getValue(EXPORT_PACKAGE); if (packageExports != null) { List<NameValuePair> exportedPackages = ManifestHeaderProcessor .parseExportString(packageExports); for (NameValuePair exportedPackage : exportedPackages) { _exportedPackages.add(new ExportedPackageImpl(this, exportedPackage.getName(), new HashMap<String, Object>(exportedPackage.getAttributes()))); } } _importedPackages = new ArrayList<ImportedPackage>(); String packageImports = bundleAttributes.getValue(IMPORT_PACKAGE); if (packageImports != null) { Map<String, Map<String, String>> importedPackages = ManifestHeaderProcessor .parseImportString(packageImports); for (Map.Entry<String, Map<String, String>> importedPackage : importedPackages.entrySet()) { Map<String, String> atts = importedPackage.getValue(); _importedPackages.add(new ImportedPackageImpl(importedPackage.getKey(), atts)); } } // Use of Import-Service and Export-Service is deprecated in OSGi. We like Blueprint. // Blueprint is good. String serviceExports = null; if (_resourceType == ResourceType.BUNDLE) { serviceExports = bundleAttributes.getValue(EXPORT_SERVICE); } if (serviceExports != null) { List<NameValuePair> expServices = ManifestHeaderProcessor .parseExportString(serviceExports); for (NameValuePair exportedService : expServices) { _exportedServices.add(new ExportedServiceImpl(exportedService.getName(), exportedService.getAttributes())); } } String serviceImports =null; if (_resourceType == ResourceType.BUNDLE) { serviceImports = bundleAttributes.getValue(IMPORT_SERVICE); } if (serviceImports != null) { Map<String, Map<String, String>> svcImports = ManifestHeaderProcessor .parseImportString(serviceImports); for (Map.Entry<String, Map<String, String>> importedService : svcImports.entrySet()) { _importedServices.add(new ImportedServiceImpl(importedService.getKey(), importedService.getValue())); } } _requiredBundles = new ArrayList<ImportedBundle>(); // Require-Bundle and DynamicImport-Package relevant to Bundles but not Composites if (_resourceType == ResourceType.BUNDLE) { String requireBundleHeader = bundleAttributes.getValue(REQUIRE_BUNDLE); if (requireBundleHeader != null) { Map<String, Map<String, String>> requiredBundles = ManifestHeaderProcessor .parseImportString(requireBundleHeader); for (Map.Entry<String, Map<String, String>> bundle : requiredBundles.entrySet()) { String type = bundle.getKey(); Map<String, String> attribs = bundle.getValue(); // We may parse a manifest with a header like Require-Bundle: bundle.a;bundle-version=3.0.0 // The filter that we generate is intended for OBR in which case we need (version>=3.0.0) and not (bundle-version>=3.0.0) String bundleVersion = attribs.remove(BUNDLE_VERSION_ATTRIBUTE); if (bundleVersion != null && attribs.get(VERSION_ATTRIBUTE) == null) { attribs.put (VERSION_ATTRIBUTE, bundleVersion); } String filter = ManifestHeaderProcessor.generateFilter(ModellingConstants.OBR_SYMBOLIC_NAME, type, attribs); Map<String, String> atts = new HashMap<String, String>(bundle.getValue()); atts.put(ModellingConstants.OBR_SYMBOLIC_NAME, bundle.getKey()); _requiredBundles.add(new ImportedBundleImpl(filter, atts)); } } String dynamicImports = bundleAttributes.getValue(DYNAMICIMPORT_PACKAGE); if (dynamicImports != null) { Map<String, Map<String, String>> dynamicImportPackages = ManifestHeaderProcessor .parseImportString(dynamicImports); for (Map.Entry<String, Map<String, String>> dynImportPkg : dynamicImportPackages.entrySet()) { if (dynImportPkg.getKey().indexOf("*") == -1) { dynImportPkg.getValue().put(RESOLUTION_DIRECTIVE + ":", RESOLUTION_OPTIONAL); _importedPackages.add(new ImportedPackageImpl(dynImportPkg.getKey(), dynImportPkg.getValue())); } } } } logger.debug(LOG_EXIT, "ModelledResourceImpl"); } public String getLocation() { logger.debug(LOG_ENTRY, "getLocation"); logger.debug(LOG_EXIT, "getLocation", _fileURI); return _fileURI; } public ExportedBundle getExportedBundle() { logger.debug(LOG_ENTRY, "getExportedBundle"); logger.debug(LOG_EXIT, "getExportedBundle", _exportedBundle); return _exportedBundle; } public Collection<ExportedPackage> getExportedPackages() { logger.debug(LOG_ENTRY, "getExportedPackages"); logger.debug(LOG_EXIT, "getExportedPackages", _exportedPackages); return Collections.unmodifiableCollection(_exportedPackages); } public Collection<ImportedPackage> getImportedPackages() { logger.debug(LOG_ENTRY, "getImportedPackages"); logger.debug(LOG_EXIT, "getImportedPackages", _importedPackages); return Collections.unmodifiableCollection(_importedPackages); } public Collection<ExportedService> getExportedServices() { logger.debug(LOG_ENTRY, "getExportedServices"); logger.debug(LOG_EXIT, "getExportedServices", _exportedServices); return Collections.unmodifiableCollection(_exportedServices); } public Collection<ImportedService> getImportedServices() { logger.debug(LOG_ENTRY, "getImportedServices"); logger.debug(LOG_EXIT, "getImportedServices", _exportedServices); return Collections.unmodifiableCollection(_importedServices); } public String getSymbolicName() { logger.debug(LOG_ENTRY, "getSymbolicName"); String result = _exportedBundle.getSymbolicName(); logger.debug(LOG_EXIT, "getSymbolicName", result); return result; } public String getVersion() { logger.debug(LOG_ENTRY, "getVersion"); String result = _exportedBundle.getVersion(); logger.debug(LOG_EXIT, "getVersion", result); return result; } public String toDeploymentString() { logger.debug(LOG_ENTRY, "toDeploymentString"); String result = _exportedBundle.toDeploymentString(); logger.debug(LOG_EXIT, "toDeploymentString", result); return result; } public ResourceType getType() { logger.debug(LOG_ENTRY, "getType"); logger.debug(LOG_EXIT, "getType", ResourceType.BUNDLE); return _resourceType; } public String toString() { return toDeploymentString(); } public Collection<ImportedBundle> getRequiredBundles() { logger.debug(LOG_ENTRY, "getRequiredBundles"); logger.debug(LOG_EXIT, "getRequiredBundles", _requiredBundles); return Collections.unmodifiableCollection(_requiredBundles); } public ImportedBundle getFragmentHost() { logger.debug(LOG_ENTRY, "getFragmentHost"); ImportedBundle result = _exportedBundle.getFragmentHost(); logger.debug(LOG_EXIT, "getFragmentHost", result); return result; } public boolean isFragment() { logger.debug(LOG_ENTRY, "isFragment"); boolean result = _exportedBundle.isFragment(); logger.debug(LOG_EXIT, "isFragment", result); return result; } }
8,890
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModellingManagerImpl.java
/* * 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); } }
8,891
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ImportedBundleImpl.java
/* * 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.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.modelling.ImportedBundle; import org.apache.aries.application.modelling.ModellingConstants; import org.apache.aries.application.modelling.Provider; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl; import org.apache.aries.application.utils.FilterUtils; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A model of a Bundle imported, or required, by something. For example, an entry in an APPLICATION.MF. */ public class ImportedBundleImpl implements ImportedBundle { private final Map<String, String> _attributes; private final String _filterString; private final Filter _filter; private final Logger logger = LoggerFactory.getLogger(ImportedBundleImpl.class); /** * Build an ImportedBundleImpl from filter string and a set of attributes. The filter string is * most easily obtained ManifestHeaderProcessor.generateFilter() or Requirement.getFilter() - * be careful if building your own. * @param filterString For example as obtained from Requirement.getFilter() * @param attributes * @throws InvalidAttributeException */ public ImportedBundleImpl(String filterString, Map<String, String> attributes) throws InvalidAttributeException { logger.debug(LOG_ENTRY, "ImportedBundleImpl", new Object[]{filterString, attributes}); _attributes = new HashMap<String, String> (attributes); String versionRange = _attributes.remove(Constants.BUNDLE_VERSION_ATTRIBUTE); if(versionRange == null) { versionRange = Version.emptyVersion.toString(); } if(_attributes.get(Constants.VERSION_ATTRIBUTE) == null) { _attributes.put(Constants.VERSION_ATTRIBUTE, versionRange); } _filterString = filterString; try { _filter = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(_filterString)); } catch (InvalidSyntaxException isx) { InvalidAttributeException iax = new InvalidAttributeException(isx); logger.debug(LOG_EXIT, "ImportedBundleImpl", new Object[]{iax}); throw iax; } logger.debug(LOG_EXIT, "ImportedBundleImpl"); } /** * Build an ImportedBundleImpl from a bundle name and version range. * @param bundleName Bundle symbolic name * @param versionRange Bundle version range * @throws InvalidAttributeException */ public ImportedBundleImpl (String bundleName, String versionRange) throws InvalidAttributeException { logger.debug(LOG_ENTRY, "ImportedBundleImpl", new Object[] {bundleName, versionRange}); _attributes = new HashMap<String, String> (); _attributes.put (ModellingConstants.OBR_SYMBOLIC_NAME, bundleName); _attributes.put (Constants.VERSION_ATTRIBUTE, versionRange); _filterString = ManifestHeaderProcessor.generateFilter(_attributes); try { _filter = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(_filterString)); } catch (InvalidSyntaxException isx) { InvalidAttributeException iax = new InvalidAttributeException(isx); logger.debug(LOG_ENTRY, "ImportedBundleImpl", new Object[] {iax}); throw iax; } logger.debug(LOG_EXIT, "ImportedBundleImpl"); } public String getAttributeFilter() { logger.debug(LOG_ENTRY, "getAttributeFilter"); logger.debug(LOG_EXIT, "getAttributeFilter", new Object[] {_filterString}); return _filterString; } public ResourceType getType() { logger.debug(LOG_ENTRY, "getType"); logger.debug(LOG_EXIT, "getType", new Object[] {ResourceType.BUNDLE}); return ResourceType.BUNDLE; } public boolean isMultiple() { logger.debug(LOG_ENTRY, "isMultiple"); logger.debug(LOG_EXIT, "isMultiple", new Object[] {false}); return false; } public boolean isOptional() { logger.debug(LOG_ENTRY, "isOptional"); boolean optional = false; if (_attributes.containsKey(Constants.RESOLUTION_DIRECTIVE + ":")) { if ((Constants.RESOLUTION_OPTIONAL).equals (_attributes.get(Constants.RESOLUTION_DIRECTIVE + ":"))) { optional = true; } } logger.debug(LOG_EXIT, "isOptional", optional); return optional; } public boolean isSatisfied(Provider capability) { logger.debug(LOG_ENTRY, "isSatisfied", capability); if (capability.getType() != ResourceType.BUNDLE && capability.getType() != ResourceType.COMPOSITE) { logger.debug(LOG_EXIT, "isSatisfied", false); return false; } Dictionary<String, Object> dict = new Hashtable<String, Object> (capability.getAttributes()); String version = (String) dict.get(Constants.VERSION_ATTRIBUTE); if (version != null) { dict.put(Constants.VERSION_ATTRIBUTE, Version.parseVersion(version)); } boolean allPresent = ModellingHelperImpl.areMandatoryAttributesPresent_(_attributes, capability); boolean result = allPresent && _filter.match(dict); logger.debug(LOG_EXIT, "isSatisfied", result); return result; } /** * Get the version range on this bundle import * @return Imported version range, as a string */ public String getVersionRange() { logger.debug(LOG_ENTRY, "getVersionRange"); String range = _attributes.get(Constants.VERSION_ATTRIBUTE); String result = (range == null) ? Version.emptyVersion.toString() : range; logger.debug(LOG_EXIT, "getVersionRange", result); return result; } /** * Get the symbolic name of the imported bundle * @return symbolic name */ public String getSymbolicName() { logger.debug(LOG_ENTRY, "getSymbolicName"); String result = _attributes.get(ModellingConstants.OBR_SYMBOLIC_NAME); logger.debug(LOG_EXIT, "getSymbolicName", result); return result; } /** * Equal if symbolic names match and version strings match */ @Override public boolean equals(Object o) { logger.debug(LOG_ENTRY, "equals", o); boolean result = false; if (o == this) { result = true; } else if (o instanceof ImportedBundleImpl) { ImportedBundleImpl ib = (ImportedBundleImpl)o; result = (getSymbolicName().equals(ib.getSymbolicName()) && getVersionRange().equals(ib.getVersionRange())); } logger.debug(LOG_EXIT, "equals", result); return result; } @Override public int hashCode() { logger.debug(LOG_ENTRY, "hashCode"); int hashCode = getSymbolicName().hashCode() + 31 * getVersionRange().hashCode(); logger.debug(LOG_ENTRY, "hashCode", hashCode); return hashCode; } @Override public String toString() { return _filterString; } }
8,892
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ExportedBundleImpl.java
/* * 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.Collections; import java.util.HashMap; import java.util.Map; import java.util.jar.Attributes; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.modelling.ImportedBundle; import org.apache.aries.application.modelling.ModellingConstants; import org.apache.aries.application.modelling.internal.MessageUtil; import org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An exported bundle: one that I have and make available. */ public class ExportedBundleImpl extends AbstractExportedBundle { private static final Logger logger = LoggerFactory.getLogger(ExportedBundleImpl.class); private final Map<String, Object> _attributes; private final ImportedBundle _fragHost; /** * Construct an ExportedBundleImpl from a processed Manifest * @param attrs * @throws InvalidAttributeException */ public ExportedBundleImpl (Attributes attrs) throws InvalidAttributeException { logger.debug(LOG_ENTRY, "ExportedBundleImpl", attrs); String symbolicName = attrs.getValue(Constants.BUNDLE_SYMBOLICNAME); Map<String,Map<String, String>> map = ManifestHeaderProcessor.parseImportString(symbolicName); //This should have one entry, which is keyed on the symbolicName if(map.size() != 1) { InvalidAttributeException iax = new InvalidAttributeException (MessageUtil.getMessage( "TOO_MANY_SYM_NAMES", new Object[] {symbolicName})); logger.debug(LOG_EXIT, "ExportedBundleImpl", iax); throw iax; } Map.Entry<String, Map<String, String>> entry = map.entrySet().iterator().next(); symbolicName = entry.getKey(); Map<String, String> bundleAttrs = entry.getValue(); String displayName = attrs.getValue(Constants.BUNDLE_NAME); String version = attrs.getValue(Constants.BUNDLE_VERSION); if (version == null) { version = Version.emptyVersion.toString(); } String bmVersion = attrs.getValue(Constants.BUNDLE_MANIFESTVERSION); if (symbolicName == null || bmVersion == null) { InvalidAttributeException iax = new InvalidAttributeException(MessageUtil.getMessage("INCORRECT_MANDATORY_HEADERS", new Object[] {symbolicName, bmVersion})); logger.debug(LOG_EXIT, "ExportedBundleImpl", iax); throw iax; } if(bundleAttrs != null) _attributes = new HashMap<String, Object>(entry.getValue()); else _attributes = new HashMap<String, Object>(); _attributes.put (Constants.BUNDLE_MANIFESTVERSION, bmVersion); _attributes.put(ModellingConstants.OBR_SYMBOLIC_NAME, symbolicName); _attributes.put (Constants.VERSION_ATTRIBUTE, version); if(displayName != null) _attributes.put(ModellingConstants.OBR_PRESENTATION_NAME, displayName); String fragmentHost = attrs.getValue(Constants.FRAGMENT_HOST); if (fragmentHost != null) { _fragHost = ModellingHelperImpl.buildFragmentHost_(fragmentHost); _attributes.put(Constants.FRAGMENT_HOST, fragmentHost); } else { _fragHost = null; } logger.debug(LOG_EXIT, "ExportedBundleImpl"); } /** * Construct a bundle from attributes and a fragment host * @param attributes attributes describing the bundle * @param fragHost may be null if this bundle is not a fragment */ public ExportedBundleImpl(Map<String, String> attributes, ImportedBundle fragHost) { logger.debug(LOG_ENTRY, "ExportedBundleImpl", new Object[]{attributes, fragHost}); _attributes = new HashMap<String, Object>(attributes); _fragHost = fragHost; logger.debug(LOG_EXIT, "ExportedBundleImpl", new Object[]{attributes, fragHost}); } @Override public Map<String, Object> getAttributes() { logger.debug(LOG_ENTRY, "getAttributes"); logger.debug(LOG_EXIT, "getAttributes", new Object[]{_attributes}); return Collections.unmodifiableMap(_attributes); } @Override public String toString() { return _attributes.toString(); } @Override public ImportedBundle getFragmentHost() { logger.debug(LOG_ENTRY, "getFragmentHost"); logger.debug(LOG_EXIT, "getFragmentHost", new Object[]{_fragHost}); return _fragHost; } @Override public boolean isFragment() { logger.debug(LOG_ENTRY, "isFragment"); boolean result = _fragHost != null; logger.debug(LOG_EXIT, "isFragment", new Object[]{result}); return result; } }
8,893
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParserProxyImpl.java
/* * 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.io.InputStream; import java.net.URL; import java.util.List; import org.apache.aries.blueprint.ComponentDefinitionRegistry; import org.apache.aries.blueprint.services.ParserService; import org.osgi.framework.BundleContext; public class ParserProxyImpl extends AbstractParserProxy { private ParserService _parserService; private BundleContext _bundleContext; public void setParserService (ParserService p) { _parserService = p; } public void setBundleContext (BundleContext b) { _bundleContext = b; } @Override protected ComponentDefinitionRegistry parseCDR(List<URL> blueprintsToParse) throws Exception { return _parserService.parse(blueprintsToParse, _bundleContext.getBundle()); } @Override protected ComponentDefinitionRegistry parseCDR(InputStream blueprintToParse) throws Exception { return _parserService.parse(blueprintToParse, _bundleContext.getBundle()); } }
8,894
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/AbstractExportedBundle.java
/* * 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.Map; import org.apache.aries.application.modelling.ExportedBundle; import org.apache.aries.application.modelling.ImportedBundle; import org.apache.aries.application.modelling.ModellingConstants; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.application.utils.AppConstants; import org.osgi.framework.Constants; import org.osgi.framework.Version; abstract class AbstractExportedBundle implements ExportedBundle { /** * Get the exported bundle or composite's manifest attributes * @return attributes extracted from the object's manifest */ public abstract Map<String, Object> getAttributes(); /** * This is always BUNDLE, even for composites. Their compositey-ness is detected * from ModelledResource.getType() */ public final ResourceType getType() { return ResourceType.BUNDLE; } /** * Get the bundle's symbolic name * @return symbolic name */ public String getSymbolicName() { String result = String.valueOf(getAttributes().get(ModellingConstants.OBR_SYMBOLIC_NAME)); return result; } /** * Get the bundle or composite's version * @return version */ public String getVersion () { String result = String.valueOf(getAttributes().get(Constants.VERSION_ATTRIBUTE)); return Version.parseVersion(result).toString(); } public String toDeploymentString() { String result = getSymbolicName() + ";" + AppConstants.DEPLOYMENT_BUNDLE_VERSION + "=" + getVersion(); return result; } /** * Return true if this is a fragment * @return true if this is a fragment */ public abstract boolean isFragment(); /** * If this bundle is a fragment, this method will return the bundle to which it attaches * @return fragment host */ public abstract ImportedBundle getFragmentHost(); }
8,895
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ExportedPackageImpl.java
/* * 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.modelling.ResourceType.PACKAGE; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.aries.application.modelling.ExportedPackage; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ResourceType; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExportedPackageImpl implements ExportedPackage { @SuppressWarnings("deprecation") private static final String PACKAGE_SPECIFICATION_VERSION = Constants.PACKAGE_SPECIFICATION_VERSION; private final Map<String, Object> _attributes; private final String _packageName; private final String _version; private final ModelledResource _bundle; private final Logger logger = LoggerFactory.getLogger(ExportedPackageImpl.class); /** * * @param mr The {@link ModelledResource} exporting this package. Never null. * @param pkg The fully qualified name of the package being exported * @param attributes The package attributes. If no version is present, will be defaulted to 0.0.0. * */ public ExportedPackageImpl (ModelledResource mr, String pkg, Map<String, Object> attributes) { logger.debug(LOG_ENTRY, "ExportedPackageImpl", new Object[]{mr, pkg, attributes}); _attributes = new HashMap<String, Object> (attributes); _packageName = pkg; _attributes.put (PACKAGE.toString(), _packageName); String version = (String) attributes.get(Constants.VERSION_ATTRIBUTE); if (version == null || "".equals(version)) { _version = Version.emptyVersion.toString(); } else { _version = version; } _attributes.put(Constants.VERSION_ATTRIBUTE, _version); _attributes.put (Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE, mr.getSymbolicName()); _attributes.put (Constants.BUNDLE_VERSION_ATTRIBUTE, mr.getVersion()); _bundle = mr; logger.debug(LOG_EXIT, "ExportedPackageImpl"); } public Map<String, Object> getAttributes() { logger.debug(LOG_ENTRY, "getAttributes"); logger.debug(LOG_EXIT, "getAttributes", _attributes); return Collections.unmodifiableMap(_attributes); } public ResourceType getType() { logger.debug(LOG_ENTRY, "getType"); logger.debug(LOG_EXIT, "getType", PACKAGE); return PACKAGE; } /** * Get the name of the exported package * @return package name */ public String getPackageName() { logger.debug(LOG_ENTRY, "getPackageName"); logger.debug(LOG_EXIT, "getPackageName", _packageName); return _packageName; } /** * This will never be null. * @return Version as String, or 0.0.0 */ public String getVersion() { logger.debug(LOG_ENTRY, "getVersion"); logger.debug(LOG_EXIT, "getVersion", _version); return _version; } /** * This method turns an {@link ExportedPackageImpl} into a string suitable for a * Use-Bundle style package import. We do NOT lock down package versions, only bundle versions. */ public String toDeploymentString() { logger.debug(LOG_ENTRY, "toDeploymentString"); StringBuilder sb = new StringBuilder(_packageName); for (Map.Entry<String, Object> entry : _attributes.entrySet()) { String key = entry.getKey(); Object objectValue = entry.getValue(); // While attributes can be arrays, especially for services, they should never be arrays for packages // If the values are not arrays, they are Strings if (!objectValue.getClass().isArray()) { String value = String.valueOf(objectValue); if (key != null && !key.equals(PACKAGE.toString()) && !key.equals(PACKAGE_SPECIFICATION_VERSION)) { if (key.equals(Constants.BUNDLE_VERSION_ATTRIBUTE)) { value = "[" + value + "," + value + "]"; } // No Export-Package directives are valid on Import-Package, so strip out all // directives. Never print out a null or empty key or value. if (key.equals("") || key.endsWith(":") || value==null || value.equals("")) { logger.debug("ExportedPackageImpl.toDeploymentString ignored " + key + "=" + value); } else { sb.append (";").append (key).append("=\"").append(value).append('"'); } } else { logger.debug("ExportedPackageImpl.toDeploymentString() ignoring attribute " + key + "->" + value); } } } String result = sb.toString(); logger.debug(LOG_EXIT, "toDeploymentString", result); return result; } public ModelledResource getBundle() { logger.debug(LOG_ENTRY, "getBundle"); logger.debug(LOG_EXIT, "getBundle", _bundle); return _bundle; } @Override public String toString() { return toDeploymentString(); } @Override public boolean equals(Object thing) { if (thing == this) { return true; } else { if (thing instanceof ExportedPackage) { ExportedPackage otherPackage = (ExportedPackage) thing; if (!this.getPackageName() .equals(otherPackage.getPackageName())) { return false; } if (!this.getVersion().equals(otherPackage.getVersion())) { return false; } if (!this.getPackageName() .equals(otherPackage.getPackageName())) { return false; } // We'll pick up the bundle comparisons in the attributes Map<String, Object> otherAttributes = otherPackage .getAttributes(); if (!attributesAreEqual(otherAttributes)) { return false; } } return true; } } private boolean attributesAreEqual(Map<String, Object> otherAttributes) { // We better have the same number of attributes if (this.getAttributes().size() != otherAttributes.size()) { return false; } for (Entry<String, Object> entry : getAttributes().entrySet()) { String key = entry.getKey(); if (otherAttributes != null && otherAttributes.containsKey(key)) { Object otherValue = otherAttributes.get(key); Object value = entry.getValue(); if (value == null) { if (otherValue != null) { return false; } } else { if (!value.equals(otherValue)) { return false; } } } else { // We insist every value be present on both sides return false; } } return true; } @Override public int hashCode() { return getPackageName().hashCode(); } }
8,896
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ParsedServiceElementsImpl.java
/* * 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); } }
8,897
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ImportedPackageImpl.java
/* * 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.modelling.ModellingConstants.OPTIONAL_KEY; import static org.apache.aries.application.modelling.ResourceType.PACKAGE; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Map.Entry; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.modelling.ExportedPackage; import org.apache.aries.application.modelling.ImportedPackage; import org.apache.aries.application.modelling.Provider; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl; import org.apache.aries.application.utils.FilterUtils; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An imported, or required package. Capable of generating an entry in DEPLOYMENT.MF's Import-Package header. */ public class ImportedPackageImpl implements ImportedPackage { private final boolean _optional; private final String _filterString; private final Filter _filter; private final String _package; private final String _versionRange; private final Map<String,String> _attributes; private final Logger logger = LoggerFactory.getLogger(ImportedPackageImpl.class); /** * Construct a package requirement * @param pkg The name of the required package * @param attributes Other attributes - most commonly, version * @throws InvalidAttributeException */ public ImportedPackageImpl (String pkg, Map<String, String> attributes) throws InvalidAttributeException { logger.debug(LOG_ENTRY, "ImportedPackageImpl", new Object[] {pkg, attributes}); _package = pkg; String versionRange = null; if (attributes != null) { _optional = (Constants.RESOLUTION_OPTIONAL.equals(attributes.get(OPTIONAL_KEY))); versionRange = attributes.get(Constants.VERSION_ATTRIBUTE); _attributes = new HashMap<String, String>(attributes); } else { _optional = false; _attributes = new HashMap<String, String>(); } if (versionRange == null) { _versionRange = Version.emptyVersion.toString(); } else { _versionRange = versionRange; } _attributes.put(Constants.VERSION_ATTRIBUTE, _versionRange); _filterString = ManifestHeaderProcessor.generateFilter(PACKAGE.toString(), _package, _attributes); try { _filter = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(_filterString)); } catch (InvalidSyntaxException isx) { logger.debug(LOG_EXIT, "ImportedPackageImpl", new Object[] {isx}); throw new InvalidAttributeException(isx); } logger.debug(LOG_EXIT, "ImportedPackageImpl"); } /** * Get this ImportedPackageImpl's attributes * @return attributes */ public Map<String, String> getAttributes() { logger.debug(LOG_ENTRY, "getAttributes"); logger.debug(LOG_EXIT, "getAttributes", new Object[] {_attributes}); return Collections.unmodifiableMap(_attributes); } /** * Get the package name * @return package name */ public String getPackageName() { logger.debug(LOG_ENTRY, "getPackageName"); logger.debug(LOG_EXIT, "getPackageName", new Object[] {_package}); return _package; } /** * Get the imported package's version range * @return version range */ public String getVersionRange() { logger.debug(LOG_ENTRY, "getVersionRange"); logger.debug(LOG_EXIT, "getVersionRange", new Object[] {_versionRange}); return _versionRange; } public String getAttributeFilter() { logger.debug(LOG_ENTRY, "getAttributeFilter"); logger.debug(LOG_EXIT, "getAttributeFilter", new Object[] {_filterString}); return _filterString; } public ResourceType getType() { logger.debug(LOG_ENTRY, "getType"); logger.debug(LOG_EXIT, "getType", new Object[] {PACKAGE}); return PACKAGE; } public boolean isMultiple() { logger.debug(LOG_ENTRY, "isMultiple"); logger.debug(LOG_EXIT, "isMultiple", new Object[] {false}); return false; // cannot import a given package more than once } public boolean isOptional() { logger.debug(LOG_ENTRY, "isOptional"); logger.debug(LOG_EXIT, "isOptional", new Object[] {_optional}); return _optional; } public boolean isSatisfied(Provider capability) { logger.debug(LOG_ENTRY, "isSatisfied", new Object[]{capability}); if (capability.getType() != PACKAGE) { logger.debug(LOG_EXIT, "isSatisfied", new Object[] {false}); return false; } Dictionary<String, Object> dict = new Hashtable<String, Object> (capability.getAttributes()); String version = (String) dict.get(Constants.VERSION_ATTRIBUTE); if (version != null) { dict.put(Constants.VERSION_ATTRIBUTE, Version.parseVersion(version)); } boolean allPresent = ModellingHelperImpl.areMandatoryAttributesPresent_(_attributes, capability); boolean result = allPresent && _filter.match(dict); logger.debug(LOG_EXIT, "isSatisfied", new Object[] {result}); return result; } /** * This method turns an {@link ImportedPackageImpl} into a string suitable for a * Provision-Bundle style package import. * It will not include ;bundle-symbolic-name=bundleName;bundle-version=version attribute pairs * @return A String */ @SuppressWarnings("deprecation") public String toDeploymentString() { logger.debug(LOG_ENTRY, "toDeploymentString"); StringBuilder sb = new StringBuilder(_package); // Note that the RESOLUTION_DIRECTIVE is set in this map, so it will be // output automatically. p41 of the OSGi Core Spec v4.2 includes an example // Import-Package with a resolution:=mandatory directive on. We could choose to suppress // resolution:=mandatory on packages however, since mandatory is the default. for (Map.Entry<String, String> entry : _attributes.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (!key.equals(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE) && !key.equals(Constants.BUNDLE_VERSION_ATTRIBUTE) && !key.equals(PACKAGE.toString()) && !key.equals(Constants.PACKAGE_SPECIFICATION_VERSION)) { sb.append(";").append(key).append("=\"").append(value).append('"'); } else { logger.debug("ignoring attribute {" + key + "=" + value + "} in ImportedPackageImpl.toDeploymentString()"); } } String result = sb.toString(); logger.debug(LOG_EXIT, "toDeploymentString", new Object[]{result}); return result; } @Override public String toString() { return toDeploymentString(); } @Override public boolean equals(Object thing) { if (thing == this) { return true; } else { if (thing instanceof ImportedPackage) { ImportedPackage otherPackage = (ImportedPackage) thing; if (!this.getPackageName() .equals(otherPackage.getPackageName())) { return false; } if (!this.getVersionRange().equals(otherPackage.getVersionRange())) { return false; } if (!this.getPackageName() .equals(otherPackage.getPackageName())) { return false; } Map<String, String> otherAttributes = otherPackage .getAttributes(); // Ignore the bundle, since the same package imported from // different bundles should count as the same if (!attributesAreEqual(otherAttributes)) { return false; } } return true; } } private boolean attributesAreEqual(Map<String, String> otherAttributes) { // We better have the same number of attributes if (this.getAttributes().size() != otherAttributes.size()) { return false; } for (Entry<String, String> entry : getAttributes().entrySet()) { String key = entry.getKey(); if (otherAttributes != null && otherAttributes.containsKey(key)) { Object otherValue = otherAttributes.get(key); Object value = entry.getValue(); if (value == null) { if (otherValue != null) { return false; } } else { if (!value.equals(otherValue)) { return false; } } } else { // We insist every value be present on both sides return false; } } return true; } @Override public int hashCode() { return getPackageName().hashCode(); } }
8,898
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/ModelledResourceManagerImpl.java
/* * 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.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.security.AccessController; import java.security.PrivilegedAction; 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 java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; 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.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.ServiceModeller; import org.apache.aries.application.modelling.internal.BundleBlueprintParser; import org.apache.aries.application.modelling.internal.MessageUtil; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.filesystem.ICloseableDirectory; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; import org.apache.aries.util.io.IOUtils; import org.apache.aries.util.manifest.BundleManifest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ModelledResourceManagerImpl implements ModelledResourceManager { private final Logger _logger = LoggerFactory.getLogger(ModelledResourceManagerImpl.class); private ParserProxy _parserProxy; private ModellingManager _modellingManager; private Collection<ServiceModeller> modellingPlugins; public void setModellingPlugins(Collection<ServiceModeller> modellingPlugins) { this.modellingPlugins = modellingPlugins; } 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 */ public ParsedServiceElements getServiceElements (IDirectory archive) throws ModellerException { BundleManifest bm = BundleManifest.fromBundle(archive); return getServiceElements(bm, archive); } public ParsedServiceElements getServiceElements(InputStreamProvider archive) throws ModellerException { ICloseableDirectory dir = null; try { dir = FileSystem.getFSRoot(archive.open()); BundleManifest bm = BundleManifest.fromBundle(dir); return getServiceElements(bm, dir); } catch (IOException e) { throw new ModellerException(e); } finally { IOUtils.close(dir); } } private ParsedServiceElements getServiceElements (BundleManifest bundleMf, IDirectory archive) throws ModellerException { Set<ExportedService> services = new HashSet<ExportedService>(); Set<ImportedService> references = new HashSet<ImportedService>(); try { ParsedServiceElements pse = getBlueprintServiceElements(bundleMf, findBlueprints(bundleMf, archive)); services.addAll(pse.getServices()); references.addAll(pse.getReferences()); for (ServiceModeller sm : modellingPlugins) { pse = sm.modelServices(bundleMf, archive); services.addAll(pse.getServices()); references.addAll(pse.getReferences()); } return new ParsedServiceElementsImpl(services, references); } catch (Exception e) { throw new ModellerException(e); } } private ParsedServiceElements getBlueprintServiceElements (BundleManifest bundleMf, Iterable<InputStream> blueprints) throws ModellerException { _logger.debug(LOG_ENTRY,"getServiceElements", new Object[] {bundleMf, blueprints} ); Set<ExportedService> services = new HashSet<ExportedService>(); Set<ImportedService> references = new HashSet<ImportedService>(); try { for (InputStream is : blueprints) { try { ParsedServiceElements pse = getParserProxy().parseAllServiceElements(is); services.addAll(pse.getServices()); references.addAll(pse.getReferences()); } finally { IOUtils.close(is); } } } 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; } public ModelledResource getModelledResource(IDirectory bundle) throws ModellerException { try { return getModelledResource(bundle.toURL().toURI().toString(), bundle); } catch (MalformedURLException mue) { throw new ModellerException(mue); } catch (URISyntaxException use) { throw new ModellerException(use); } } public ModelledResource getModelledResource(String uri, InputStreamProvider bundle) throws ModellerException { ICloseableDirectory dir = null; try { dir = FileSystem.getFSRoot(bundle.open()); return getModelledResource(uri, dir); } catch (IOException e) { throw new ModellerException(e); } finally { IOUtils.close(dir); } } public ModelledResource getModelledResource(String uri, IDirectory bundle) throws ModellerException{ _logger.debug(LOG_ENTRY, "getModelledResource", new Object[]{uri, bundle}); if (bundle != null) { BundleManifest bm = BundleManifest.fromBundle(bundle); ParsedServiceElements pse = getServiceElements(bm, bundle); return model(uri, bm, pse); } else { // The bundle does not exist ModellerException me = new ModellerException(MessageUtil.getMessage("INVALID_BUNDLE_LOCATION", bundle)); _logger.debug(LOG_EXIT, "getModelledResource", me); throw me; } } private ModelledResource model(String uri, BundleManifest bm, ParsedServiceElements pse) throws ModellerException { Attributes attributes = bm.getRawAttributes(); ModelledResource mbi = null; try { mbi = _modellingManager.getModelledResource(uri, attributes, pse.getReferences(), pse.getServices()); } catch (InvalidAttributeException iae) { ModellerException me = new ModellerException(iae); _logger.debug(LOG_EXIT, "getModelledResource", me); throw me; } _logger.debug(LOG_EXIT, "getModelledResource", mbi); return mbi; } /** * Helper method to pass a single bundle into findBlueprints * @param bundleMf The bundle manifest * @param oneBundle a single bundle * @return Files for all the blueprint files within the bundle * @throws URISyntaxException * @throws IOException */ private Iterable<InputStream> findBlueprints(BundleManifest bundleMf, IDirectory bundle) throws IOException { _logger.debug(LOG_ENTRY, "findBlueprints", bundle); Collection<IFile> blueprints = new ArrayList<IFile>(); BundleBlueprintParser bpParser = new BundleBlueprintParser(bundleMf); /* OSGi R5 Spec, section 121.3.4: "If the Bundle-Blueprint header is specified but empty, then the Blueprint * bundle must not be managed. This can be used to temporarily disable a Blueprint bundle." */ if (bpParser.mightContainBlueprint()) { List<IFile> files = bundle.listAllFiles(); Iterator<IFile> it = files.iterator(); while (it.hasNext()) { IFile file = it.next(); String directoryFullPath = file.getName(); String directoryName = ""; String fileName = ""; if (directoryFullPath.lastIndexOf("/") != -1) { // This bundle may be nested within another archive. In that case, we need to trim // /bundleFileName.jar from the front of the directory. int bundleNameLength = bundle.getName().length(); directoryName = directoryFullPath.substring(bundleNameLength, directoryFullPath.lastIndexOf("/")); if (directoryName.startsWith("/") && directoryName.length() > 1) { directoryName = directoryName.substring(1); } fileName = directoryFullPath.substring(directoryFullPath.lastIndexOf("/") + 1); } else { if (file.isFile()) { directoryName=""; fileName = directoryFullPath; } } if (!file.isDirectory() && bpParser.isBPFile(directoryName, fileName)) { blueprints.add(file); } } } Collection<InputStream> result = new ArrayList<InputStream>(); try { for (IFile bp : blueprints) result.add(bp.open()); } catch (IOException e) { // if something went wrong, make sure we still clean up for (InputStream is : result) IOUtils.close(is); throw e; } _logger.debug(LOG_EXIT, "findBlueprints", result); return result; } private class ZipBlueprintIterator implements Iterator<InputStream> { private final ZipInputStream zip; private final BundleBlueprintParser bpParser; private boolean valid; public ZipBlueprintIterator(ZipInputStream zip, BundleBlueprintParser bpParser) { this.zip = zip; this.bpParser = bpParser; } public boolean hasNext() { valid = false; ZipEntry entry; try { while (!valid && (entry = zip.getNextEntry()) != null) { if (!entry.isDirectory()) { String name = entry.getName(); String directory = ""; int index = name.lastIndexOf('/'); if (index != -1) { directory = name.substring(0, index); name = name.substring(index+1); } if (bpParser.isBPFile(directory, name)) { valid = true; } } } } catch (IOException e) { _logger.error("Could not open next zip entry", e); } return valid; } public InputStream next() { if (!valid) throw new IllegalStateException(); return new InputStream() { public int read() throws IOException { return zip.read(); } @Override public void close() { // intercept close so that the zipinputstream stays open } }; } public void remove() { throw new UnsupportedOperationException(); } } /** * Internal use only. Different to the general Iterable interface this can return an Iterator only once. */ private Iterable<InputStream> findBlueprints(BundleManifest bundleMf, InputStream stream) { final BundleBlueprintParser bpParser = new BundleBlueprintParser(bundleMf); final ZipInputStream zip = new ZipInputStream(stream); return new Iterable<InputStream>() { public Iterator<InputStream> iterator() { return new ZipBlueprintIterator(zip, bpParser); } }; } }
8,899