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-modeller/src/main/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/impl/AbstractParserProxy.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.impl; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.modelling.ExportedService; import org.apache.aries.application.modelling.ImportedService; import org.apache.aries.application.modelling.ModellingManager; import org.apache.aries.application.modelling.ParsedServiceElements; import org.apache.aries.application.modelling.ParserProxy; import org.apache.aries.application.modelling.WrappedServiceMetadata; import org.apache.aries.blueprint.ComponentDefinitionRegistry; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.service.blueprint.reflect.BeanArgument; import org.osgi.service.blueprint.reflect.BeanMetadata; import org.osgi.service.blueprint.reflect.BeanProperty; import org.osgi.service.blueprint.reflect.CollectionMetadata; import org.osgi.service.blueprint.reflect.ComponentMetadata; import org.osgi.service.blueprint.reflect.MapEntry; import org.osgi.service.blueprint.reflect.MapMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.osgi.service.blueprint.reflect.RefMetadata; import org.osgi.service.blueprint.reflect.ReferenceListMetadata; import org.osgi.service.blueprint.reflect.ReferenceListener; import org.osgi.service.blueprint.reflect.RegistrationListener; import org.osgi.service.blueprint.reflect.ServiceMetadata; import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata; import org.osgi.service.blueprint.reflect.Target; import org.osgi.service.blueprint.reflect.ValueMetadata; import org.osgi.service.jndi.JNDIConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; abstract public class AbstractParserProxy implements ParserProxy { private final Logger _logger = LoggerFactory.getLogger(AbstractParserProxy.class); private ModellingManager _modellingManager; protected abstract ComponentDefinitionRegistry parseCDR(List<URL> blueprintsToParse) throws Exception; protected abstract ComponentDefinitionRegistry parseCDR(InputStream blueprintToParse) throws Exception; public void setModellingManager (ModellingManager m) { _modellingManager = m; } public List<? extends WrappedServiceMetadata> parse(List<URL> blueprintsToParse) throws Exception { _logger.debug(LOG_ENTRY, "parse", new Object[]{blueprintsToParse}); ComponentDefinitionRegistry cdr = parseCDR (blueprintsToParse); List<? extends WrappedServiceMetadata> result = parseCDRForServices (cdr, true); _logger.debug(LOG_EXIT, "parse", new Object[]{result}); return result; } public List<? extends WrappedServiceMetadata> parse(URL blueprintToParse) throws Exception { _logger.debug(LOG_ENTRY, "parse", new Object[]{blueprintToParse}); List<URL> list = new ArrayList<URL>(); list.add(blueprintToParse); List<? extends WrappedServiceMetadata> result = parse (list); _logger.debug(LOG_EXIT, "parse", new Object[]{result}); return result; } public List<? extends WrappedServiceMetadata> parse(InputStream blueprintToParse) throws Exception { _logger.debug(LOG_ENTRY, "parse", new Object[]{blueprintToParse}); ComponentDefinitionRegistry cdr = parseCDR (blueprintToParse); List<? extends WrappedServiceMetadata> result = parseCDRForServices (cdr, true); _logger.debug(LOG_EXIT, "parse", new Object[]{result}); return result; } public ParsedServiceElements parseAllServiceElements(InputStream blueprintToParse) throws Exception { _logger.debug(LOG_ENTRY, "parseAllServiceElements", new Object[]{blueprintToParse}); ComponentDefinitionRegistry cdr = parseCDR (blueprintToParse); Collection<ExportedService> services = parseCDRForServices(cdr, false); Collection<ImportedService> references = parseCDRForReferences (cdr); ParsedServiceElements result = _modellingManager.getParsedServiceElements(services, references); _logger.debug(LOG_EXIT, "parseAllServiceElements", new Object[]{result}); return result; } /** * Extract Service metadata from a ComponentDefinitionRegistry. When doing SCA modelling, we * need to suppress anonymous services. We don't want to do that when we're modelling for * provisioning dependencies. * @param cdr ComponentDefinitionRegistry * @param suppressAnonymousServices Unnamed services will not be returned if this is true * @return List<WrappedServiceMetadata> */ private List<ExportedService> parseCDRForServices (ComponentDefinitionRegistry cdr, boolean suppressAnonymousServices) { _logger.debug(LOG_ENTRY, "parseCDRForServices", new Object[]{cdr, suppressAnonymousServices}); List<ExportedService> result = new ArrayList<ExportedService>(); for (ComponentMetadata compMetadata : findAllComponents(cdr)) { if (compMetadata instanceof ServiceMetadata) { ServiceMetadata serviceMetadata = (ServiceMetadata)compMetadata; String serviceName; int ranking; Collection<String> interfaces = new ArrayList<String>(); Map<String, Object> serviceProps = new HashMap<String, Object>(); ranking = serviceMetadata.getRanking(); for (Object i : serviceMetadata.getInterfaces()) { interfaces.add((String)i); } // get the service properties List<MapEntry> props = serviceMetadata.getServiceProperties(); for (MapEntry entry : props) { String key = ((ValueMetadata)entry.getKey()).getStringValue(); Metadata value = entry.getValue(); if (value instanceof CollectionMetadata) { processMultiValueProperty(serviceProps, key, value); } else { serviceProps.put(key, ((ValueMetadata)entry.getValue()).getStringValue()); } } // serviceName: use the service id unless that's not set, // in which case we use the bean id. serviceName = serviceMetadata.getId(); // If the Service references a Bean, export the bean id as a service property // as per 121.6.5 p669 of the blueprint 1.0 specification Target t = serviceMetadata.getServiceComponent(); String targetId = null; if (t instanceof RefMetadata) { targetId = ((RefMetadata)t).getComponentId(); } else if (t instanceof BeanMetadata) { targetId = ((BeanMetadata)t).getId(); } // Our OBR code MUST have access to targetId if it's available (i.e. not null // or auto-generated for an anonymous service. This must ALWAYS be set. if (targetId != null && !targetId.startsWith(".")) { // Don't set this for anonymous inner components serviceProps.put("osgi.service.blueprint.compname", targetId); if (serviceName == null || serviceName.equals("") || serviceName.startsWith(".")) { serviceName = targetId; } } if(serviceName != null && serviceName.startsWith(".")) serviceName = null; // If suppressAnonymous services, do not expose services that have no name if (!suppressAnonymousServices || (serviceName != null)) { ExportedService wsm = _modellingManager.getExportedService(serviceName, ranking, interfaces, serviceProps); result.add(wsm); } } } _logger.debug(LOG_EXIT, "parseAllServiceElements", new Object[]{result}); return result; } private void processMultiValueProperty(Map<String, Object> serviceProps, String key, Metadata value) { List<Metadata> values = ((CollectionMetadata)value).getValues(); Class<?> collectionClass = ((CollectionMetadata)value).getCollectionClass(); Object collectionValue; if(Collection.class.isAssignableFrom(collectionClass)) { Collection<String> theseValues = getCollectionFromClass(collectionClass); for(Metadata m : values) { theseValues.add(((ValueMetadata)m).getStringValue()); } collectionValue = theseValues; } else { String[] theseValues = new String[values.size()]; for (int i=0; i < values.size(); i++) { Metadata m = values.get(i); theseValues[i] = ((ValueMetadata)m).getStringValue(); } collectionValue = theseValues; } serviceProps.put(key, collectionValue); } private Collection<String> getCollectionFromClass(Class<?> collectionClass) { if(List.class.isAssignableFrom(collectionClass)) { return new ArrayList<String>(); } else if (Set.class.isAssignableFrom(collectionClass)) { return new LinkedHashSet<String>(); } else if (Queue.class.isAssignableFrom(collectionClass)) { //This covers Queue and Deque, which is caught by the isAssignableFrom check //as a sub-interface of Queue return new LinkedList<String>(); } else { throw new IllegalArgumentException(collectionClass.getName()); } } /** * Extract References metadata from a ComponentDefinitionRegistry. * @param cdr ComponentDefinitionRegistry * @return List<WrappedReferenceMetadata> * @throws InvalidAttributeException */ private List<ImportedService> parseCDRForReferences (ComponentDefinitionRegistry cdr) throws InvalidAttributeException { _logger.debug(LOG_ENTRY, "parseCDRForReferences", new Object[]{cdr}); List<ImportedService> result = new ArrayList<ImportedService>(); for (ComponentMetadata compMetadata : findAllComponents(cdr)) { if (compMetadata instanceof ServiceReferenceMetadata) { ServiceReferenceMetadata referenceMetadata = (ServiceReferenceMetadata)compMetadata; boolean optional = referenceMetadata.getAvailability() == ServiceReferenceMetadata.AVAILABILITY_OPTIONAL; String iface = referenceMetadata.getInterface(); String compName = referenceMetadata.getComponentName(); String blueprintFilter = referenceMetadata.getFilter(); String id = referenceMetadata.getId(); boolean isMultiple = (referenceMetadata instanceof ReferenceListMetadata); //The blueprint parser teams up with JPA and blueprint resource ref // namespace handlers to give us service imports of the form, // objectClass=javax.persistence.EntityManagerFactory, org.apache.aries.jpa.proxy.factory=*, osgi.unit.name=blabber // // There will be no matching service for this reference. // For now we blacklist certain objectClasses and filters - this is a pretty dreadful thing to do. if (!isBlacklisted (iface, blueprintFilter)) { ImportedService ref = _modellingManager.getImportedService (optional, iface, compName, blueprintFilter, id, isMultiple); result.add (ref); } } } _logger.debug(LOG_EXIT, "parseCDRForReferences", new Object[]{result}); return result; } /** * Find all the components in a given {@link ComponentDefinitionRegistry} this finds top-level * components as well as their nested counter-parts. It may however not find components in custom namespacehandler * {@link ComponentMetadata} instances. * * @param cdr The {@link ComponentDefinitionRegistry} to scan * @return a {@link Set} of {@link ComponentMetadata} */ private Set<ComponentMetadata> findAllComponents(ComponentDefinitionRegistry cdr) { Set<ComponentMetadata> components = new HashSet<ComponentMetadata>(); for (String name : cdr.getComponentDefinitionNames()) { ComponentMetadata component = cdr.getComponentDefinition(name); traverseComponent(component, components); } return components; } /** * Traverse to find all nested {@link ComponentMetadata} instances * @param metadata * @param output */ private void traverse(Metadata metadata, Set<ComponentMetadata> output) { if (metadata instanceof ComponentMetadata) { traverseComponent((ComponentMetadata) metadata, output); } else if (metadata instanceof CollectionMetadata) { CollectionMetadata collection = (CollectionMetadata) metadata; for (Metadata v : collection.getValues()) traverse(v, output); } else if (metadata instanceof MapMetadata) { MapMetadata map = (MapMetadata) metadata; for (MapEntry e : map.getEntries()) { traverse(e.getKey(), output); traverse(e.getValue(), output); } } } /** * Traverse {@link ComponentMetadata} instances to find all nested {@link ComponentMetadata} instances * @param component * @param output */ private void traverseComponent(ComponentMetadata component, Set<ComponentMetadata> output) { if (!!!output.add(component)) return; if (component instanceof BeanMetadata) { BeanMetadata bean = (BeanMetadata) component; traverse(bean.getFactoryComponent(), output); for (BeanArgument argument : bean.getArguments()) { traverse(argument.getValue(), output); } for (BeanProperty property : bean.getProperties()) { traverse(property.getValue(), output); } } else if (component instanceof ServiceMetadata) { ServiceMetadata service = (ServiceMetadata) component; traverse(service.getServiceComponent(), output); for (RegistrationListener listener : service.getRegistrationListeners()) { traverse(listener.getListenerComponent(), output); } for (MapEntry e : service.getServiceProperties()) { traverse(e.getKey(), output); traverse(e.getValue(), output); } } else if (component instanceof ServiceReferenceMetadata) { ServiceReferenceMetadata reference = (ServiceReferenceMetadata) component; for (ReferenceListener listener : reference.getReferenceListeners()) { traverse(listener.getListenerComponent(), output); } } } /** * Some services are injected directly into isolated frameworks by default. We do * not need to model these services. They are not represented as ExportedServices * (Capabilities) in the various OBR registries, and so cannot be resolved against. * Since they are injected directly into each isolated framework, we do not need * an entry in DEPLOYMENT.MF's Deployed-ImportService header for any of these * services. * * @param iface The interface declared on a blueprint reference * @param blueprintFilter The filter on the blueprint reference * @return True if the service is not 'blacklisted' and so may be exposed * in the model being generated. */ protected boolean isBlacklisted (String iface, String blueprintFilter) { _logger.debug(LOG_ENTRY, "isBlacklisted", new Object[]{iface, blueprintFilter}); boolean blacklisted = false; if (iface != null) { // JPA - detect interface; blacklisted |= iface.equals("javax.persistence.EntityManagerFactory"); blacklisted |= iface.equals("javax.persistence.EntityManager"); // JTA - detect interface blacklisted |= iface.equals("javax.transaction.UserTransaction"); blacklisted |= iface.equals("javax.transaction.TransactionSynchronizationRegistry"); // ConfigurationAdmin - detect interface blacklisted |= iface.equals("org.osgi.service.cm.ConfigurationAdmin"); // Don't provision against JNDI references if (blueprintFilter != null && blueprintFilter.trim().length() != 0) { Map<String, String> filter = ManifestHeaderProcessor.parseFilter(blueprintFilter); blacklisted |= filter.containsKey(JNDIConstants.JNDI_SERVICENAME); } } _logger.debug(LOG_EXIT, "isBlacklisted", new Object[]{!blacklisted}); return blacklisted; } }
8,900
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/DeployedBundlesImpl.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.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.management.ResolverException; import org.apache.aries.application.modelling.DeployedBundles; import org.apache.aries.application.modelling.DeploymentMFElement; 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.internal.MessageUtil; import org.apache.aries.application.modelling.internal.PackageRequirementMerger; import org.apache.aries.application.utils.AppConstants; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class to generate DEPLOYMENT.MF manifest entries for resolved bundles based on * corresponding APPLICATION.MF entries. */ public final class DeployedBundlesImpl implements DeployedBundles { private final Logger logger = LoggerFactory.getLogger(DeployedBundlesImpl.class); private final String assetName; private String cachedImportPackage; private Collection<ModelledResource> cachedRequiredUseBundle; private Collection<ImportedPackage> cachedExternalRequirements; private String cachedDeployedImportService; /** Content from APPLICATION.MF */ private final Set<ImportedBundle> appContent = new HashSet<ImportedBundle>(); /** Use Bundle from APPLICATION.MF */ private final Set<ImportedBundle> appUseBundle = new HashSet<ImportedBundle>(); /** Content for deployment.mf deployed-content. */ private final Set<ModelledResource> deployedContent = new HashSet<ModelledResource>(); /** Content for deployment.mf use-bundle. */ private final Set<ModelledResource> deployedUseBundle = new HashSet<ModelledResource>(); /** Content for deployment.mf provision-bundle. */ private final Set<ModelledResource> deployedProvisionBundle = new HashSet<ModelledResource>(); /** Content for deployment.mf DeployedImport-Service. */ private final Collection<ImportedService> deployedImportService = new HashSet<ImportedService>(); private final Collection<ModelledResource> fakeDeployedBundles = new HashSet<ModelledResource>(); /** * Constructor for cases when we have one or more ' * @param assetName the name of the asset being deployed. * @param appContentNames the bundle names specified in Deployed-Content. * @param appUseBundleNames the bundle names specified in Deployed-Use-Bundle. * @param fakeServiceProvidingBundles bundles that we're pretending are part of the deployed content. Can be null. * These bundles are proxies for bundles provided (for example by SCA) that export * services matching Application-ImportService. */ public DeployedBundlesImpl(String assetName, Collection<ImportedBundle> appContentNames, Collection<ImportedBundle> appUseBundleNames, Collection<ModelledResource> fakeServiceProvidingBundles) { logger.debug(LOG_ENTRY, "DeployedBundles", new Object[]{appContentNames, appUseBundleNames, fakeServiceProvidingBundles}); this.assetName = assetName; appContent.addAll(appContentNames); appUseBundle.addAll(appUseBundleNames); if (fakeServiceProvidingBundles != null) { fakeDeployedBundles.addAll(fakeServiceProvidingBundles); } logger.debug(LOG_EXIT, "DeployedBundles"); } /** * Add provisioned version information for a specific bundle name. This will be added to the * appropriate manifest header for the specified bundle. * @param resolvedBundle the bundle that has been provisioned. * @param resolvedVersion the specific version provisioned. */ public void addBundle(ModelledResource modelledBundle) { logger.debug(LOG_ENTRY, "addBundle", new Object[]{modelledBundle}); // Identify the deployment.mf entries the bundle should be added to by matching // both the bundle name and resolved version against the name and version range // defined in application.mf. ExportedBundle resolvedBundle = modelledBundle.getExportedBundle(); if (isBundleMatch(appContent, resolvedBundle)) { logger.debug("Added to " + AppConstants.DEPLOYMENT_CONTENT + ": " + resolvedBundle); deployedContent.add(modelledBundle); // Add any service dependencies to the list deployedImportService.addAll(modelledBundle.getImportedServices()); } else if (isBundleMatch(appUseBundle, resolvedBundle)) { logger.debug("Added to " + AppConstants.DEPLOYMENT_USE_BUNDLE + ": " + resolvedBundle); deployedUseBundle.add(modelledBundle); } else { logger.debug("Added to " + AppConstants.DEPLOYMENT_PROVISION_BUNDLE + ": " + resolvedBundle); deployedProvisionBundle.add(modelledBundle); } // Invalidate caches cachedImportPackage = null; cachedRequiredUseBundle = null; cachedDeployedImportService = null; cachedExternalRequirements = null; logger.debug(LOG_EXIT, "addBundle"); } /** * Check if a match is found between the supplied map of application bundle name/version information, * and the supplied bundle name and version. * @param imports Imported bundles * @param potentialMatch the exported bundle or composite we're interested in * @return true if a match is found; otherwise false. */ private boolean isBundleMatch(Set<ImportedBundle> imports, ExportedBundle potentialMatch) { boolean result = false; for (ImportedBundle ib : imports) { if (ib.isSatisfied(potentialMatch)) { result = true; break; } } return result; } /** * 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. */ public String getContent() { return createManifestString(deployedContent); } /** * 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. */ public String getUseBundle() { return createManifestString(deployedUseBundle); } /** * 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. */ public String getProvisionBundle() { return createManifestString(deployedProvisionBundle); } /** * 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. */ public String getImportPackage() throws ResolverException { logger.debug(LOG_ENTRY, "getImportPackage"); String result = cachedImportPackage; if (result == null) { Collection<ImportedPackage> externalReqs = new ArrayList<ImportedPackage>(getExternalPackageRequirements()); //Validate that we don't have attributes that will break until RFC138 is used validateOtherImports(externalReqs); // Find the matching capabilities from bundles in use bundle, and prune // matched requirements out of the external requirements collection. Map<ImportedPackage,ExportedPackage> useBundlePkgs = new HashMap<ImportedPackage,ExportedPackage>(); for (Iterator<ImportedPackage> iter = externalReqs.iterator(); iter.hasNext(); ) { ImportedPackage req = iter.next(); ExportedPackage match = getPackageMatch(req, deployedUseBundle); if (match != null) { useBundlePkgs.put(req, match); iter.remove(); } } StringBuilder useBundleImports = new StringBuilder(); for(Map.Entry<ImportedPackage, ExportedPackage> entry : useBundlePkgs.entrySet()) { useBundleImports.append(entry.getValue().toDeploymentString()); ImportedPackage key = entry.getKey(); if(key.isOptional()) useBundleImports.append(";" + Constants.RESOLUTION_DIRECTIVE +":=" + Constants.RESOLUTION_OPTIONAL); useBundleImports.append(","); } result = useBundleImports.toString() + createManifestString(externalReqs); if(result.endsWith(",")) result = result.substring(0, result.length() - 1); cachedImportPackage = result; } logger.debug(LOG_EXIT, "getImportPackage", result); return result; } /** * 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 * */ public String getDeployedImportService() { logger.debug(LOG_ENTRY,"getDeployedImportService"); String result = cachedDeployedImportService; if (result == null) { Collection<ImportedService> deployedBundleServiceImports = new ArrayList<ImportedService>(); Collection<ExportedService> servicesExportedWithinIsolatedContent = new ArrayList<ExportedService>(); for (ModelledResource mRes : getDeployedContent()) { servicesExportedWithinIsolatedContent.addAll(mRes.getExportedServices()); } for (ModelledResource mRes : fakeDeployedBundles) { servicesExportedWithinIsolatedContent.addAll(mRes.getExportedServices()); } for (ImportedService impService : deployedImportService) { if (impService.isMultiple()) { deployedBundleServiceImports.add(impService); } else { boolean serviceProvidedWithinIsolatedContent = false; Iterator<ExportedService> it = servicesExportedWithinIsolatedContent.iterator(); while (!serviceProvidedWithinIsolatedContent && it.hasNext()) { ExportedService svc = it.next(); serviceProvidedWithinIsolatedContent |= impService.isSatisfied(svc); } if (!serviceProvidedWithinIsolatedContent) { deployedBundleServiceImports.add(impService); } } } result = createManifestString(deployedBundleServiceImports); cachedDeployedImportService = result; } logger.debug(LOG_EXIT,"getDeployedImportService", result); return result; } /** * Get all the requirements of bundles in deployed content that are not satisfied * by other bundles in deployed content. * @return a collection of package requirements. * @throws ResolverException if the requirements could not be resolved. */ private Collection<ImportedPackage> getExternalPackageRequirements() throws ResolverException { logger.debug(LOG_ENTRY,"getExternalPackageRequirements"); Collection<ImportedPackage> result = cachedExternalRequirements; if (result == null) { // Get all the internal requirements. Collection<ImportedPackage> requirements = new ArrayList<ImportedPackage>(); Collection<ExportedPackage> internalExports = new ArrayList<ExportedPackage>(); for (ModelledResource bundle : deployedContent) { requirements.addAll(bundle.getImportedPackages()); internalExports.addAll(bundle.getExportedPackages()); } // Filter out requirements satisfied by internal capabilities. result = new ArrayList<ImportedPackage>(); for (ImportedPackage req : requirements) { boolean satisfied = false; for (ExportedPackage export : internalExports) { if (req.isSatisfied(export)) { satisfied = true; break; } } //If we didn't find a match then it must come from outside if (!satisfied) result.add(req); } PackageRequirementMerger merger = new PackageRequirementMerger(result); if (!merger.isMergeSuccessful()) { List<String> pkgNames = new ArrayList<String>(merger.getInvalidRequirements()); StringBuilder buff = new StringBuilder(); for (String pkgName : merger.getInvalidRequirements()) { buff.append(pkgName).append(", "); } int buffLen = buff.length(); String pkgString = (buffLen > 0 ? buff.substring(0, buffLen - 2) : ""); ResolverException re = new ResolverException(MessageUtil.getMessage( "INCOMPATIBLE_PACKAGE_VERSION_REQUIREMENTS", new Object[] { assetName, pkgString })); re.setUnsatisfiedRequirements(pkgNames); logger.debug(LOG_EXIT,"getExternalPackageRequirements", re); throw re; } result = merger.getMergedRequirements(); cachedExternalRequirements = result; } logger.debug(LOG_EXIT,"getExternalPackageRequirements", result); return result; } /** * Create entries for the Import-Package header corresponding to the supplied * packages, referring to bundles not in Use-Bundle. * @param requirements packages for which entries should be created. * @return manifest header entries. * @throws ResolverException if the imports are invalid. */ private void validateOtherImports(Collection<ImportedPackage> requirements) throws ResolverException { logger.debug(LOG_ENTRY, "validateOtherImports", requirements); for (ImportedPackage req : requirements) { String pkgName = req.getPackageName(); for (String name : req.getAttributes().keySet()) { if (Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE.equals(name) || Constants.BUNDLE_VERSION_ATTRIBUTE.equals(name)) { ResolverException re = new ResolverException(MessageUtil.getMessage( "INVALID_PACKAGE_REQUIREMENT_ATTRIBUTES", new Object[] { assetName, name, pkgName })); re.setUnsatisfiedRequirements(Arrays.asList(pkgName)); logger.debug(LOG_EXIT, "validateOtherImports", re); throw re; } } } logger.debug(LOG_EXIT, "validateOtherImports"); } /** * Get a package match between the specified requirement and a capability of the supplied * bundles. The resulting match object might not refer to any matching capability. * @param requirement the {@link ImportedPackageImpl} to be matched. * @param bundles the bundles to be searched for matching capabilities. * @return an ExportedPackageImpl or null if no match is found. */ private ExportedPackage getPackageMatch(ImportedPackage requirement, Collection<ModelledResource> bundles) { logger.debug(LOG_ENTRY, "getPackageMatch", new Object[]{requirement, bundles}); ExportedPackage result = null; outer: for (ModelledResource bundle : bundles) { for (ExportedPackage pkg : bundle.getExportedPackages()) { if(requirement.isSatisfied(pkg)) { result = pkg; break outer; } } } logger.debug(LOG_EXIT, "getPackageMatch", new Object[]{result}); return result; } private String createManifestString(Collection<? extends DeploymentMFElement> values) { logger.debug(LOG_ENTRY, "createManifestString", new Object[]{values}); StringBuilder builder = new StringBuilder(); for (DeploymentMFElement value : values) { builder.append(value.toDeploymentString()).append(","); } int length = builder.length(); String result = (length > 0 ? builder.substring(0, length - 1) : ""); logger.debug(LOG_EXIT, "createManifestString", new Object[]{result}); return result; } @Override public String toString() { return AppConstants.DEPLOYMENT_CONTENT + '=' + deployedContent + ' ' + AppConstants.DEPLOYMENT_USE_BUNDLE + '=' + deployedUseBundle + ' ' + AppConstants.DEPLOYMENT_PROVISION_BUNDLE + '=' + deployedProvisionBundle; } /** * Get the set of bundles that are going to be deployed into an isolated framework * @return a set of bundle metadata */ public Collection<ModelledResource> getDeployedContent() { logger.debug(LOG_ENTRY, "getDeployedContent"); logger.debug(LOG_EXIT,"getDeployedContent", deployedContent); return Collections.unmodifiableCollection(deployedContent); } /** * 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. * */ public Collection<ModelledResource> getDeployedProvisionBundle () { logger.debug(LOG_ENTRY,"getDeployedProvisionBundle"); logger.debug(LOG_EXIT, "getDeployedProvisionBundle", deployedContent); return Collections.unmodifiableCollection(deployedProvisionBundle); } /** * 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. */ public Collection<ModelledResource> getRequiredUseBundle() throws ResolverException { logger.debug(LOG_ENTRY, "getRequiredUseBundle"); Collection<ModelledResource> usedUseBundles = cachedRequiredUseBundle; if (usedUseBundles == null) { Collection<ImportedPackage> externalReqs = getExternalPackageRequirements(); usedUseBundles = new HashSet<ModelledResource>(); for (ImportedPackage req : externalReqs) { // Find a match from the supplied bundle capabilities. ExportedPackage match = getPackageMatch(req, deployedUseBundle); if (match != null) { usedUseBundles.add(match.getBundle()); } } cachedRequiredUseBundle = usedUseBundles; } logger.debug(LOG_EXIT, "getRequiredUseBundle", usedUseBundles); return usedUseBundles; } /** This method will be overridden by a PostResolveTransformer returning an extended version of * DeployedBundles */ public Map<String, String> getExtraHeaders() { logger.debug (LOG_ENTRY, "getExtraHeaders"); Map<String, String> result = Collections.emptyMap(); logger.debug (LOG_EXIT, "getExtraHeaders", result); return result; } }
8,901
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/internal/PackageRequirementMerger.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.internal; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.aries.application.modelling.ImportedPackage; import org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A class to merge collections of package requirements, such that multiple requirements * for the same package are consolidated to a single requirement with a version constraint * that is the intersection of the original version requirements. */ public final class PackageRequirementMerger { private final Logger logger = LoggerFactory.getLogger(PackageRequirementMerger.class); /** The merged requirements, or null if the merge failed. */ private final Collection<ImportedPackage> mergedRequirements; /** Names of packages for which requirements were incompatible. */ private final Set<String> invalidRequirements = new HashSet<String>(); /** * Constructor. * @param requirements the package requirements to be merged. * @throws NullPointerException if the parameter is {@code null}. */ public PackageRequirementMerger(Collection<ImportedPackage> requirements) { logger.debug(LOG_ENTRY, "PackageRequirementMerger", requirements); if (requirements == null) { NullPointerException npe = new NullPointerException(); logger.debug(LOG_EXIT, "PackageRequirementMerger", npe); throw npe; } // Do the merge. Map<String, ImportedPackage> reqMap = new HashMap<String, ImportedPackage>(); for (ImportedPackage req : requirements) { String pkgName = req.getPackageName(); ImportedPackage existingReq = reqMap.get(pkgName); if (existingReq == null) { reqMap.put(pkgName, req); continue; } ImportedPackage intersectReq = ModellingHelperImpl.intersectPackage_(req, existingReq); if (intersectReq != null) { reqMap.put(pkgName, intersectReq); continue; } invalidRequirements.add(pkgName); } mergedRequirements = (invalidRequirements.isEmpty() ? reqMap.values() : null); logger.debug(LOG_EXIT,"PackageRequirementMerger"); } /** * Check if the requirements could be successfully merged. * @return true if the merge was successful; false if the requirements were not compatible. */ public boolean isMergeSuccessful() { logger.debug(LOG_ENTRY, "isMergeSuccessful"); boolean result = mergedRequirements != null; logger.debug(LOG_EXIT, "isMergeSuccessful", result); return result; } /** * Get the merged package requirements. The result will mirror the input collection, * except that multiple requirements for the same package will be replaced by a single * requirement that is the intersection of all the input requirements. * <p> * The {@code isMergeSuccessful} method should be checked for success prior to calling this method. * @param inputRequirements * @return A collection of package requirements, or {@code null} if the input contained incompatible requirements. * @throws IllegalStateException if the merge was not successful. */ public Collection<ImportedPackage> getMergedRequirements() { logger.debug(LOG_ENTRY, "getMergedRequirements"); if (mergedRequirements == null) { IllegalStateException ise = new IllegalStateException(); logger.debug(LOG_EXIT, "getMergedRequirements", ise); throw ise; } logger.debug(LOG_EXIT, "getMergedRequirements", mergedRequirements); return Collections.unmodifiableCollection(mergedRequirements); } /** * Get the names of packages that caused the merge to fail due to their constraints * being mutually exclusive. * @return an unmodifiable set of package names. */ public Set<String> getInvalidRequirements() { logger.debug(LOG_ENTRY, "getInvalidRequirements"); logger.debug(LOG_EXIT, "getInvalidRequirements", invalidRequirements); return Collections.unmodifiableSet(invalidRequirements); } }
8,902
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/internal/BundleBlueprintParser.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.internal; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; import org.apache.aries.util.manifest.BundleManifest; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.aries.application.utils.AppConstants.*; /** * A bundle may contain a Bundle-Blueprint: header as per p649 of the v4 spec. If present, * this denotes where to look for blueprint xml files. We could use Bundle.findEntries() * to deal with the wildcards that the last entry in the list may contain, but our caller * is introspecting .jar files within an EBA and does not have access to Bundle objects, * so we need this extra support. Our caller needs to iterate over the files * within a jar in each case asking this class, 'is this a blueprint file'? * */ public class BundleBlueprintParser { public static final String DEFAULT_HEADER = "OSGI-INF/blueprint/*.xml"; private static final Logger logger = LoggerFactory.getLogger(BundleBlueprintParser.class); String _mfHeader = null; List<Path> _paths; static class Path { String directory; String filename; // This will either be a simple filename or 'null', in which case filenamePattern will be set Pattern filenamePattern; public Path (String d, String f) { directory = d; if (f.contains("*")) { filename = null; String pattern = f.replace(".", "\\."); pattern = pattern.replace("*", ".*"); filenamePattern = Pattern.compile(pattern); } else { filename = f; filenamePattern = null; } } /** * Match this Path object against a specific directory, file pair. Case sensitive. * @param dir Directory * @param fil Filename - may not contain a wildcard * @return true these match */ public boolean matches (String dir, String fil) { boolean match = false; if (!directory.equals(dir)) { match = false; } else if (filename != null) { match = (filename.equals(fil)); } else { match = filenamePattern.matcher(fil).matches(); } return match; } } /** * BundleBlueprintParser constructor * @param bundleMf BundleManifest to construct the parser from */ public BundleBlueprintParser (BundleManifest bundleMf) { String bundleBPHeader = bundleMf.getRawAttributes().getValue("Bundle-Blueprint"); setup (bundleBPHeader); } /** * BundleBlueprintParser alternative constructor * @param bundleBPHeader Bundle-Blueprint header to construct the parser from */ public BundleBlueprintParser (String bundleBPHeader) { setup (bundleBPHeader); } /** * Default constructor */ public BundleBlueprintParser () { setup(null); } static final boolean _blueprintHeaderMandatory; static { String blueprintHeaderMandatory = AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return System.getProperty("org.apache.aries.blueprint.header.mandatory", "false"); } }); _blueprintHeaderMandatory = blueprintHeaderMandatory.toLowerCase().equals("true"); } /** * @return true if this bundle might contain blueprint files */ public boolean mightContainBlueprint() { return _mfHeader != null && _mfHeader.trim().length() > 0; } private void setup (String bundleBPHeader) { _paths = new LinkedList <Path>(); if (bundleBPHeader == null) { if (_blueprintHeaderMandatory) { _mfHeader = null; } else { _mfHeader = DEFAULT_HEADER; } } else { _mfHeader = bundleBPHeader; } logger.debug("Bundle-Blueprint header: {}", _mfHeader); // Break this comma separated list up List<String> files = ManifestHeaderProcessor.split(_mfHeader, ","); clauses: for (String fileClause : files) { // we could be doing directives, so we split again, the clause can // have multiple paths with directives at the end. List<String> yetMoreFiles = ManifestHeaderProcessor.split(fileClause, ";"); for (String f : yetMoreFiles) { // if f has an = in it then we have hit the directive, which must // be at the end, we do not have any directives so we just continue // onto the next clause. if (f.contains("=")) continue clauses; // we need to make sure we have zero spaces here, otherwise stuff may // not be found. f = f.trim(); if (f.startsWith("\"") && f.endsWith("\"")) { f = f.substring(1,f.length()-1); } int index = f.lastIndexOf('/'); String path = ""; String file = f; if (index != -1) { path = f.substring(0, index); file = f.substring(index + 1); } _paths.add(new Path(path, file)); } } } /** * Iterate through the list of valid file patterns. Return true if this matches against * the header provided to the constructor. We're going to have to be case sensitive. * @param directory Directory name * @param filename File name * @return true if this is a blueprint file according to the Bundle-Blueprint header */ public boolean isBPFile (String directory, String filename) { logger.debug(LOG_ENTRY, "isBPFile", new Object[] {directory, filename}); boolean result=false; for (Path path: _paths) { if (path.matches(directory, filename)) { result = true; break; } } logger.debug(LOG_EXIT, "isBPFile", result); return result; } }
8,903
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/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.modelling.internal; import java.text.MessageFormat; import java.util.ResourceBundle; public class MessageUtil { /** The resource bundle for blueprint messages */ private final static ResourceBundle messages = ResourceBundle.getBundle("org.apache.aries.application.modelling.messages.APPModellingMessages"); /** * Resolve a message from the bundle, including any necessary formatting. * * @param key the message key. * @param inserts any required message inserts. * @return the message translated into the server local. */ public static final String getMessage(String key, Object ... inserts) { String msg = messages.getString(key); if (inserts.length > 0) msg = MessageFormat.format(msg, inserts); return msg; } }
8,904
0
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/utils
Create_ds/aries/application/application-modeller/src/main/java/org/apache/aries/application/modelling/utils/impl/ModellingHelperImpl.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.utils.impl; import static org.apache.aries.application.modelling.ModellingConstants.OPTIONAL_KEY; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import static org.osgi.framework.Constants.BUNDLE_VERSION_ATTRIBUTE; import static org.osgi.framework.Constants.VERSION_ATTRIBUTE; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.modelling.DeployedBundles; import org.apache.aries.application.modelling.ImportedBundle; import org.apache.aries.application.modelling.ImportedPackage; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ModellingConstants; import org.apache.aries.application.modelling.Provider; import org.apache.aries.application.modelling.impl.DeployedBundlesImpl; import org.apache.aries.application.modelling.impl.ImportedBundleImpl; import org.apache.aries.application.modelling.impl.ImportedPackageImpl; import org.apache.aries.application.modelling.internal.MessageUtil; import org.apache.aries.application.modelling.utils.ModellingHelper; import org.apache.aries.util.VersionRange; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ModellingHelperImpl implements ModellingHelper { private static final Logger logger = LoggerFactory.getLogger(ModellingHelperImpl.class); public boolean areMandatoryAttributesPresent( Map<String, String> consumerAttributes, Provider p) { return areMandatoryAttributesPresent_(consumerAttributes, p); } public ImportedBundle buildFragmentHost(String fragmentHostHeader) throws InvalidAttributeException { return buildFragmentHost_(fragmentHostHeader); } public ImportedPackage intersectPackage(ImportedPackage p1, ImportedPackage p2) { return intersectPackage_(p1, p2); } public DeployedBundles createDeployedBundles(String assetName, Collection<ImportedBundle> appContentNames, Collection<ImportedBundle> appUseBundleNames, Collection<ModelledResource> fakeServiceProvidingBundles) { logger.debug(LOG_ENTRY, "createDeployedBundles", new Object[]{assetName, appContentNames, appUseBundleNames, fakeServiceProvidingBundles}); DeployedBundles result = new DeployedBundlesImpl (assetName, appContentNames, appUseBundleNames, fakeServiceProvidingBundles); logger.debug(LOG_EXIT, "createDeployedBundles", result); return result; } // These underlying static methods are directly accessible // from other classes within the bundle public static boolean areMandatoryAttributesPresent_(Map<String,String> consumerAttributes, Provider p) { logger.debug(LOG_ENTRY, "areMandatoryAttributesPresent_", new Object[]{consumerAttributes, p}); boolean allPresent = true; String mandatory = (String) p.getAttributes().get(Constants.MANDATORY_DIRECTIVE + ":"); if(mandatory != null && !mandatory.equals("")) { List<String> attributeNames = ManifestHeaderProcessor.split(mandatory, ","); for(String name : attributeNames) { allPresent = consumerAttributes.containsKey(name); if(!allPresent) break; } } logger.debug(LOG_EXIT, "areMandatoryAttributesPresent_", allPresent); return allPresent; } public static ImportedBundle buildFragmentHost_(String fragmentHostHeader) throws InvalidAttributeException { logger.debug(LOG_ENTRY, "buildFragmentHost_", new Object[]{fragmentHostHeader}); if(fragmentHostHeader == null) { return null; } Map<String, Map<String, String>> parsedFragHost = ManifestHeaderProcessor.parseImportString(fragmentHostHeader); if(parsedFragHost.size() != 1) throw new InvalidAttributeException(MessageUtil.getMessage("MORE_THAN_ONE_FRAG_HOST", new Object[] {fragmentHostHeader}, "An internal error occurred. A bundle fragment manifest must define exactly one Fragment-Host entry. The following entry was found" + fragmentHostHeader + ".")); String hostName = parsedFragHost.keySet().iterator().next(); Map<String, String> attribs = parsedFragHost.get(hostName); String bundleVersion = attribs.remove(BUNDLE_VERSION_ATTRIBUTE); if (bundleVersion != null && attribs.get(VERSION_ATTRIBUTE) == null) { attribs.put (VERSION_ATTRIBUTE, bundleVersion); } attribs.put(ModellingConstants.OBR_SYMBOLIC_NAME, hostName); String filter = ManifestHeaderProcessor.generateFilter(attribs); ImportedBundle result = new ImportedBundleImpl(filter, attribs); logger.debug(LOG_EXIT, "buildFragmentHost_", result); return result; } public static ImportedPackage intersectPackage_ (ImportedPackage p1, ImportedPackage p2) { logger.debug(LOG_ENTRY, "intersectPackage_", new Object[]{p1, p2}); ImportedPackage result = null; if (p1.getPackageName().equals(p2.getPackageName())) { Map<String,String> att1 = new HashMap<String, String>(p1.getAttributes()); Map<String,String> att2 = new HashMap<String, String>(p2.getAttributes()); // Get the versions, we remove them so that the remaining attributes can be matched. String rangeStr1 = att1.remove(Constants.VERSION_ATTRIBUTE); String rangeStr2 = att2.remove(Constants.VERSION_ATTRIBUTE); //Also remove the optional directive as we don't care about that either att1.remove(OPTIONAL_KEY); att2.remove(OPTIONAL_KEY); //If identical take either, otherwise null! Map<String, String> mergedAttribs = (att1.equals(att2) ? att1 : null); if (mergedAttribs == null) { // Cannot intersect requirements if attributes are not identical. result = null; } else { boolean isIntersectSuccessful = true; if (rangeStr1 != null && rangeStr2 != null) { // Both requirements have a version constraint so check for an intersection between them. VersionRange range1 = ManifestHeaderProcessor.parseVersionRange(rangeStr1); VersionRange range2 = ManifestHeaderProcessor.parseVersionRange(rangeStr2); VersionRange intersectRange = range1.intersect(range2); if (intersectRange == null) { // No intersection possible. isIntersectSuccessful = false; } else { // Use the intersected version range. mergedAttribs.put(Constants.VERSION_ATTRIBUTE, intersectRange.toString()); } } else if (rangeStr1 != null) { mergedAttribs.put(Constants.VERSION_ATTRIBUTE, rangeStr1); } else if (rangeStr2 != null) { mergedAttribs.put(Constants.VERSION_ATTRIBUTE, rangeStr2); } //If both optional, we are optional, otherwise use the default if(p1.isOptional() && p2.isOptional()) { mergedAttribs.put(OPTIONAL_KEY, Constants.RESOLUTION_OPTIONAL); } try { result = (isIntersectSuccessful ? new ImportedPackageImpl(p1.getPackageName(), mergedAttribs) : null); } catch (InvalidAttributeException iax) { logger.error(iax.getMessage()); } } } logger.debug(LOG_EXIT, "intersectPackage_", result); return result; } }
8,905
0
Create_ds/aries/application/application-runtime-isolated/src/main/java/org/apache/aries/application/runtime/isolated
Create_ds/aries/application/application-runtime-isolated/src/main/java/org/apache/aries/application/runtime/isolated/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.isolated.impl; 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.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.aries.application.ApplicationMetadata; 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.UpdateException; import org.apache.aries.application.management.spi.framework.BundleFrameworkManager; import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion; import org.apache.aries.application.management.spi.repository.BundleRepositoryManager; import org.apache.aries.application.management.spi.repository.ContextException; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApplicationContextImpl implements AriesApplicationContext { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextImpl.class); private final AriesApplication _application; private final Set<Bundle> _bundles; private ApplicationState _state = ApplicationState.UNINSTALLED; private boolean _closed; private final BundleRepositoryManager _bundleRepositoryManager; private final BundleFrameworkManager _bundleFrameworkManager; /** deployment metadata associated with aries application */ private DeploymentMetadata _deploymentMF; public ApplicationContextImpl(AriesApplication app, ApplicationContextManagerImpl acm) throws BundleException { LOGGER.debug(LOG_ENTRY, "ApplicationContextImpl", new Object[] { app, acm }); _bundleFrameworkManager = acm.getBundleFrameworkManager(); _bundleRepositoryManager = acm.getBundleRepositoryManager(); _bundles = new LinkedHashSet<Bundle>(); _application = app; _deploymentMF = _application.getDeploymentMetadata(); if (_deploymentMF.getApplicationDeploymentContents() != null && !_deploymentMF.getApplicationDeploymentContents().isEmpty()) { install(); } LOGGER.debug(LOG_EXIT, "ApplicationContextImpl", this); } /** * Called to install the application. * @return whether the installation is successful * */ private void install() throws BundleException { LOGGER.debug(LOG_ENTRY, "install"); List<DeploymentContent> bundlesToFind = new ArrayList<DeploymentContent>(_deploymentMF .getApplicationDeploymentContents()); List<DeploymentContent> useBundlesToFind = new ArrayList<DeploymentContent>(_deploymentMF .getDeployedUseBundle()); List<DeploymentContent> provisionBundlesToFind = new ArrayList<DeploymentContent>(_deploymentMF .getApplicationProvisionBundles()); try { installBundles(provisionBundlesToFind, true); installBundles(useBundlesToFind, true); installBundles(bundlesToFind, false); _state = ApplicationState.INSTALLED; LOGGER.debug("Successfully installed application " + _application.getApplicationMetadata().getApplicationSymbolicName()); } catch (BundleException e) { LOGGER.debug(LOG_EXCEPTION, "Failed to install application " + _application.getApplicationMetadata().getApplicationSymbolicName()); uninstall(); throw e; } LOGGER.debug(LOG_EXIT, "install"); } /** * Called to remove the application, if called multiple times the subsequent * calls will be ignored. * @return whether the uninstallation is successful */ protected synchronized void uninstall() throws BundleException { LOGGER.debug(LOG_ENTRY, "uninstall"); if (_state != ApplicationState.UNINSTALLED) { // Iterate through all of the bundles that were started when this application was started, // and attempt to stop and uninstall each of them. for (Iterator<Bundle> bundleIter = _bundles.iterator(); bundleIter.hasNext();) { Bundle bundleToRemove = bundleIter.next(); if (bundleToRemove.getState() != Bundle.UNINSTALLED) { try { // If Bundle is active, stop it first. if (bundleToRemove.getState() == Bundle.ACTIVE) { _bundleFrameworkManager.stopBundle(bundleToRemove); } } catch (BundleException be) { LOGGER.debug(LOG_EXCEPTION, be); } try { // Delegate the uninstall to the bundleFrameworkManager _bundleFrameworkManager.uninstallBundle(bundleToRemove); } catch (BundleException be) { LOGGER.debug(LOG_EXCEPTION, be); } } bundleIter.remove(); } _state = ApplicationState.UNINSTALLED; } LOGGER.debug(LOG_EXIT, "uninstall"); } /** * This method finds bundles matching the list of content passed in * @param bundlesToFind bundles to find and start if the bundle is shared. If isolated, install it. * @param shared whether the bundles will be shared or isolated * @return the result of execution */ private void installBundles(List<DeploymentContent> bundlesToFind, boolean shared) throws BundleException { LOGGER.debug(LOG_ENTRY, "install", new Object[] { bundlesToFind, Boolean.valueOf(shared) }); if (!bundlesToFind.isEmpty() || !shared) { Iterator<DeploymentContent> it = bundlesToFind.iterator(); /** * Dont install any bundles from the list which are already * installed */ Bundle[] sharedBundles = _bundleFrameworkManager.getSharedBundleFramework() .getIsolatedBundleContext().getBundles(); if (shared) { if (sharedBundles.length > 0) { while (it.hasNext()) { DeploymentContent bundleToFind = it.next(); for (Bundle b : sharedBundles) { if (bundleToFind.getContentName().equals(b.getSymbolicName()) && bundleToFind.getExactVersion().equals(b.getVersion())) { it.remove(); _bundles.add(b); break; } } } } } /** * Ask the repository manager to find us a list of suggested bundles * to install based on our content list */ Map<DeploymentContent, BundleSuggestion> bundlesToBeInstalled = findBundleSuggestions(bundlesToFind); /** * Perform the install of the bundles */ try { if (shared) _bundles.addAll(_bundleFrameworkManager.installSharedBundles( new ArrayList<BundleSuggestion>(bundlesToBeInstalled.values()), makeAppProxy())); else _bundles.add(_bundleFrameworkManager.installIsolatedBundles( new ArrayList<BundleSuggestion>(bundlesToBeInstalled.values()), makeAppProxy())); } catch (BundleException e) { LOGGER.debug(LOG_EXCEPTION, e); throw e; } } LOGGER.debug(LOG_EXIT, "install"); } /** * Create a proxy for the AriesApplication we pass on so as to respect the correct current deployment metadata. */ private AriesApplication makeAppProxy() { return new AriesApplication() { public void store(OutputStream out) throws FileNotFoundException, IOException { throw new UnsupportedOperationException(); } public void store(File f) throws FileNotFoundException, IOException { throw new UnsupportedOperationException(); } public boolean isResolved() { return true; } public DeploymentMetadata getDeploymentMetadata() { return _deploymentMF; } public Set<BundleInfo> getBundleInfo() { return _application.getBundleInfo(); } public ApplicationMetadata getApplicationMetadata() { return _application.getApplicationMetadata(); } }; } private Map<DeploymentContent, BundleSuggestion> findBundleSuggestions( Collection<DeploymentContent> bundlesToFind) throws BundleException { Map<DeploymentContent, BundleSuggestion> suggestions = null; try { suggestions = _bundleRepositoryManager.getBundleSuggestions(_application .getApplicationMetadata().getApplicationSymbolicName(), _application .getApplicationMetadata().getApplicationVersion().toString(), bundlesToFind); } catch (ContextException e) { LOGGER.debug(LOG_EXCEPTION, e); throw new BundleException("Failed to locate bundle suggestions", e); } return suggestions; } public AriesApplication getApplication() { LOGGER.debug(LOG_ENTRY, "getApplication"); LOGGER.debug(LOG_EXIT, "getApplication", new Object[] { _application }); return _application; } public synchronized Set<Bundle> getApplicationContent() { LOGGER.debug(LOG_ENTRY, "getApplicationContent"); LOGGER.debug(LOG_EXIT, "getApplicationContent", new Object[] { _bundles }); return _bundles; } public synchronized ApplicationState getApplicationState() { LOGGER.debug(LOG_ENTRY, "getApplicationState"); LOGGER.debug(LOG_EXIT, "getApplicationState", new Object[] { _state }); return _state; } public synchronized void start() throws BundleException, IllegalStateException { LOGGER.debug(LOG_ENTRY, "start"); if (!(_state == ApplicationState.INSTALLED || _state == ApplicationState.RESOLVED)) throw new IllegalStateException("Appication is in incorrect state " + _state + " expected " + ApplicationState.INSTALLED + " or " + ApplicationState.RESOLVED); List<Bundle> bundlesWeStarted = new ArrayList<Bundle>(); try { for (Bundle b : _bundles) { _bundleFrameworkManager.startBundle(b); bundlesWeStarted.add(b); } } catch (BundleException be) { for (Bundle b : bundlesWeStarted) { try { _bundleFrameworkManager.stopBundle(b); } 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. LOGGER.debug(LOG_EXCEPTION, be2); } } LOGGER.debug(LOG_EXCEPTION, be); LOGGER.debug(LOG_EXIT, "start", new Object[] { be }); throw be; } _state = ApplicationState.ACTIVE; LOGGER.debug(LOG_EXIT, "start"); } public synchronized void stop() throws BundleException, IllegalStateException { LOGGER.debug(LOG_ENTRY, "stop"); if (_state != ApplicationState.ACTIVE) throw new IllegalStateException("Appication is in incorrect state " + _state + " expected " + ApplicationState.ACTIVE); for (Bundle entry : _bundles) { Bundle b = entry; _bundleFrameworkManager.stopBundle(b); } _state = ApplicationState.RESOLVED; LOGGER.debug(LOG_EXIT, "stop"); } public synchronized void update(final DeploymentMetadata newMetadata, final DeploymentMetadata oldMetadata) throws UpdateException { final boolean toStart = getApplicationState() == ApplicationState.ACTIVE; if (_bundleFrameworkManager.allowsUpdate(newMetadata, oldMetadata)) { _bundleFrameworkManager.updateBundles(newMetadata, oldMetadata, _application, new BundleFrameworkManager.BundleLocator() { public Map<DeploymentContent, BundleSuggestion> suggestBundle( Collection<DeploymentContent> bundles) throws BundleException { return findBundleSuggestions(bundles); } }, _bundles, toStart); } else { // fallback do a uninstall, followed by a reinstall try { uninstall(); _deploymentMF = newMetadata; try { install(); if (toStart) start(); } catch (BundleException e) { try { uninstall(); _deploymentMF = oldMetadata; install(); if (toStart) start(); throw new UpdateException("Could not install updated application", e, true, null); } catch (BundleException e2) { throw new UpdateException("Could not install updated application", e, false, e2); } } } catch (BundleException e) { try { _deploymentMF = oldMetadata; install(); if (toStart) start(); throw new UpdateException("Could not install updated application", e, true, null); } catch (BundleException e2) { throw new UpdateException("Could not install updated application", e, false, e2); } } } } public synchronized void close() throws BundleException { uninstall(); _closed = true; } public synchronized void open() throws BundleException { if (_closed) { install(); _closed = false; } } }
8,906
0
Create_ds/aries/application/application-runtime-isolated/src/main/java/org/apache/aries/application/runtime/isolated
Create_ds/aries/application/application-runtime-isolated/src/main/java/org/apache/aries/application/runtime/isolated/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.isolated.impl; 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.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; 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.AriesApplicationContext.ApplicationState; import org.apache.aries.application.management.ManagementException; import org.apache.aries.application.management.UpdateException; import org.apache.aries.application.management.spi.framework.BundleFrameworkManager; import org.apache.aries.application.management.spi.repository.BundleRepositoryManager; import org.apache.aries.application.management.spi.runtime.AriesApplicationContextManager; import org.apache.aries.application.utils.AppConstants; import org.osgi.framework.BundleException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApplicationContextManagerImpl implements AriesApplicationContextManager { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextManagerImpl.class); private ConcurrentMap<AriesApplication, AriesApplicationContext> _appToContextMap; private BundleFrameworkManager _bundleFrameworkManager; private BundleRepositoryManager _bundleRepositoryManager; public ApplicationContextManagerImpl() { LOGGER.debug(LOG_ENTRY, "ApplicationContextImpl"); _appToContextMap = new ConcurrentHashMap<AriesApplication, AriesApplicationContext>(); // When doing isolated runtime support provisioning against the local repo is a really bad idea // it can result in trying to install things into the shared framework into the local framework // this doesn't work because we don't know how to install them into the shared framework and // we can't just use them because they are in the local framework, so if this class is constructed // we disable local provisioning. System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "true"); LOGGER.debug(LOG_EXIT, "ApplicationContextImpl", this); } public void setBundleFrameworkManager(BundleFrameworkManager bfm) { _bundleFrameworkManager = bfm; } public void setBundleRepositoryManager(BundleRepositoryManager brm) { LOGGER.debug(LOG_ENTRY, "setBundleRepositoryManager", brm); LOGGER.debug(LOG_EXIT, "setBundleRepositoryManager"); this._bundleRepositoryManager = brm; } public BundleRepositoryManager getBundleRepositoryManager() { LOGGER.debug(LOG_ENTRY, "getBundleRepositoryManager"); LOGGER.debug(LOG_EXIT, "getBundleRepositoryManager", _bundleRepositoryManager); return _bundleRepositoryManager; } public synchronized AriesApplicationContext getApplicationContext(AriesApplication app) throws BundleException, ManagementException { LOGGER.debug(LOG_ENTRY, "getApplicationContext", app); AriesApplicationContext result; if (_appToContextMap.containsKey(app)) { result = _appToContextMap.get(app); } else { result = new ApplicationContextImpl(app, this); AriesApplicationContext previous = _appToContextMap.putIfAbsent(app, result); if (previous != null) { result = previous; } } LOGGER.debug(LOG_EXIT, "getApplicationContext", result); return result; } public synchronized Set<AriesApplicationContext> getApplicationContexts() { LOGGER.debug(LOG_ENTRY, "getApplicationContexts"); Set<AriesApplicationContext> result = new HashSet<AriesApplicationContext>(); for (Map.Entry<AriesApplication, AriesApplicationContext> entry : _appToContextMap.entrySet()) { result.add(entry.getValue()); } LOGGER.debug(LOG_EXIT, "getApplicationContexts", result); return result; } public void remove(AriesApplicationContext app) throws BundleException { LOGGER.debug(LOG_ENTRY, "remove", app); ApplicationContextImpl appToRemove = null; synchronized (_appToContextMap) { Iterator<Map.Entry<AriesApplication, AriesApplicationContext>> it = _appToContextMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<AriesApplication, AriesApplicationContext> entry = it.next(); ApplicationContextImpl potentialMatch = (ApplicationContextImpl) entry.getValue(); if (potentialMatch == app) { it.remove(); appToRemove = potentialMatch; break; } } } if (appToRemove != null) { appToRemove.uninstall(); } LOGGER.debug(LOG_EXIT, "remove"); } public void close() { LOGGER.debug(LOG_ENTRY, "close"); List<ApplicationContextImpl> contextsToUninstall = new ArrayList<ApplicationContextImpl>(); synchronized (_appToContextMap) { Iterator<AriesApplicationContext> it = _appToContextMap.values().iterator(); while (it.hasNext()) { ApplicationContextImpl ctx = (ApplicationContextImpl)it.next(); if (ctx.getApplicationState() != ApplicationState.UNINSTALLED) { contextsToUninstall.add(ctx); it.remove(); } } } for (ApplicationContextImpl c : contextsToUninstall) { try { c.uninstall(); } catch (BundleException e) { LOGGER.debug(LOG_EXCEPTION,e); } } LOGGER.debug(LOG_EXIT, "close"); } protected BundleFrameworkManager getBundleFrameworkManager() { LOGGER.debug(LOG_ENTRY, "getBundleFrameworkManager"); LOGGER.debug(LOG_EXIT, "getBundleFrameworkManager", _bundleFrameworkManager); return _bundleFrameworkManager; } public AriesApplicationContext update(AriesApplication app, DeploymentMetadata oldMetadata) throws UpdateException { ApplicationContextImpl ctx = (ApplicationContextImpl)_appToContextMap.get(app); if (ctx == null) { throw new IllegalArgumentException("AriesApplication "+ app.getApplicationMetadata().getApplicationSymbolicName() + "/" + app.getApplicationMetadata().getApplicationVersion() + " cannot be updated because it is not installed"); } ctx.update(app.getDeploymentMetadata(), oldMetadata); return ctx; } public void bindBundleFrameworkManager(BundleFrameworkManager bfm) { LOGGER.debug(LOG_ENTRY, "bindBundleFrameworkManager", bfm); List<AriesApplicationContext> contexts = new ArrayList<AriesApplicationContext>(); synchronized (_appToContextMap) { contexts.addAll (_appToContextMap.values()); } for (AriesApplicationContext ctx : contexts) { try { ((ApplicationContextImpl)ctx).open(); } catch (BundleException e) { LOGGER.debug(LOG_EXCEPTION,e); } } LOGGER.debug(LOG_EXIT, "bindBundleFrameworkManager"); } public void unbindBundleFrameworkManager(BundleFrameworkManager bfm) { LOGGER.debug(LOG_ENTRY, "unbindBundleFrameworkManager", bfm); List<AriesApplicationContext> appContexts = new ArrayList<AriesApplicationContext>(); synchronized (_appToContextMap) { appContexts.addAll(_appToContextMap.values()); } for (AriesApplicationContext c : appContexts) { try { ((ApplicationContextImpl)c).close(); } catch (BundleException e) { LOGGER.debug(LOG_EXCEPTION,e); } } LOGGER.debug(LOG_EXIT, "unbindBundleFrameworkManager"); } }
8,907
0
Create_ds/aries/application/application-management/src/test/java/org/apache/aries/unittest
Create_ds/aries/application/application-management/src/test/java/org/apache/aries/unittest/utils/EbaUnitTestUtils.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.unittest.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.aries.util.io.IOUtils; public class EbaUnitTestUtils { private static final String TEMP_DIR = "unittest/tmpEbaContent"; public static void createEba(String rootFolder, String outputFile) throws IOException { File tempDir = new File(TEMP_DIR); tempDir.mkdirs(); createEbaRecursive(new File(rootFolder), tempDir, ""); IOUtils.zipUp(tempDir, new File(outputFile)); IOUtils.deleteRecursive(tempDir); } private static void createEbaRecursive(File folder, File tempDir, String prefix) throws IOException { File[] files = folder.listFiles(); if (files != null) { for (File f : files) { if ((f.getName().endsWith(".jar") || f.getName().endsWith(".war")) && f.isDirectory()) { File manifestFile = new File(f, "META-INF/MANIFEST.MF"); Manifest m; if (manifestFile.isFile()) m = new Manifest(new FileInputStream(manifestFile)); else { m = new Manifest(); m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); } File jarFile = new File(tempDir, prefix + f.getName()); jarFile.getParentFile().mkdirs(); IOUtils.jarUp(f, jarFile, m); } else if (f.isFile()) { IOUtils.writeOut(tempDir, prefix + f.getName(), new FileInputStream(f)); } else if (f.isDirectory()) { createEbaRecursive(f, tempDir, prefix + f.getName() + File.separator); } } } } public static void cleanupEba(String outputFile) { new File(outputFile).delete(); } }
8,908
0
Create_ds/aries/application/application-management/src/test/java/org/apache/aries/application/management
Create_ds/aries/application/application-management/src/test/java/org/apache/aries/application/management/impl/AriesApplicationManagerImplTest.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.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.util.ArrayList; 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 java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.ApplicationMetadataFactory; import org.apache.aries.application.Content; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.DeploymentMetadataFactory; import org.apache.aries.application.ServiceDeclaration; import org.apache.aries.application.impl.ApplicationMetadataFactoryImpl; import org.apache.aries.application.impl.ContentImpl; import org.apache.aries.application.impl.DeploymentContentImpl; import org.apache.aries.application.impl.DeploymentMetadataFactoryImpl; 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.ResolveConstraint; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.UpdateException; import org.apache.aries.application.management.spi.convert.BundleConversion; import org.apache.aries.application.management.spi.convert.BundleConverter; import org.apache.aries.application.management.spi.convert.ConversionException; 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.runtime.AriesApplicationContextManager; import org.apache.aries.application.management.spi.runtime.LocalPlatform; import org.apache.aries.application.modelling.DeployedBundles; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.application.utils.management.SimpleBundleInfo; import org.apache.aries.unittest.mocks.MethodCall; import org.apache.aries.unittest.mocks.Skeleton; import org.apache.aries.unittest.utils.EbaUnitTestUtils; import org.apache.aries.util.filesystem.FileSystem; 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.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.osgi.framework.Constants; import org.osgi.framework.Version; /** * Initial, simple test that creates and stores an AriesApplication. No * BundleConverters are used in this test. */ public class AriesApplicationManagerImplTest { static class DummyDMManager implements DeploymentManifestManager { private AriesApplicationResolver resolver; public Manifest generateDeploymentManifest(AriesApplication app, ResolveConstraint... constraints) throws ResolverException { Map<String, String> deploymentMap = new HashMap<String, String>(); Set<BundleInfo> byValueBundles = app.getBundleInfo(); StringBuilder deployedContents = new StringBuilder(); boolean beginning= true; for (BundleInfo bundle: byValueBundles) { if (!!!beginning) { deployedContents.append(","); } deployedContents.append(bundle.getSymbolicName()+";" + AppConstants.DEPLOYMENT_BUNDLE_VERSION + "=" + bundle.getVersion()); beginning = false; } deploymentMap.put(AppConstants.DEPLOYMENT_CONTENT, deployedContents.toString()); // fake the provision bundle now. String persistenceLibraryLocation = "../src/test/resources/bundles/repository/a.handy.persistence.library.jar"; File persistenceLibrary = new File (persistenceLibraryLocation); BundleManifest mf = BundleManifest.fromBundle(persistenceLibrary); deploymentMap.put(AppConstants.DEPLOYMENT_PROVISION_BUNDLE, mf.getSymbolicName()+";" + AppConstants.DEPLOYMENT_BUNDLE_VERSION + "=" + mf.getVersion()); deploymentMap.put(AppConstants.APPLICATION_SYMBOLIC_NAME, app.getApplicationMetadata().getApplicationSymbolicName()); deploymentMap.put(AppConstants.APPLICATION_VERSION, app.getApplicationMetadata().getApplicationVersion().toString()); Manifest man = new Manifest(); Attributes att = man.getMainAttributes(); att.putValue(Attributes.Name.MANIFEST_VERSION.toString(), AppConstants.MANIFEST_VERSION); for (Map.Entry<String, String> entry : deploymentMap.entrySet()) { att.putValue(entry.getKey(), entry.getValue()); } return man; } public void setResolver(AriesApplicationResolver resolver) { this.resolver = resolver; } public AriesApplicationResolver getResolver() { return resolver; } public Manifest generateDeploymentManifest(String appName, String appVersion, Collection<Content> appContent, Collection<ModelledResource> byValueBundles, Collection<Content> useBundleSet, Collection<Content> otherBundles, Collection<ServiceDeclaration> appImportServices) throws ResolverException { return null; } public DeployedBundles generateDeployedBundles(ApplicationMetadata appMetadata, Collection<ModelledResource> byValueBundles, Collection<Content> otherBundles) throws ResolverException { // Not required or used in this test return null; } public Manifest generateDeploymentManifest(String appSymbolicName, String appVersion, DeployedBundles deployedBundles) throws ResolverException { // Not required or used in this test return null; } } static class DummyResolver implements AriesApplicationResolver { Set<BundleInfo> nextResult; public Set<BundleInfo> resolve(AriesApplication app, ResolveConstraint... constraints) { Set<BundleInfo> info = new HashSet<BundleInfo>(nextResult); info.addAll(app.getBundleInfo()); return info; } void setNextResult (Set<BundleInfo> r) { nextResult = r; } public BundleInfo getBundleInfo(String bundleSymbolicName, Version bundleVersion) { return null; } 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 null; } } 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 class DummyConverter implements BundleConverter { public BundleConversion convert(IDirectory parentEba, IFile toBeConverted) throws ConversionException { if (toBeConverted.getName().equals("helloWorld.war")) { InputStream is = null; try { is = new FileInputStream(new File("../src/test/resources/conversion/MANIFEST.MF")); Manifest warManifest = new Manifest(is); final File convertedFile = new File("./ariesApplicationManagerImplTest/conversion/helloWorld.war"); IOUtils.jarUp(new File("../src/test/resources/conversion/conversion.eba/helloWorld.war"), convertedFile, warManifest); final String location = toBeConverted.toString(); return new BundleConversion() { public BundleInfo getBundleInfo() throws IOException { return new SimpleBundleInfo(BundleManifest.fromBundle(convertedFile), location); } public InputStream getInputStream() throws IOException { return new FileInputStream(convertedFile); } }; } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (Exception e) { e.printStackTrace(); } } } return null; } } static final String TEST_EBA = "./ariesApplicationManagerImplTest/test.eba"; static final String CONVERSION_EBA = "./ariesApplicationManagerImplTest/conversion.eba"; @BeforeClass public static void preTest() throws Exception { new File("ariesApplicationManagerImplTest/conversion").mkdirs(); EbaUnitTestUtils.createEba("../src/test/resources/bundles/test.eba", TEST_EBA); File src = new File ("../src/test/resources/bundles/repository/a.handy.persistence.library.jar"); File dest = new File ("ariesApplicationManagerImplTest/a.handy.persistence.library.jar"); IOUtils.zipUp(src, dest); EbaUnitTestUtils.createEba("../src/test/resources/conversion/conversion.eba", CONVERSION_EBA); } AriesApplicationManagerImpl _appMgr; ApplicationMetadataFactory _appMetaFactory; DummyResolver _resolver; DummyConverter _converter; DummyDMManager _dmMgr; @Before public void setup() { _appMgr = new AriesApplicationManagerImpl (); _appMetaFactory = new ApplicationMetadataFactoryImpl (); DeploymentMetadataFactory dmf = new DeploymentMetadataFactoryImpl(); _converter = new DummyConverter(); List<BundleConverter> bundleConverters = new ArrayList<BundleConverter>(); bundleConverters.add(_converter); _resolver = new DummyResolver(); _dmMgr = new DummyDMManager(); _dmMgr.setResolver(_resolver); _appMgr.setApplicationMetadataFactory(_appMetaFactory); _appMgr.setDeploymentMetadataFactory(dmf); _appMgr.setBundleConverters(bundleConverters); _appMgr.setDeploymentManifestManager(_dmMgr); _appMgr.setLocalPlatform(new DummyLocalPlatform()); } @Test public void testCreate() throws Exception { AriesApplication app = createApplication (TEST_EBA); ApplicationMetadata appMeta = app.getApplicationMetadata(); assertEquals (appMeta.getApplicationName(), "Test application"); assertEquals (appMeta.getApplicationSymbolicName(), "org.apache.aries.application.management.test"); assertEquals (appMeta.getApplicationVersion(), new Version("1.0")); List<Content> appContent = appMeta.getApplicationContents(); assertEquals (appContent.size(), 2); Content fbw = new ContentImpl("foo.bar.widgets;version=1.0.0"); Content mbl = new ContentImpl("my.business.logic;version=1.0.0"); assertTrue (appContent.contains(fbw)); assertTrue (appContent.contains(mbl)); DeploymentMetadata dm = app.getDeploymentMetadata(); List<DeploymentContent> dcList = dm.getApplicationDeploymentContents(); assertEquals (2, dcList.size()); DeploymentContent dc1 = new DeploymentContentImpl ("foo.bar.widgets;deployed-version=1.1.0"); DeploymentContent dc2 = new DeploymentContentImpl ("my.business.logic;deployed-version=1.1.0"); DeploymentContent dc3 = new DeploymentContentImpl ("a.handy.persistence.library;deployed-version=1.1.0"); assertTrue (dcList.contains(dc1)); assertTrue (dcList.contains(dc2)); dcList = dm.getApplicationProvisionBundles(); assertEquals(1, dcList.size()); assertTrue (dcList.contains(dc3)); } @Test public void testCreateAndConversion() throws Exception { AriesApplication app = createApplication (CONVERSION_EBA); ApplicationMetadata appMeta = app.getApplicationMetadata(); assertEquals (appMeta.getApplicationName(), "conversion.eba"); assertEquals (appMeta.getApplicationSymbolicName(), "conversion.eba"); assertEquals (appMeta.getApplicationVersion(), new Version("0.0")); List<Content> appContent = appMeta.getApplicationContents(); assertEquals (2, appContent.size()); Content fbw = new ContentImpl("hello.world.jar;version=\"[1.1.0, 1.1.0]\""); Content mbl = new ContentImpl("helloWorld.war;version=\"[0.0.0, 0.0.0]\""); assertTrue (appContent.contains(fbw)); assertTrue (appContent.contains(mbl)); DeploymentMetadata dm = app.getDeploymentMetadata(); List<DeploymentContent> dcList = dm.getApplicationDeploymentContents(); assertEquals (2, dcList.size()); DeploymentContent dc1 = new DeploymentContentImpl ("hello.world.jar;deployed-version=1.1.0"); DeploymentContent dc2 = new DeploymentContentImpl ("helloWorld.war;deployed-version=0.0.0"); DeploymentContent dc3 = new DeploymentContentImpl ("a.handy.persistence.library;deployed-version=1.1.0"); assertTrue (dcList.contains(dc1)); assertTrue (dcList.contains(dc2)); dcList = dm.getApplicationProvisionBundles(); assertEquals(1, dcList.size()); assertTrue (dcList.contains(dc3)); assertEquals(2, app.getBundleInfo().size()); BundleInfo info; info = findBundleInfo(app.getBundleInfo(), "hello.world.jar"); assertNotNull(info); assertEquals("HelloWorldJar", info.getHeaders().get(Constants.BUNDLE_NAME)); info = findBundleInfo(app.getBundleInfo(), "helloWorld.war"); assertNotNull(info); assertEquals("helloWorld.war", info.getHeaders().get(Constants.BUNDLE_NAME)); assertEquals("/test", info.getHeaders().get("Bundle-ContextPath")); } private BundleInfo findBundleInfo(Set<BundleInfo> infos, String symbolicName) { for (BundleInfo info : infos) { if (symbolicName.equals(info.getSymbolicName())) { return info; } } return null; } @Test public void testStoreAndReload() throws Exception { AriesApplication app = createApplication (TEST_EBA); File dest = new File ("ariesApplicationManagerImplTest/stored.eba"); app.store(dest); /* Dest should be a zip file with four entries: * /foo.bar.widgets.jar * /my.business.logic.jar * /META-INF/APPLICATION.MF * /META-INF/DEPLOYMENT.MF */ IDirectory storedEba = FileSystem.getFSRoot(dest); assertNotNull (storedEba); assertEquals (storedEba.listFiles().size(), 3); IFile ifile = storedEba.getFile("META-INF/APPLICATION.MF"); assertNotNull (ifile); ifile = storedEba.getFile ("META-INF/DEPLOYMENT.MF"); assertNotNull (ifile); ifile = storedEba.getFile ("foo.bar.widgets.jar"); assertNotNull (ifile); ifile = storedEba.getFile ("my.business.logic.jar"); assertNotNull (ifile); AriesApplication newApp = _appMgr.createApplication(storedEba); DeploymentMetadata dm = newApp.getDeploymentMetadata(); assertEquals (2, dm.getApplicationDeploymentContents().size()); assertEquals(1, dm.getApplicationProvisionBundles().size()); assertEquals (dm.getApplicationSymbolicName(), app.getApplicationMetadata().getApplicationSymbolicName()); assertEquals (dm.getApplicationVersion(), app.getApplicationMetadata().getApplicationVersion()); } @Test public void testUpdate() throws Exception { AriesApplication app = createApplication(TEST_EBA); DeploymentMetadata depMf = createUpdateDepMf(); AriesApplicationContextManager ctxMgr = Skeleton.newMock(AriesApplicationContextManager.class); _appMgr.setApplicationContextManager(ctxMgr); _appMgr.update(app, depMf); assertTrue("Deployment.mf should have been updated", app.getDeploymentMetadata() == depMf); } @Test(expected=IllegalArgumentException.class) public void testUpdateWithIncorrectDepMf() throws Exception { AriesApplication app = createApplication(TEST_EBA); DeploymentMetadata depMf = Skeleton.newMock(DeploymentMetadata.class); Skeleton.getSkeleton(depMf).setReturnValue(new MethodCall(DeploymentMetadata.class, "getApplicationSymbolicName"), "random.app"); Skeleton.getSkeleton(depMf).setReturnValue(new MethodCall(DeploymentMetadata.class, "getApplicationVersion"), new Version("1.0.0")); AriesApplicationContextManager ctxMgr = Skeleton.newMock(AriesApplicationContextManager.class); _appMgr.setApplicationContextManager(ctxMgr); _appMgr.update(app, depMf); } @Test public void testFailedUpdate() throws Exception { AriesApplication app = createApplication(TEST_EBA); DeploymentMetadata depMf = createUpdateDepMf(); AriesApplicationContext ctx = Skeleton.newMock(AriesApplicationContext.class); Skeleton.getSkeleton(ctx).setReturnValue(new MethodCall(AriesApplicationContext.class, "getApplication"), app); AriesApplicationContextManager ctxMgr = Skeleton.newMock(AriesApplicationContextManager.class); Skeleton.getSkeleton(ctxMgr).setReturnValue( new MethodCall(AriesApplicationContextManager.class, "getApplicationContexts"), Collections.singleton(ctx)); Skeleton.getSkeleton(ctxMgr).setThrows( new MethodCall(AriesApplicationContextManager.class, "update", AriesApplication.class, DeploymentMetadata.class), new UpdateException("", null, false, null)); _appMgr.setApplicationContextManager(ctxMgr); try { _appMgr.update(app, depMf); fail("Update should have failed."); } catch (UpdateException e) { assertTrue("Deployment.mf should have been updated", app.getDeploymentMetadata() == depMf); } } @Test public void testRolledbackUpdate() throws Exception { AriesApplication app = createApplication(TEST_EBA); DeploymentMetadata depMf = createUpdateDepMf(); DeploymentMetadata oldMf = app.getDeploymentMetadata(); AriesApplicationContext ctx = Skeleton.newMock(AriesApplicationContext.class); Skeleton.getSkeleton(ctx).setReturnValue(new MethodCall(AriesApplicationContext.class, "getApplication"), app); AriesApplicationContextManager ctxMgr = Skeleton.newMock(AriesApplicationContextManager.class); Skeleton.getSkeleton(ctxMgr).setReturnValue( new MethodCall(AriesApplicationContextManager.class, "getApplicationContexts"), Collections.singleton(ctx)); Skeleton.getSkeleton(ctxMgr).setThrows( new MethodCall(AriesApplicationContextManager.class, "update", AriesApplication.class, DeploymentMetadata.class), new UpdateException("", null, true, null)); _appMgr.setApplicationContextManager(ctxMgr); try { _appMgr.update(app, depMf); fail("Update should have failed."); } catch (UpdateException e) { assertTrue("Deployment.mf should have been rolled back to the old", app.getDeploymentMetadata() == oldMf); } } private DeploymentMetadata createUpdateDepMf() { DeploymentMetadata depMf = Skeleton.newMock(DeploymentMetadata.class); Skeleton.getSkeleton(depMf).setReturnValue(new MethodCall(DeploymentMetadata.class, "getApplicationSymbolicName"), "org.apache.aries.application.management.test"); Skeleton.getSkeleton(depMf).setReturnValue(new MethodCall(DeploymentMetadata.class, "getApplicationVersion"), new Version("1.0.0")); return depMf; } private AriesApplication createApplication (String fileName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, ManagementException, ResolverException { // This next block is a very long winded way of constructing a BundleInfoImpl // against the existing (BundleManifest bm, String location) constructor. If we // find we need a String-based BundleInfoImpl constructor for other reasons, // we could change to using it here. Set<BundleInfo> nextResolverResult = new HashSet<BundleInfo>(); String persistenceLibraryLocation = "../src/test/resources/bundles/repository/a.handy.persistence.library.jar"; File persistenceLibrary = new File (persistenceLibraryLocation); BundleManifest mf = BundleManifest.fromBundle(persistenceLibrary); BundleInfo resolvedPersistenceLibrary = new SimpleBundleInfo(mf, persistenceLibraryLocation); Field v = SimpleBundleInfo.class.getDeclaredField("_version"); v.setAccessible(true); v.set(resolvedPersistenceLibrary, new Version("1.1.0")); nextResolverResult.add(resolvedPersistenceLibrary); _resolver.setNextResult(nextResolverResult); IDirectory testEba = FileSystem.getFSRoot(new File(fileName)); AriesApplication app = _appMgr.createApplication(testEba); app = _appMgr.resolve(app); return app; } }
8,909
0
Create_ds/aries/application/application-management/src/test/java/org/apache/aries/application/management
Create_ds/aries/application/application-management/src/test/java/org/apache/aries/application/management/repository/ApplicationRepositoryTest.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.repository; import java.util.HashSet; import java.util.Map; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.impl.DeploymentContentImpl; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion; import org.apache.aries.unittest.mocks.MethodCall; import org.apache.aries.unittest.mocks.Skeleton; import org.junit.Test; import org.osgi.framework.Version; import static org.junit.Assert.*; public class ApplicationRepositoryTest { @Test public void testBundleNotInApp() { AriesApplication app = Skeleton.newMock(AriesApplication.class); BundleInfo bi = Skeleton.newMock(BundleInfo.class); Skeleton.getSkeleton(bi).setReturnValue(new MethodCall(BundleInfo.class, "getSymbolicName"), "test.bundle"); Skeleton.getSkeleton(bi).setReturnValue(new MethodCall(BundleInfo.class, "getVersion"), new Version("1.0.0")); Skeleton.getSkeleton(app).setReturnValue( new MethodCall(AriesApplication.class, "getBundleInfo"), new HashSet<BundleInfo>()); ApplicationRepository rep = new ApplicationRepository(app); BundleSuggestion sug = rep.suggestBundleToUse(new DeploymentContentImpl("test.bundle", new Version("2.0.0"))); assertNull("We have apparently found a bundle that is not in the application in the ApplicationRepository", sug); } }
8,910
0
Create_ds/aries/application/application-management/src/main/java/org/apache/aries/application/management
Create_ds/aries/application/application-management/src/main/java/org/apache/aries/application/management/impl/AriesApplicationManagerImpl.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.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.JarURLConnection; import java.net.URL; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Manifest; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.ApplicationMetadataFactory; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.DeploymentMetadataFactory; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.AriesApplicationContext; import org.apache.aries.application.management.AriesApplicationListener; import org.apache.aries.application.management.AriesApplicationManager; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.ManagementException; import org.apache.aries.application.management.ResolveConstraint; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.UpdateException; import org.apache.aries.application.management.internal.MessageUtil; import org.apache.aries.application.management.repository.ApplicationRepository; import org.apache.aries.application.management.spi.convert.BundleConversion; import org.apache.aries.application.management.spi.convert.BundleConverter; import org.apache.aries.application.management.spi.convert.ConversionException; import org.apache.aries.application.management.spi.repository.BundleRepository; import org.apache.aries.application.management.spi.resolve.DeploymentManifestManager; import org.apache.aries.application.management.spi.runtime.AriesApplicationContextManager; import org.apache.aries.application.management.spi.runtime.LocalPlatform; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.application.utils.management.SimpleBundleInfo; import org.apache.aries.application.utils.manifest.ManifestDefaultsInjector; import org.apache.aries.util.filesystem.FileSystem; 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.apache.aries.util.manifest.ManifestProcessor; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceException; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AriesApplicationManagerImpl implements AriesApplicationManager { private ApplicationMetadataFactory _applicationMetadataFactory; private DeploymentMetadataFactory _deploymentMetadataFactory; private List<BundleConverter> _bundleConverters; private LocalPlatform _localPlatform; private AriesApplicationContextManager _applicationContextManager; private BundleContext _bundleContext; private DeploymentManifestManager deploymentManifestManager; private Map<AriesApplication, ServiceRegistration> serviceRegistrations = new HashMap<AriesApplication, ServiceRegistration>(); private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.application.management.impl"); public void setApplicationMetadataFactory (ApplicationMetadataFactory amf) { _applicationMetadataFactory = amf; } public void setDeploymentMetadataFactory (DeploymentMetadataFactory dmf) { _deploymentMetadataFactory = dmf; } public void setBundleConverters (List<BundleConverter> bcs) { _bundleConverters = bcs; } public void setDeploymentManifestManager(DeploymentManifestManager dm) { this.deploymentManifestManager = dm; } public void setLocalPlatform (LocalPlatform lp) { _localPlatform = lp; } public void setApplicationContextManager (AriesApplicationContextManager acm) { _applicationContextManager = acm; } public void setBundleContext(BundleContext b) { _bundleContext = b; } /** * Create an AriesApplication from a .eba file: a zip file with a '.eba' extension */ public AriesApplication createApplication(IDirectory ebaFile) throws ManagementException { ApplicationMetadata applicationMetadata = null; DeploymentMetadata deploymentMetadata = null; Map<String, BundleConversion> modifiedBundles = new HashMap<String, BundleConversion>(); AriesApplicationImpl application = null; String appPath = ebaFile.toString(); try { // try to read the app name out of the application.mf Manifest applicationManifest = parseApplicationManifest (ebaFile); String appName = applicationManifest.getMainAttributes().getValue(AppConstants.APPLICATION_NAME); //If the application name is null, we will try to get the file name. if (appName == null || appName.isEmpty()) { String fullPath = appPath; if (fullPath.endsWith("/")) { fullPath = fullPath.substring(0, fullPath.length() -1); } int last_slash = fullPath.lastIndexOf("/"); appName = fullPath.substring(last_slash + 1, fullPath.length()); } IFile deploymentManifest = ebaFile.getFile(AppConstants.DEPLOYMENT_MF); /* We require that all other .jar and .war files included by-value be valid bundles * because a DEPLOYMENT.MF has been provided. If no DEPLOYMENT.MF, migrate * wars to wabs, plain jars to bundles */ Set<BundleInfo> extraBundlesInfo = new HashSet<BundleInfo>(); for (IFile f : ebaFile) { if (f.isDirectory()) { continue; } BundleManifest bm = getBundleManifest (f); if (bm != null) { if (bm.isValid()) { _logger.debug("File {} is a valid bundle. Adding it to bundle list.", f.getName()); extraBundlesInfo.add(new SimpleBundleInfo(bm, f.toURL().toExternalForm())); } else if (deploymentManifest == null) { _logger.debug("File {} is not a valid bundle. Attempting to convert it.", f.getName()); // We have a jar that needs converting to a bundle, or a war to migrate to a WAB // We only do this if a DEPLOYMENT.MF does not exist. BundleConversion convertedBinary = null; Iterator<BundleConverter> converters = _bundleConverters.iterator(); List<ConversionException> conversionExceptions = Collections.emptyList(); while (converters.hasNext() && convertedBinary == null) { try { BundleConverter converter = converters.next(); _logger.debug("Converting file using {} converter", converter); convertedBinary = converter.convert(ebaFile, f); } catch (ServiceException sx) { // We'll get this if our optional BundleConverter has not been injected. } catch (ConversionException cx) { conversionExceptions.add(cx); } } if (conversionExceptions.size() > 0) { for (ConversionException cx : conversionExceptions) { _logger.error("APPMANAGEMENT0004E", new Object[]{f.getName(), appName, cx}); } throw new ManagementException (MessageUtil.getMessage("APPMANAGEMENT0005E", appName)); } if (convertedBinary != null) { _logger.debug("File {} was successfully converted. Adding it to bundle list.", f.getName()); modifiedBundles.put (f.getName(), convertedBinary); extraBundlesInfo.add(convertedBinary.getBundleInfo()); } else { _logger.debug("File {} was not converted.", f.getName()); } } else { _logger.debug("File {} was ignored. It is not a valid bundle and DEPLOYMENT.MF is present", f.getName()); } } else { _logger.debug("File {} was ignored. It has no manifest file.", f.getName()); } } // if Application-Content header was not specified build it based on the bundles included by value if (applicationManifest.getMainAttributes().getValue(AppConstants.APPLICATION_CONTENT) == null) { String appContent = buildAppContent(extraBundlesInfo); applicationManifest.getMainAttributes().putValue(AppConstants.APPLICATION_CONTENT, appContent); } ManifestDefaultsInjector.updateManifest(applicationManifest, appName, ebaFile); applicationMetadata = _applicationMetadataFactory.createApplicationMetadata(applicationManifest); if (deploymentManifest != null) { deploymentMetadata = _deploymentMetadataFactory.parseDeploymentMetadata(deploymentManifest); // Validate: symbolic names must match String appSymbolicName = applicationMetadata.getApplicationSymbolicName(); String depSymbolicName = deploymentMetadata.getApplicationSymbolicName(); if (!appSymbolicName.equals(depSymbolicName)) { throw new ManagementException (MessageUtil.getMessage("APPMANAGEMENT0002E", appName, appSymbolicName, depSymbolicName)); } } application = new AriesApplicationImpl (applicationMetadata, extraBundlesInfo, _localPlatform); application.setDeploymentMetadata(deploymentMetadata); // Store a reference to any modified bundles application.setModifiedBundles (modifiedBundles); } catch (IOException iox) { _logger.error ("APPMANAGEMENT0006E", new Object []{appPath, iox}); throw new ManagementException(iox); } return application; } private String buildAppContent(Set<BundleInfo> bundleInfos) { StringBuilder builder = new StringBuilder(); Iterator<BundleInfo> iterator = bundleInfos.iterator(); while (iterator.hasNext()) { BundleInfo info = iterator.next(); builder.append(info.getSymbolicName()); // bundle version is not a required manifest header if (info.getVersion() != null) { String version = info.getVersion().toString(); builder.append(";version=\"["); builder.append(version); builder.append(','); builder.append(version); builder.append("]\""); } if (iterator.hasNext()) { builder.append(","); } } return builder.toString(); } /** * Create an application from a URL. * The first version of this method isn't smart enough to check whether * the input URL is file:// */ public AriesApplication createApplication(URL url) throws ManagementException { OutputStream os = null; AriesApplication app = null; try { File tempFile = _localPlatform.getTemporaryFile(); InputStream is = url.openStream(); os = new FileOutputStream (tempFile); IOUtils.copy(is, os); IDirectory downloadedSource = FileSystem.getFSRoot(tempFile); app = createApplication (downloadedSource); } catch (IOException iox) { throw new ManagementException (iox); } finally { IOUtils.close(os); } return app; } public AriesApplication resolve(AriesApplication originalApp, ResolveConstraint... constraints) throws ResolverException { AriesApplicationImpl application = new AriesApplicationImpl(originalApp.getApplicationMetadata(), originalApp.getBundleInfo(), _localPlatform); Manifest deploymentManifest = deploymentManifestManager.generateDeploymentManifest(originalApp, constraints); try { application.setDeploymentMetadata(_deploymentMetadataFactory.createDeploymentMetadata(deploymentManifest)); } catch (IOException ioe) { throw new ResolverException(ioe); } // Store a reference to any modified bundles if (originalApp instanceof AriesApplicationImpl) { // TODO: are we really passing streams around ? application.setModifiedBundles(((AriesApplicationImpl) originalApp).getModifiedBundles()); } return application; } public AriesApplicationContext install(AriesApplication app) throws BundleException, ManagementException, ResolverException { if (!app.isResolved()) { app = resolve(app); } // Register an Application Repository for this application if none exists String appScope = app.getApplicationMetadata().getApplicationScope(); ServiceReference[] ref = null; try { String filter = "(" + BundleRepository.REPOSITORY_SCOPE + "=" + appScope + ")"; ref = _bundleContext.getServiceReferences(BundleRepository.class.getName(),filter); } catch (InvalidSyntaxException e) { // Something went wrong attempting to find a service so we will act as if // there is no existing service. } if (ref == null || ref.length == 0) { Dictionary dict = new Hashtable(); dict.put(BundleRepository.REPOSITORY_SCOPE, appScope); ServiceRegistration serviceReg = _bundleContext.registerService(BundleRepository.class.getName(), new ApplicationRepository(app), dict); serviceRegistrations.put(app, serviceReg); } AriesApplicationContext result = _applicationContextManager.getApplicationContext(app); // When installing bundles in the .eba file we use the jar url scheme. This results in a // JarFile being held open, which is bad as on windows we cannot delete the .eba file // so as a work around we open a url connection to one of the bundles in the eba and // if it is a jar url we close the associated JarFile. Iterator<BundleInfo> bi = app.getBundleInfo().iterator(); if (bi.hasNext()) { String location = bi.next().getLocation(); if (location.startsWith("jar")) { try { URL url = new URL(location); JarURLConnection urlc = (JarURLConnection) url.openConnection(); // Make sure that we pick up the cached version rather than creating a new one urlc.setUseCaches(true); urlc.getJarFile().close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return result; } public void uninstall(AriesApplicationContext appContext) throws BundleException { _applicationContextManager.remove(appContext); // Also unregister the service if we added one for it AriesApplication app = appContext.getApplication(); if (app != null) { ServiceRegistration reg = serviceRegistrations.remove(app); if (reg != null) try { reg.unregister(); } catch (IllegalStateException e) { // Must be already unregistered - ignore } } } public void addApplicationListener(AriesApplicationListener l) { // Need application listener lifecycle support } public void removeApplicationListener(AriesApplicationListener l) { // TODO Auto-generated method stub } /** * Locate and parse an application.mf in an eba * @param source An aries application file * @return parsed manifest, or an empty Manifest * @throws IOException */ private Manifest parseApplicationManifest (IDirectory source) throws IOException { Manifest result = new Manifest(); IFile f = source.getFile(AppConstants.APPLICATION_MF); if (f != null) { InputStream is = null; try { is = f.open(); result = ManifestProcessor.parseManifest(is); } catch (IOException iox) { _logger.error ("APPMANAGEMENT0007E", new Object[]{source.getName(), iox}); throw iox; } finally { IOUtils.close(is); } } return result; } /** * Extract a bundle manifest from an IFile representing a bundle * @param file The bundle to extract the manifest from * @return bundle manifest */ private BundleManifest getBundleManifest(IFile file) throws IOException { BundleManifest mf = null; InputStream in = null; try { in = file.open(); mf = BundleManifest.fromBundle(in); } finally { IOUtils.close(in); } return mf; } public AriesApplicationContext update(AriesApplication app, DeploymentMetadata depMf) throws UpdateException { if (!(app instanceof AriesApplicationImpl)) throw new IllegalArgumentException("Argument is not AriesApplication created by this manager"); if (!!!app.getApplicationMetadata().getApplicationSymbolicName().equals(depMf.getApplicationSymbolicName()) || !!!app.getApplicationMetadata().getApplicationVersion().equals(depMf.getApplicationVersion())) { throw new IllegalArgumentException("The deployment metadata does not match the application."); } DeploymentMetadata oldMetadata = app.getDeploymentMetadata(); AriesApplicationContext foundCtx = null; for (AriesApplicationContext ctx : _applicationContextManager.getApplicationContexts()) { if (ctx.getApplication().equals(app)) { foundCtx = ctx; break; } } ((AriesApplicationImpl) app).setDeploymentMetadata(depMf); if (foundCtx != null) { try { return _applicationContextManager.update(app, oldMetadata); } catch (UpdateException ue) { if (ue.hasRolledBack()) { ((AriesApplicationImpl) app).setDeploymentMetadata(oldMetadata); } throw ue; } } else { return null; } } }
8,911
0
Create_ds/aries/application/application-management/src/main/java/org/apache/aries/application/management
Create_ds/aries/application/application-management/src/main/java/org/apache/aries/application/management/impl/AriesApplicationImpl.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.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; 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.DeploymentMetadata; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.spi.convert.BundleConversion; import org.apache.aries.application.management.spi.runtime.LocalPlatform; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.util.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AriesApplicationImpl implements AriesApplication { private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.application.management"); private Set<BundleInfo> _bundleInfo; private ApplicationMetadata _applicationMetadata; private DeploymentMetadata _deploymentMetadata; private LocalPlatform _localPlatform; // Placeholders for information we'll need for store() private Map<String, BundleConversion> _modifiedBundles = null; public AriesApplicationImpl(ApplicationMetadata meta, Set<BundleInfo> bundleInfo, LocalPlatform lp) { _applicationMetadata = meta; _bundleInfo = bundleInfo; _deploymentMetadata = null; _localPlatform = lp; } public AriesApplicationImpl(ApplicationMetadata meta, DeploymentMetadata dep, Set<BundleInfo> bundleInfo, LocalPlatform lp) { _applicationMetadata = meta; _bundleInfo = bundleInfo; _deploymentMetadata = dep; _localPlatform = lp; } public ApplicationMetadata getApplicationMetadata() { return _applicationMetadata; } public Set<BundleInfo> getBundleInfo() { return _bundleInfo; } public DeploymentMetadata getDeploymentMetadata() { return _deploymentMetadata; } public void setDeploymentMetadata (DeploymentMetadata dm) { _deploymentMetadata = dm; } public Map<String, BundleConversion> getModifiedBundles() { return _modifiedBundles; } public void setModifiedBundles (Map<String, BundleConversion> modifiedBundles) { _modifiedBundles = modifiedBundles; } public void setLocalPlatform (LocalPlatform lp) { _localPlatform = lp; } public boolean isResolved() { return getDeploymentMetadata() != null; } public void store(File f) throws FileNotFoundException, IOException { if (f.isDirectory()) { storeInDirectory(f); } else { OutputStream os = new FileOutputStream (f); store(os); os.close(); } } /** * Construct an eba in a temporary directory * Copy the eba to the target output stream * Delete the temporary directory. * Leave target output stream open */ public void store(OutputStream targetStream) throws FileNotFoundException, IOException { // // This code will be run on various application server platforms, each of which // will have its own policy about where to create temporary directories. We // can't just ask the local filesystem for a temporary directory since it may // be quite large: the app server implementation will be better able to select // an appropriate location. File tempDir = _localPlatform.getTemporaryDirectory(); storeInDirectory(tempDir); // We now have an exploded eba in tempDir which we need to copy into targetStream IOUtils.zipUp(tempDir, targetStream); if (!IOUtils.deleteRecursive(tempDir)) { _logger.warn("APPMANAGEMENT0001E", tempDir); } } private void storeInDirectory(File dir) throws IOException, MalformedURLException { OutputStream out = null; InputStream in = null; try { out = IOUtils.getOutputStream(dir, AppConstants.APPLICATION_MF); _applicationMetadata.store(out); } finally { IOUtils.close(out); } if (_deploymentMetadata != null) { try { out = IOUtils.getOutputStream(dir, AppConstants.DEPLOYMENT_MF); _deploymentMetadata.store(out); } finally { IOUtils.close(out); } } // Write the by-value eba files out for (BundleInfo bi : _bundleInfo) { // bi.getLocation() will return a URL to the source bundle. It may be of the form // file:/path/to/my/file.jar, or // jar:file:/my/path/to/eba.jar!/myBundle.jar String bundleLocation = bi.getLocation(); String bundleFileName = bundleLocation.substring(bundleLocation.lastIndexOf('/') + 1); try { out = IOUtils.getOutputStream(dir, bundleFileName); URL bundleURL = new URL (bundleLocation); InputStream is = bundleURL.openStream(); IOUtils.copy(is, out); } finally { IOUtils.close(out); IOUtils.close(in); } } // Write the migrated bundles out if (_modifiedBundles != null) { for (Map.Entry<String, BundleConversion> modifiedBundle : _modifiedBundles.entrySet()) { try { out = IOUtils.getOutputStream(dir, modifiedBundle.getKey()); IOUtils.copy(modifiedBundle.getValue().getInputStream(), out); } finally { IOUtils.close(out); } } } } }
8,912
0
Create_ds/aries/application/application-management/src/main/java/org/apache/aries/application/management
Create_ds/aries/application/application-management/src/main/java/org/apache/aries/application/management/repository/ApplicationRepository.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.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.BundleInfo; 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.resolve.AriesApplicationResolver; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.Version; public class ApplicationRepository implements BundleRepository { private static final int REPOSITORY_COST = 0; private AriesApplication app; AriesApplicationResolver resolver; public ApplicationRepository(AriesApplication app) { this.app = app; } public int getCost() { return REPOSITORY_COST; } public BundleSuggestion suggestBundleToUse(DeploymentContent content) { BundleInfo bundleInfo = null; if ((app.getBundleInfo() != null) && (!app.getBundleInfo().isEmpty())) { for (BundleInfo bi : app.getBundleInfo()) { if (bi.getSymbolicName().equals(content.getContentName()) && (bi.getVersion().equals(content.getVersion().getExactVersion()))) { bundleInfo = bi; break; } } } if (bundleInfo != null) { return new BundleSuggestionImpl(bundleInfo); } else { return null; } } private class BundleSuggestionImpl implements BundleSuggestion { private final BundleInfo bundleInfo; BundleSuggestionImpl(BundleInfo bundleInfo) { this.bundleInfo = bundleInfo; } public int getCost() { return REPOSITORY_COST; } public Set<Content> getExportPackage() { if (bundleInfo != null) { return bundleInfo.getExportPackage(); } else { return null; } } public Set<Content> getImportPackage() { if (bundleInfo != null) { return bundleInfo.getImportPackage(); } else { return null; } } public Version getVersion() { if (bundleInfo != null) { return bundleInfo.getVersion(); } else { return null; } } public Bundle install(BundleFramework framework, AriesApplication app) throws BundleException { if (bundleInfo != null ) { return framework.getIsolatedBundleContext().installBundle(bundleInfo.getLocation()); } else { throw new BundleException("Unable to install the bundle, as the BundleInfo is null."); } } } }
8,913
0
Create_ds/aries/application/application-management/src/main/java/org/apache/aries/application/management
Create_ds/aries/application/application-management/src/main/java/org/apache/aries/application/management/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.management.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.management.messages.AppManagementMessages"); /** * 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,914
0
Create_ds/aries/application/application-converters/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-converters/src/main/java/org/apache/aries/application/converters/WabConverterService.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.converters; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.application.management.spi.convert.BundleConversion; import org.apache.aries.application.management.spi.convert.BundleConverter; import org.apache.aries.application.utils.management.SimpleBundleInfo; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; import org.apache.aries.util.manifest.BundleManifest; import org.apache.aries.web.converter.WabConversion; import org.apache.aries.web.converter.WarToWabConverter; import org.apache.aries.web.converter.WarToWabConverter.InputStreamProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WabConverterService implements BundleConverter { private static final String WAR_FILE_EXTENSION = ".war"; private static final Logger LOGGER = LoggerFactory.getLogger(WabConverterService.class); private WarToWabConverter wabConverter; public WarToWabConverter getWabConverter() { return wabConverter; } public void setWabConverter(WarToWabConverter wabConverter) { this.wabConverter = wabConverter; } public BundleConversion convert(IDirectory parentEba, final IFile toBeConverted) { if (toBeConverted.getName().endsWith(WAR_FILE_EXTENSION)) { try { final WabConversion conversion = wabConverter.convert(new InputStreamProvider() { public InputStream getInputStream() throws IOException { return toBeConverted.open(); } }, toBeConverted.getName(), new Properties()); return new BundleConversion() { public BundleInfo getBundleInfo() throws IOException { return new SimpleBundleInfo(BundleManifest.fromBundle(conversion.getWAB()), toBeConverted.toString()); } public InputStream getInputStream() throws IOException { return conversion.getWAB(); } }; } catch (IOException e) { LOGGER.error("Encountered an exception while converting " + toBeConverted.getName() + " in " + parentEba.getName(), e); } } return null; } }
8,915
0
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework/BundleFrameworkFactoryImpl.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; 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.BundleFrameworkFactory; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceReference; import org.osgi.service.framework.CompositeBundle; import org.osgi.service.framework.CompositeBundleFactory; public class BundleFrameworkFactoryImpl implements BundleFrameworkFactory { public BundleFramework createBundleFramework(BundleContext bc, BundleFrameworkConfiguration config) throws BundleException { BundleFramework framework = null; ServiceReference sr = bc.getServiceReference(CompositeBundleFactory.class.getName()); if (sr != null) { CompositeBundleFactory cbf = (CompositeBundleFactory) bc.getService(sr); CompositeBundle compositeBundle = cbf.installCompositeBundle( config.getFrameworkProperties(), config.getFrameworkID(), config.getFrameworkManifest()); framework = new BundleFrameworkImpl(compositeBundle); } else throw new BundleException("Failed to obtain framework factory service"); return framework; } }
8,916
0
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework/BundleFrameworkImpl.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; 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.List; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.spi.framework.BundleFramework; 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; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.osgi.framework.ServiceReference; import org.osgi.framework.launch.Framework; import org.osgi.service.framework.CompositeBundle; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; import org.osgi.util.tracker.ServiceTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BundleFrameworkImpl implements BundleFramework { private static final Logger LOGGER = LoggerFactory.getLogger(BundleFrameworkImpl.class); List<Bundle> _bundles; CompositeBundle _compositeBundle; Framework _framework; ServiceTracker _packageAdminTracker; private final AtomicBoolean startLevelIncreased = new AtomicBoolean(false); BundleFrameworkImpl(CompositeBundle cb) { _compositeBundle = cb; _framework = cb.getCompositeFramework(); _bundles = new ArrayList<Bundle>(); } @Override public void start() throws BundleException { _compositeBundle.getCompositeFramework().init(); _compositeBundle.start(Bundle.START_ACTIVATION_POLICY); if ( _packageAdminTracker == null) { _packageAdminTracker = new ServiceTracker(_compositeBundle.getCompositeFramework().getBundleContext(), PackageAdmin.class.getName(), null); _packageAdminTracker.open(); } // make sure inner bundles are now startable if (startLevelIncreased.compareAndSet(false, true)) { increaseStartLevel(_compositeBundle.getCompositeFramework().getBundleContext()); } } @Override public void init() throws BundleException { if (_compositeBundle.getCompositeFramework().getState() != Framework.ACTIVE) { _compositeBundle.getCompositeFramework().start(); _packageAdminTracker = new ServiceTracker(_compositeBundle.getCompositeFramework().getBundleContext(), PackageAdmin.class.getName(), null); _packageAdminTracker.open(); setupStartLevelToPreventAutostart(_compositeBundle.getCompositeFramework().getBundleContext()); } } /** * Name says it all if we don't make some adjustments bundles will be autostarted, which in the * grand scheme of things causes extenders to act on the inner bundles before the outer composite is even * resolved ... */ private void setupStartLevelToPreventAutostart(BundleContext frameworkBundleContext) { ServiceReference ref = frameworkBundleContext.getServiceReference(StartLevel.class.getName()); if (ref != null) { StartLevel sl = (StartLevel) frameworkBundleContext.getService(ref); if (sl != null) { // make sure new bundles are *not* automatically started (because that causes havoc) sl.setInitialBundleStartLevel(sl.getStartLevel()+1); frameworkBundleContext.ungetService(ref); } } } private void increaseStartLevel(BundleContext context) { /* * Algorithm for doing this * * 1. Set up a framework listener that will tell us when the start level has been set. * * 2. Change the start level. This is asynchronous so by the time the method returned the event * could have been sent. This is why we set up the listener in step 1. * * 3. Wait until the start level has been set appropriately. At this stage all the bundles are startable * and some have been started (most notably lazy activated bundles it appears). Other bundles are still * in resolved state. */ ServiceReference ref = context.getServiceReference(StartLevel.class.getName()); if (ref != null) { StartLevel sl = (StartLevel) context.getService(ref); if (sl != null) { final Semaphore waitForStartLevelChangedEventToOccur = new Semaphore(0); // step 1 FrameworkListener listener = new FrameworkListener() { public void frameworkEvent(FrameworkEvent event) { if (event.getType() == FrameworkEvent.STARTLEVEL_CHANGED) { waitForStartLevelChangedEventToOccur.release(); } } }; context.addFrameworkListener(listener); // step 2 sl.setStartLevel(sl.getStartLevel()+1); // step 3 try { if (!!!waitForStartLevelChangedEventToOccur.tryAcquire(60, TimeUnit.SECONDS)) { LOGGER.debug("Starting CBA child bundles took longer than 60 seconds"); } } catch (InterruptedException e) { // restore the interrupted status Thread.currentThread().interrupt(); } context.removeFrameworkListener(listener); } context.ungetService(ref); } } public void close() throws BundleException { // close out packageadmin service tracker if (_packageAdminTracker != null) { try { _packageAdminTracker.close(); } catch (IllegalStateException ise) { // Ignore this error because this can happen when we're trying to close the tracker on a // framework that has closed/is closing. } } // We used to call stop before uninstall but this seems to cause NPEs in equinox. It isn't // all the time, but I put in a change to resolution and it started NPEing all the time. This // was because stop caused everything to go back to the RESOLVED state, so equinox inited the // framework during uninstall and then tried to get the surrogate bundle, but init did not // create a surroage, so we got an NPE. I removed the stop and added this comment in the hope // that the stop doesn't get added back in. _compositeBundle.uninstall(); } public void start(Bundle b) throws BundleException { if (b.getState() != Bundle.ACTIVE && !isFragment(b)) b.start(Bundle.START_ACTIVATION_POLICY); } public void stop(Bundle b) throws BundleException { if (!isFragment(b)) b.stop(); } public Bundle getFrameworkBundle() { return _compositeBundle; } public BundleContext getIsolatedBundleContext() { return _compositeBundle.getCompositeFramework().getBundleContext(); } public List<Bundle> getBundles() { // Ensure our bundle list is refreshed ArrayList latestBundles = new ArrayList<Bundle>(); for (Bundle appBundle : _framework.getBundleContext().getBundles()) { for (Bundle cachedBundle : _bundles) { // Look for a matching name and version (this doesnt make it the same bundle // but it means we find the one we want) if (cachedBundle.getSymbolicName().equals(appBundle.getSymbolicName()) && cachedBundle.getVersion().equals(appBundle.getVersion())) { // Now check if it has changed - the equals method will check more thoroughly // to ensure this is the exact bundle we cached. if (!cachedBundle.equals(appBundle)) latestBundles.add(appBundle); // bundle updated else latestBundles.add(cachedBundle); // bundle has not changed } } } _bundles = latestBundles; return _bundles; } /** * This method uses the PackageAdmin service to identify if a bundle * is a fragment. * @param b * @return */ private boolean isFragment(Bundle b) { LOGGER.debug(LOG_ENTRY, "isFragment", new Object[] { b }); PackageAdmin admin = null; boolean isFragment = false; try { if (_packageAdminTracker != null) { admin = (PackageAdmin) _packageAdminTracker.getService(); if (admin != null) { isFragment = (admin.getBundleType(b) == PackageAdmin.BUNDLE_TYPE_FRAGMENT); } } } catch (RuntimeException re) { LOGGER.debug(LOG_EXCEPTION, re); } LOGGER.debug(LOG_EXIT, "isFragment", new Object[] { Boolean.valueOf(isFragment) }); return isFragment; } public Bundle install(BundleSuggestion suggestion, AriesApplication app) throws BundleException { Bundle installedBundle = suggestion.install(this, app); _bundles.add(installedBundle); return installedBundle; } public void uninstall(Bundle b) throws BundleException { b.uninstall(); _bundles.remove(b); } }
8,917
0
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework/config/BundleFrameworkConfigurationFactoryImpl.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.config; import java.util.Collection; import java.util.Properties; import org.apache.aries.application.Content; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.spi.framework.BundleFrameworkConfiguration; import org.apache.aries.application.management.spi.framework.BundleFrameworkConfigurationFactory; import org.apache.aries.application.runtime.framework.utils.EquinoxFrameworkConstants; import org.apache.aries.application.runtime.framework.utils.EquinoxFrameworkUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; public class BundleFrameworkConfigurationFactoryImpl implements BundleFrameworkConfigurationFactory { public BundleFrameworkConfiguration createBundleFrameworkConfig(String frameworkId, BundleContext parentCtx, AriesApplication app) { BundleFrameworkConfiguration config = null; DeploymentMetadata metadata = app.getDeploymentMetadata(); /** * Set up framework config properties */ Properties frameworkConfig = new Properties(); // Problems occur if the parent framework has osgi.console set because the child framework // will also attempt to listen on the same port which will cause port clashs. Setting this // to null essentially turns the console off. frameworkConfig.put("osgi.console", "none"); String flowedSystemPackages = EquinoxFrameworkUtils.calculateSystemPackagesToFlow( EquinoxFrameworkUtils.getSystemExtraPkgs(parentCtx), metadata.getImportPackage()); frameworkConfig.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, flowedSystemPackages); /** * Set up BundleManifest for the framework bundle */ Properties frameworkBundleManifest = new Properties(); frameworkBundleManifest.put(Constants.BUNDLE_SYMBOLICNAME, metadata .getApplicationSymbolicName()); frameworkBundleManifest.put(Constants.BUNDLE_VERSION, metadata.getApplicationVersion() .toString()); /** * Set up Import-Package header for framework manifest */ // Extract the import packages and remove anything we already have available in the current framework Collection<Content> imports = EquinoxFrameworkUtils.calculateImports(metadata .getImportPackage(), EquinoxFrameworkUtils.getExportPackages(parentCtx)); if (imports != null && !imports.isEmpty()) { StringBuffer buffer = new StringBuffer(); for (Content i : imports) buffer.append(EquinoxFrameworkUtils.contentToString(i) + ","); frameworkBundleManifest.put(Constants.IMPORT_PACKAGE, buffer .substring(0, buffer.length() - 1)); } /** * Set up CompositeServiceFilter-Import header for framework manifest */ StringBuilder serviceImportFilter = new StringBuilder(); String txRegsitryImport = "(" + Constants.OBJECTCLASS + "=" + EquinoxFrameworkConstants.TRANSACTION_REGISTRY_BUNDLE + ")"; Collection<Filter> deployedServiceImports = metadata.getDeployedServiceImport(); //if there are more services than the txRegistry import a OR group is required for the Filter if (deployedServiceImports.size() > 0){ serviceImportFilter.append("(|"); } for (Filter importFilter : metadata.getDeployedServiceImport()) { serviceImportFilter.append(importFilter.toString()); } serviceImportFilter.append(txRegsitryImport); //close the OR group if needed if (deployedServiceImports.size() > 0){ serviceImportFilter.append(")"); } frameworkBundleManifest.put(EquinoxFrameworkConstants.COMPOSITE_SERVICE_FILTER_IMPORT, serviceImportFilter.toString()); config = new BundleFrameworkConfigurationImpl(frameworkId, frameworkConfig, frameworkBundleManifest); return config; } public BundleFrameworkConfiguration createBundleFrameworkConfig(String frameworkId, BundleContext parentCtx) { BundleFrameworkConfiguration config = null; // Set up framework config properties Properties frameworkConfig = new Properties(); // Problems occur if the parent framework has osgi.console set because the child framework // will also attempt to listen on the same port which will cause port clashs. Setting this // to null essentially turns the console off. frameworkConfig.put("osgi.console", "none"); if (parentCtx.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA) != null) frameworkConfig.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, parentCtx .getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA)); /** * Set up BundleManifest for the framework bundle */ Properties frameworkBundleManifest = new Properties(); /** * Set up CompositeServiceFilter-Import header for framework manifest */ StringBuffer serviceImportFilter = new StringBuffer("(" + Constants.OBJECTCLASS + "=" + EquinoxFrameworkConstants.TRANSACTION_REGISTRY_BUNDLE + ")"); frameworkBundleManifest.put(EquinoxFrameworkConstants.COMPOSITE_SERVICE_FILTER_IMPORT, serviceImportFilter.toString()); config = new BundleFrameworkConfigurationImpl(frameworkId, frameworkConfig, frameworkBundleManifest); return config; } }
8,918
0
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework/config/BundleFrameworkConfigurationImpl.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.config; import java.util.Properties; import org.apache.aries.application.management.spi.framework.BundleFrameworkConfiguration; public class BundleFrameworkConfigurationImpl implements BundleFrameworkConfiguration { private String frameworkId; private Properties frameworkBundleManifest; private Properties frameworkConfig; public BundleFrameworkConfigurationImpl(String frameworkId, Properties frameworkConfig, Properties frameworkBundleManifest) { this.frameworkId = frameworkId; this.frameworkConfig = frameworkConfig; this.frameworkBundleManifest = frameworkBundleManifest; } public String getFrameworkID() { return frameworkId; } public Properties getFrameworkManifest() { return frameworkBundleManifest; } public Properties getFrameworkProperties() { return frameworkConfig; } }
8,919
0
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework/utils/EquinoxFrameworkConstants.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.utils; public interface EquinoxFrameworkConstants { public static final String TRANSACTION_BUNDLE = "javax.transaction"; public static final String TRANSACTION_BUNDLE_VERSION = "1.1.0"; public static final String TRANSACTION_REGISTRY_BUNDLE = "javax.transaction.TransactionSynchronizationRegistry"; public static final String COMPOSITE_SERVICE_FILTER_IMPORT = "CompositeServiceFilter-Import"; }
8,920
0
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework
Create_ds/aries/application/application-runtime-framework/src/main/java/org/apache/aries/application/runtime/framework/utils/EquinoxFrameworkUtils.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.utils; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.aries.application.Content; import org.apache.aries.application.utils.manifest.ContentFactory; import org.apache.aries.util.VersionRange; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.aries.util.manifest.ManifestHeaderProcessor.NameValuePair; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Version; public class EquinoxFrameworkUtils { public static Collection<Content> getExportPackages(BundleContext isolatedBundleContext) { Set<Content> exports = new HashSet<Content>(); Bundle sysBundle = isolatedBundleContext.getBundle(0); if (sysBundle != null && sysBundle.getHeaders() != null) { String exportString = (String) sysBundle.getHeaders().get(Constants.EXPORT_PACKAGE); if (exportString != null) { for (NameValuePair nvp : ManifestHeaderProcessor .parseExportString(exportString)) exports.add(ContentFactory.parseContent(nvp.getName(), nvp.getAttributes())); } } return Collections.unmodifiableSet(exports); } public static Collection<Content> getSystemExtraPkgs(BundleContext context) { Set<Content> extraPkgs = new HashSet<Content>(); String exportString = context.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA); if (exportString != null) { for (NameValuePair nvp : ManifestHeaderProcessor .parseExportString(exportString)) extraPkgs.add(ContentFactory.parseContent(nvp.getName(), nvp.getAttributes())); } return Collections.unmodifiableSet(extraPkgs); } public static Collection<Content> calculateImports(final Collection<Content> importPackage, final Collection<Content> exportPackages) { Set<Content> results = new HashSet<Content>(); if (importPackage != null && !importPackage.isEmpty()) { for (Content exportPkg : exportPackages) { for (Content importPkg : importPackage) { if (!(importPkg.getContentName().equals(exportPkg.getContentName()) && importPkg.getVersion().equals(exportPkg.getVersion()))) { results.add(importPkg); } } } } return Collections.unmodifiableSet(results); } public static String contentToString(Content content) { StringBuffer value = new StringBuffer(); value.append(content.getContentName()); Map<String, String> nvm = content.getNameValueMap(); for (Map.Entry<String, String> entry : nvm.entrySet()) { if (entry.getKey().equalsIgnoreCase(Constants.VERSION_ATTRIBUTE) || entry.getKey().equalsIgnoreCase(Constants.BUNDLE_VERSION_ATTRIBUTE)) { value.append(";" + entry.getKey() + "=\"" + entry.getValue() + "\""); } else { value.append(";" + entry.getKey() + "=" + entry.getValue()); } } return value.toString(); } /** * Calculates which system packages should be flowed * to a child framework based on what packages the * child framework imports. Equinox will require anything imported by the * child framework which is available from the system bundle * in the parent framework to come from the system bundle * in the child framework. However, we don't want to flow * all the extra system packages by default since we want CBAs * which use them to explicitly import them. * @param importPackage * @return * @throws CompositeBundleCalculateException */ public static String calculateSystemPackagesToFlow(final Collection<Content> systemExports, final Collection<Content> imports) { // Let's always set javax.transaction as system extra packages because of the split package. // It is reasonable to do so because we always flow userTransaction service into child framework anyway. Map<String, String> map = new HashMap<String, String>(); map.put(EquinoxFrameworkConstants.TRANSACTION_BUNDLE, EquinoxFrameworkConstants.TRANSACTION_BUNDLE_VERSION); Map<String, Map<String, String>> resultMap = new HashMap<String, Map<String, String>>(); resultMap.put(EquinoxFrameworkConstants.TRANSACTION_BUNDLE, map); // let's go through the import list to build the resultMap for (Content nvp : imports) { String name = nvp.getContentName().trim(); // if it exist in the list of packages exported by the system, we need to add it to the result if (existInExports(name, nvp.getNameValueMap(), systemExports)) { /* We've now ensured the versions match, but not worried too * much about other constraints like company or any of the * other things which could be added to a version statement. * We don't want to flow system packages we don't need to, * but we're not in the business of provisioning, so we'll * let OSGi decide whether every constraint is satisfied * and resolve the bundle or not, as appropriate. */ for (Content nvpp : systemExports) { if (nvpp.getContentName().trim().equals(name)) { Map<String, String> frameworkVersion = nvpp.getNameValueMap(); resultMap.put(name, frameworkVersion); // We don't break here since we're too lazy to check the version // again and so we might end up flowing multiple statements for the // same package (but with different versions). Better this than // accidentally flowing the wrong version if we hit it first. } } } } StringBuffer result = new StringBuffer(); for (String key : resultMap.keySet()) { result.append(getString(key, resultMap) + ","); } String toReturn = trimEndString(result.toString().trim(), ","); return toReturn; } /** * check if the value in nvm already exist in the exports * @param key * @param nvm * @param exports * @return boolean whether the value in nvm already exist in the exports */ private static boolean existInExports(String key, Map<String, String> nvm, final Collection<Content> exports) { boolean value = false; for (Content nvp : exports) { if (nvp.getContentName().trim().equals(key.trim())) { // ok key equal. let's check the version // if version is higher, we still want to import, for example javax.transaction;version=1.1 String vi = nvm.get(Constants.VERSION_ATTRIBUTE); String ve = nvp.getNameValueMap().get(Constants.VERSION_ATTRIBUTE); if (vi == null || vi.length() == 0) { vi = "0.0.0"; } if (ve == null || ve.length() == 0) { ve = "0.0.0"; } if (vi.indexOf(",") == -1) { if (new Version(vi).compareTo(new Version(ve)) <= 0) { // we got it covered in our exports value = true; } } else { // parse vi into version range. VersionRange vri = ManifestHeaderProcessor.parseVersionRange(vi); Version minV = vri.getMinimumVersion(); Version maxV = vri.getMaximumVersion(); if (minV.compareTo(new Version(ve)) < 0 && maxV.compareTo(new Version(ve)) > 0) { value = true; } else if (minV.compareTo(new Version(ve)) == 0 && !!!vri.isMinimumExclusive()) { value = true; } else if (maxV.compareTo(new Version(ve)) == 0 && !!!vri.isMaximumExclusive()) { value = true; } } } } return value; } private static String trimEndString(String s, String trim) { if (s.startsWith(trim)) { s = s.substring(trim.length()); } if (s.endsWith(trim)) { s = s.substring(0, s.length() - trim.length()); } return s; } private static String getString(String key, Map<String, Map<String, String>> imports) { StringBuffer value = new StringBuffer(); value.append(key); Map<String, String> nvm = imports.get(key); for (Map.Entry<String, String> entry : nvm.entrySet()) { if (entry.getKey().equalsIgnoreCase(Constants.VERSION_ATTRIBUTE) || entry.getKey().equalsIgnoreCase(Constants.BUNDLE_VERSION_ATTRIBUTE)) { value.append(";" + entry.getKey() + "=\"" + entry.getValue() + "\""); } else { value.append(";" + entry.getKey() + "=" + entry.getValue()); } } return value.toString(); } }
8,921
0
Create_ds/aries/application/application-default-local-platform/src/main/java/org/apache/aries/application/local/platform
Create_ds/aries/application/application-default-local-platform/src/main/java/org/apache/aries/application/local/platform/impl/DefaultLocalPlatform.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.local.platform.impl; import java.io.File; import java.io.IOException; import org.apache.aries.application.management.spi.runtime.LocalPlatform; public class DefaultLocalPlatform implements LocalPlatform { public File getTemporaryDirectory() throws IOException { File f = File.createTempFile("ebaTmp", null); f.delete(); f.mkdir(); return f; } public File getTemporaryFile () throws IOException { return File.createTempFile("ebaTmp", null); } }
8,922
0
Create_ds/aries/application/application-itest-interface/src/main/java/org/apache/aries
Create_ds/aries/application/application-itest-interface/src/main/java/org/apache/aries/sample/HelloWorldManager.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.sample; public interface HelloWorldManager { int getNumOfHelloServices(); }
8,923
0
Create_ds/aries/application/application-itest-interface/src/main/java/org/apache/aries
Create_ds/aries/application/application-itest-interface/src/main/java/org/apache/aries/sample/HelloWorld.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.sample; public interface HelloWorld { public String getMessage(); }
8,924
0
Create_ds/aries/application/application-tooling-repository-generator/src/main/java/org/apache/aries/application/repository
Create_ds/aries/application/application-tooling-repository-generator/src/main/java/org/apache/aries/application/repository/generator/AriesRepositoryGenerator.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.repository.generator; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import org.apache.aries.application.management.spi.repository.RepositoryGenerator; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.launch.Framework; import org.osgi.framework.launch.FrameworkFactory; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.util.tracker.ServiceTracker; public class AriesRepositoryGenerator { private Framework framework = null; private List<String> ignoreList = new ArrayList<String>(); private List<ServiceTracker> srs = new ArrayList<ServiceTracker>(); public static final long DEFAULT_TIMEOUT = 60000; public static final String ERROR_LEVEL = "ERROR"; public static final String DEFAULT_REPO_NAME="repository.xml"; /** * Start OSGi framework and install the necessary bundles * @return * @throws BundleException */ public BundleContext startFramework() throws BundleException{ ServiceLoader<FrameworkFactory> factoryLoader = ServiceLoader.load(FrameworkFactory.class, getClass().getClassLoader()); Iterator<FrameworkFactory> factoryIterator = factoryLoader.iterator(); //Map<String, String> osgiPropertyMap = new HashMap<String, String>(); if (!!!factoryIterator.hasNext()) { System.out.println( "Unable to locate the osgi jar"); } try { FrameworkFactory frameworkFactory = factoryIterator.next(); framework = frameworkFactory.newFramework(Collections.EMPTY_MAP); } catch (ServiceConfigurationError sce) { sce.printStackTrace(); } framework.init(); framework.start(); // install the bundles in the current directory Collection<Bundle> installedBundles = new ArrayList<Bundle>(); File bundleDir = new File("."); File[] jars = bundleDir.listFiles(); try { for (File jar : jars) { if (jar.isFile() && (jar.getName().endsWith(".jar"))) { String location = URLDecoder.decode(jar.toURI().toURL().toExternalForm(), "UTF-8"); if (shouldInstall(location, getIgnoreList())) { installedBundles.add(framework.getBundleContext().installBundle( "reference:" + location)); } } } } catch (Exception e) { e.printStackTrace(); } ServiceReference paRef = framework.getBundleContext().getServiceReference(PackageAdmin.class.getCanonicalName()); if (paRef != null) { try { PackageAdmin admin = (PackageAdmin) framework.getBundleContext().getService(paRef); admin.resolveBundles(installedBundles.toArray(new Bundle[installedBundles.size()])); } finally { framework.getBundleContext().ungetService(paRef); } } else { System.out.println("Unable to find the service reference for package admin"); } //start the bundles //loop through the list of installed bundles to start them for (Bundle bundle : installedBundles) { try { if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) == null) { //start the bundle using its activiation policy bundle.start(Bundle.START_ACTIVATION_POLICY); } else { //nothing to start, we have got a fragment } } catch (BundleException e) { e.printStackTrace(); continue; } } return framework.getBundleContext(); } private void stopFramework() throws Exception{ for (ServiceTracker st : srs) { if (st != null) { st.close(); } } if (framework != null) { framework.stop(); } } private Object getOsgiService(BundleContext bc, String className) { ServiceTracker tracker = null; try { String flt = "(" + Constants.OBJECTCLASS + "=" + className + ")"; Filter osgiFilter = FrameworkUtil.createFilter(flt); tracker = new ServiceTracker(bc, osgiFilter, null); tracker.open(); // add tracker to the list of trackers we close at tear down srs.add(tracker); Object x = tracker.waitForService(DEFAULT_TIMEOUT); if (x == null) { throw new RuntimeException("Gave up waiting for service " + flt); } return x; } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("Invalid filter", e); } catch (InterruptedException e) { throw new RuntimeException(e); } } public static void usage() { System.out.println("Invalid parameter specifed. See program usage below."); System.out.println("========================= Usage ==============================="); System.out.println("Parameter list: [Reporsitory File Location] url1 [url2 url3 ...]"); System.out.println(); System.out.println("The parameter of the repository file location is the location for the genenerated reporsitory xml, e.g. /test/rep/repo.xml. It must end with .xml. If the parameter is not present, it will generate a repository.xml in the current directory."); System.out.println(); System.out.println("The paremater of url1 [url2 url 3 ...] is a list of urls. If the url starts with file:, it can be a directory, which means all jar or war files in that directory to be included in the reposiotry."); System.out.println("==============================================================="); } /** * Execute this program using * java -jar thisbundlename arg0 arg1... * arg0 can be the location of the repository xml or a url * arg1... a list of url. If there is a file url, all jar/wars under the url are to be included. * e.g. file:///c:/temp/, all jars/wars under temp or its subdirectory are to be included. * @param args */ public static void main(String[] args) { String[] urlArray = args; if (args.length == 0){ usage(); System.exit(0); } else { AriesRepositoryGenerator generator = new AriesRepositoryGenerator(); // set the system property for logging if not set in the command line String loggerLevelProp = "org.ops4j.pax.logging.DefaultServiceLog.level"; if (System.getProperty(loggerLevelProp) == null) { System.setProperty(loggerLevelProp, ERROR_LEVEL); } FileOutputStream fout = null; try { BundleContext ctx = generator.startFramework(); // get the object of repositoryGenerator and call its method File xmlFile = new File(DEFAULT_REPO_NAME); if (args[0].endsWith(".xml")) { xmlFile = new File(args[0]); // get the directors File parentDir = xmlFile.getAbsoluteFile().getParentFile(); if (!!!parentDir.exists()) { parentDir.mkdirs(); } // put the rest of the args to the list of urls if (args.length >1) { urlArray = Arrays.copyOfRange(args, 1, args.length); } else { usage(); System.exit(0); } } // Use reflection to get around the class loading issue fout = new FileOutputStream(xmlFile); Object repoGen = generator.getOsgiService(ctx, RepositoryGenerator.class.getName()); Class gen= repoGen.getClass(); Method m = gen.getDeclaredMethod("generateRepository", new Class[]{String[].class, OutputStream.class}); m.invoke(repoGen, urlArray, fout); generator.stopFramework(); System.out.println("The reporsitory xml was generated successfully under " + xmlFile.getAbsolutePath() + "."); } catch (Exception e) { e.printStackTrace(); System.exit(0); } finally { try { if (fout != null) fout.close(); } catch (IOException e) { fout = null; } } } } /** * Return whether to install the specified bundle * @param location bundle location * @param ignoreList the ignore list containing the bundles to be ignored * @return */ private boolean shouldInstall(String location, List<String> ignoreList) { String name = location.substring(location.lastIndexOf('/') + 1); //check that it isn't one of the files we should ignore boolean inIgnoreList = false; for (String prefix : ignoreList) { //we check for _ in case of version and .jar in case of a prefix.*.jar we should allow if (name.startsWith(prefix + "-") || name.startsWith(prefix + ".jar")) { inIgnoreList = true; break; } } return !!!inIgnoreList; } private List<String> getIgnoreList() { ignoreList.add("osgi"); ignoreList.add("org.apache.aries.application.obr.generator"); return ignoreList; } }
8,925
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/ModellerTest.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.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.jar.Manifest; import org.apache.aries.application.modelling.ExportedPackage; 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.ModelledResourceManager; import org.apache.aries.application.modelling.impl.ModelledResourceManagerImpl; import org.apache.aries.application.modelling.impl.ModellingManagerImpl; import org.apache.aries.application.modelling.impl.ParserProxyTest; import org.apache.aries.application.modelling.standalone.OfflineModellingFactory; import org.apache.aries.mocks.BundleContextMock; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.io.IOUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import static org.junit.Assert.*; @RunWith(Parameterized.class) public class ModellerTest { @Parameters public static List<Object[]> getDifferentModelledResourceManagers() { ModelledResourceManagerImpl manager = new ModelledResourceManagerImpl(); manager.setModellingManager(new ModellingManagerImpl()); manager.setParserProxy(ParserProxyTest.getMockParserServiceProxy()); manager.setModellingPlugins(Collections.<ServiceModeller>emptyList()); return Arrays.asList(new Object[][] { {OfflineModellingFactory.getModelledResourceManager()}, {manager} }); } @BeforeClass public static void setup() throws Exception { URL pathToTestBundle = ModellerTest.class.getClassLoader().getResource("test.bundle"); File testBundleDir = new File(pathToTestBundle.toURI()); File outputArchive = new File(testBundleDir.getParentFile(), "test.bundle.jar"); FileInputStream fis = new FileInputStream(new File(testBundleDir, "META-INF/MANIFEST.MF")); Manifest manifest = new Manifest(fis); fis.close(); IOUtils.jarUp(testBundleDir, outputArchive, manifest); } @AfterClass public static void cleanup() { BundleContextMock.clear(); } private final ModelledResourceManager sut; public ModellerTest(ModelledResourceManager sut) { this.sut = sut; } @Test public void testParsingByInputStreamProvider() throws Exception { final URL pathToTestBundle = getClass().getClassLoader().getResource("test.bundle.jar"); ModelledResource resource = sut.getModelledResource("file:///test.bundle.uri", new ModelledResourceManager.InputStreamProvider() { public InputStream open() throws IOException { return pathToTestBundle.openStream(); } } ); checkTestBundleResource(resource); } @Test public void testParsingOfBundle() throws Exception { URL pathToTestBundle = getClass().getClassLoader().getResource("test.bundle"); ModelledResource resource = sut.getModelledResource( "file:///test.bundle.uri", FileSystem.getFSRoot(new File(pathToTestBundle.toURI()))); checkTestBundleResource(resource); } private void checkTestBundleResource(ModelledResource resource) { assertNotNull(resource); assertEquals("file:///test.bundle.uri", resource.getLocation()); // sanity check that we have parsed the manifest and package imports / exports assertEquals("test.bundle", resource.getSymbolicName()); assertEquals("1.0.0", resource.getVersion()); assertEquals(1, resource.getExportedPackages().size()); assertEquals(3, resource.getImportedPackages().size()); boolean foundFirstPackage = false; for (ImportedPackage pack : resource.getImportedPackages()) { if ("javax.jms".equals(pack.getPackageName()) && "1.1.0".equals(pack.getVersionRange())) foundFirstPackage = true; } assertTrue(foundFirstPackage); ExportedPackage epack = resource.getExportedPackages().iterator().next(); assertEquals("wibble", epack.getPackageName()); assertEquals("1.0.0", epack.getVersion()); assertEquals("true", epack.getAttributes().get("directive:")); // sanity check that we have parsed the services assertEquals(4, resource.getExportedServices().size()); assertEquals(4, resource.getImportedServices().size()); boolean foundFirst = false; for (ImportedService service : resource.getImportedServices()) { if ("foo.bar.MyInjectedService".equals(service.getInterface())) { foundFirst = true; assertTrue(service.isOptional()); assertFalse(service.isList()); assertEquals("anOptionalReference", service.getId()); } } assertTrue(foundFirst); } }
8,926
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/impl/ParserProxyTest.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.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.aries.application.modelling.ModellingManager; import org.apache.aries.application.modelling.ParsedServiceElements; import org.apache.aries.application.modelling.ParserProxy; import org.apache.aries.application.modelling.WrappedReferenceMetadata; import org.apache.aries.application.modelling.WrappedServiceMetadata; import org.apache.aries.application.modelling.standalone.OfflineModellingFactory; import org.apache.aries.blueprint.container.NamespaceHandlerRegistry; import org.apache.aries.blueprint.container.ParserServiceImpl; import org.apache.aries.blueprint.namespace.NamespaceHandlerRegistryImpl; import org.apache.aries.blueprint.services.ParserService; import org.apache.aries.mocks.BundleContextMock; import org.apache.aries.unittest.mocks.Skeleton; import org.junit.AfterClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.osgi.framework.BundleContext; @RunWith(Parameterized.class) public class ParserProxyTest { @Parameters public static List<Object[]> parserProxies() { return Arrays.asList(new Object[][] { {getMockParserServiceProxy()}, {OfflineModellingFactory.getOfflineParserProxy()}}); } public static ParserProxy getMockParserServiceProxy() { BundleContext mockCtx = Skeleton.newMock(new BundleContextMock(), BundleContext.class); NamespaceHandlerRegistry nhri = new NamespaceHandlerRegistryImpl (mockCtx); ParserService parserService = new ParserServiceImpl(nhri); mockCtx.registerService(ParserService.class.getName(), parserService, new Hashtable<String, String>()); ParserProxyImpl parserProxyService = new ParserProxyImpl(); parserProxyService.setParserService(parserService); parserProxyService.setBundleContext(mockCtx); parserProxyService.setModellingManager(new ModellingManagerImpl()); return parserProxyService; } @AfterClass public static void teardown() { BundleContextMock.clear(); } private final ModellingManager _modellingManager; private final ParserProxy _parserProxy; private final File resourceDir; public ParserProxyTest(ParserProxy sut) throws IOException { _parserProxy = sut; _modellingManager = new ModellingManagerImpl(); // make sure paths work in Eclipse as well as Maven if (new File(".").getCanonicalFile().getName().equals("target")) { resourceDir = new File("../src/test/resources"); } else { resourceDir = new File("src/test/resources"); } } @Test public void basicTest1() throws Exception { File bpXml = new File (resourceDir, "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bp.xml"); File bp2Xml = new File (resourceDir, "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bp2.xml"); List<URL> urls = new ArrayList<URL>(); urls.add ((bpXml.toURI()).toURL()); urls.add ((bp2Xml.toURI()).toURL()); List<? extends WrappedServiceMetadata> results = _parserProxy.parse(urls); assertTrue ("Four results expected, not " + results.size(), results.size() == 4); Set<WrappedServiceMetadata> resultSet = new HashSet<WrappedServiceMetadata>(results); Set<WrappedServiceMetadata> expectedResults = getTest1ExpectedResults(); assertEquals ("Blueprint parsed xml is not as expected: " + resultSet.toString() + " != " + expectedResults, resultSet, expectedResults); } @Test public void testParseAllServiceElements() throws Exception { File bpXml = new File (resourceDir, "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bp.xml"); File bp2Xml = new File (resourceDir, "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bp2.xml"); List<WrappedServiceMetadata> services = new ArrayList<WrappedServiceMetadata>(); List<WrappedReferenceMetadata> references = new ArrayList<WrappedReferenceMetadata>(); FileInputStream fis = new FileInputStream (bpXml); ParsedServiceElements bpelem = _parserProxy.parseAllServiceElements(fis); services.addAll(bpelem.getServices()); references.addAll(bpelem.getReferences()); fis = new FileInputStream (bp2Xml); bpelem = _parserProxy.parseAllServiceElements(fis); services.addAll(bpelem.getServices()); references.addAll(bpelem.getReferences()); // We expect: // bp.xml: 3 services and 2 references // bp2.xml: 3 services and a reference list // assertTrue ("Six services expected, not " + services.size(), services.size() == 6); assertTrue ("Three references expected, not " + references.size(), references.size() == 3); Set<WrappedServiceMetadata> expectedServices = getTest2ExpectedServices(); // ServiceResultSet will contain some services with autogenerated names starting '.' so we can't // use a straight Set.equals(). We could add the autogenerated names to the expected results but instead // let's test that differsOnlyByName() works int serviceMatchesFound = 0; for (WrappedServiceMetadata result : services) { Iterator<WrappedServiceMetadata> it = expectedServices.iterator(); while (it.hasNext()) { WrappedServiceMetadata next = it.next(); if (result.equals(next) || result.identicalOrDiffersOnlyByName(next)) { serviceMatchesFound++; it.remove(); } } } assertEquals ("Parsed services are wrong: " + expectedServices + " unmatched ", 6, serviceMatchesFound); Set<WrappedReferenceMetadata> expectedReferences = getTest2ExpectedReferences(); Set<WrappedReferenceMetadata> results = new HashSet<WrappedReferenceMetadata>(references); assertTrue ("Parsed references are not as we'd expected: " + results.toString() + " != " + expectedReferences, results.equals(expectedReferences)); } @Test public void checkMultiValues() throws Exception { File bpXml = new File (resourceDir, "appModeller/test1.eba/bundle1.jar/OSGI-INF/blueprint/bpMultiValues.xml"); List<WrappedServiceMetadata> services = new ArrayList<WrappedServiceMetadata>(); FileInputStream fis = new FileInputStream (bpXml); ParsedServiceElements bpelem = _parserProxy.parseAllServiceElements(fis); services.addAll(bpelem.getServices()); assertEquals ("Multi valued service not parsed correctly", services.size(), 1); WrappedServiceMetadata wsm = services.get(0); Map<String, Object> props = wsm.getServiceProperties(); String [] intents = (String[]) props.get("service.intents"); assertEquals ("Service.intents[0] wrong", intents[0], "propagatesTransaction"); assertEquals ("Service.intents[1] wrong", intents[1], "confidentiality"); } // model // <reference id="fromOutside" interface="foo.bar.MyInjectedService"/> // <reference-list id="refList1" interface="my.logging.services" filter="(active=true)"/> // private Set<WrappedReferenceMetadata> getTest2ExpectedReferences() throws Exception { Set<WrappedReferenceMetadata> expectedResults = new HashSet<WrappedReferenceMetadata>(); expectedResults.add(_modellingManager.getImportedService(false, "foo.bar.MyInjectedService", null, null, "fromOutside", false)); expectedResults.add(_modellingManager.getImportedService(true, "foo.bar.MyInjectedService", null, null, "anotherOptionalReference", false)); expectedResults.add(_modellingManager.getImportedService(false, "my.logging.service", null, "(&(trace=on)(debug=true))", "refList1", true)); return expectedResults; } // Test 2 includes anonymous services: the expected results are a superset of test1 private Set<WrappedServiceMetadata> getTest2ExpectedServices() { Set<WrappedServiceMetadata> expectedResults = getTest1ExpectedResults(); expectedResults.add(_modellingManager.getExportedService("", 0, Arrays.asList("foo.bar.AnonService"), null)); expectedResults.add(_modellingManager.getExportedService("", 0, Arrays.asList("foo.bar.NamedInnerBeanService"), null)); return expectedResults; } private Set<WrappedServiceMetadata> getTest1ExpectedResults() { Set<WrappedServiceMetadata> expectedResults = new HashSet<WrappedServiceMetadata>(); Map<String, Object> props = new HashMap<String, Object>(); props.put ("priority", "9"); props.put("volume", "11"); props.put("property.list", Arrays.asList("1", "2", "3", "2", "1")); //Deliberately miss off duplicate entries and reorder, the parser should still match this props.put("property.set", new LinkedHashSet<String>(Arrays.asList("1", "2", "3"))); props.put("property.array", new String[]{"1", "2", "3", "2", "1"}); props.put("osgi.service.blueprint.compname", "myBean"); expectedResults.add(_modellingManager.getExportedService("myService", 0, Arrays.asList("foo.bar.MyService"), props)); props = new HashMap<String, Object>(); props.put ("priority", "7"); props.put ("volume", "11"); props.put ("osgi.service.blueprint.compname", "bean1"); expectedResults.add(_modellingManager.getExportedService("service1.should.be.exported", 0, Arrays.asList("foo.bar.MyService"), props)); props = new HashMap<String, Object>(); props.put ("customer", "pig"); props.put ("osgi.service.blueprint.compname", "bean2"); expectedResults.add(_modellingManager.getExportedService("service2.should.not.be.exported", 0, Arrays.asList("com.acme.Delivery"), props)); props = new HashMap<String, Object>(); props.put ("customer", "pig"); props.put ("target", "rabbit"); props.put ("payload", "excessive"); props.put ("osgi.service.blueprint.compname", "bean3"); expectedResults.add(_modellingManager.getExportedService("bean3", 0, Arrays.asList("com.acme.Delivery"), props)); return expectedResults; } }
8,927
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/utils/ExportedServiceTest.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.utils; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.aries.application.modelling.WrappedServiceMetadata; import org.apache.aries.application.modelling.impl.ExportedServiceImpl; import org.junit.Test; public class ExportedServiceTest { @Test public void checkEquality() { // public ExportedService (String name, int ranking, Collection<String> ifaces, // Map<String, String> serviceProperties ) { Map<String, Object> props = new HashMap<String, Object>(); props.put ("away", "www.away.com"); props.put ("home", "www.home.net"); WrappedServiceMetadata wsm1 = new ExportedServiceImpl (null, 0, Arrays.asList("a.b.c", "d.e.f"), props); WrappedServiceMetadata wsm2 = new ExportedServiceImpl (null, 0, Arrays.asList("d.e.f", "a.b.c"), props); assertTrue ("Basic equality test", wsm1.equals(wsm2)); assertTrue ("Basic equality test", wsm2.equals(wsm1)); assertTrue ("Hashcodes equal", wsm1.hashCode() == wsm2.hashCode()); wsm2 = new ExportedServiceImpl (null, 0, Arrays.asList("d.e.f", "a.b.c", "g.e.f"), props); assertFalse ("Adding an interface makes them different", wsm1.equals(wsm2)); assertFalse ("Adding an interface makes them different", wsm2.equals(wsm1)); assertFalse ("Hashcodes should differ", wsm1.hashCode() == wsm2.hashCode()); props = new HashMap<String, Object>(props); props.put("interim", "w3.interim.org"); wsm1 = new ExportedServiceImpl (null, 0, Arrays.asList("a.b.c","d.e.f", "g.e.f"), props); assertFalse ("Adding a service property makes them different", wsm1.equals(wsm2)); assertFalse ("Adding a service property makes them different", wsm2.equals(wsm1)); assertFalse ("Hashcodes still different", wsm1.hashCode() == wsm2.hashCode()); } }
8,928
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/utils/BundleResourceTest.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.utils; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.jar.Manifest; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ResourceType; import org.apache.aries.application.modelling.impl.ModelledResourceImpl; import org.junit.Test; import org.osgi.framework.Constants; public class BundleResourceTest extends AbstractBundleResourceTest { /** * */ private static final String MANIFEST_MF = "MANIFEST.MF"; /** * */ private static final String TEST_APP_MANIFEST_PATH = "../src/test/resources/bundles/test.bundle1.jar/META-INF"; /** * @return * @throws IOException * @throws FileNotFoundException * @throws ResolverException * @throws InvalidAttributeException */ protected ModelledResource instantiateBundleResource() throws Exception { File file = new File(TEST_APP_MANIFEST_PATH, MANIFEST_MF); Manifest man = new Manifest(new FileInputStream(file)); ModelledResource br = new ModelledResourceImpl(null, man.getMainAttributes(), null, null); return br; } @Test public void testBundleResourceIsBundle() throws Exception { assertEquals(ResourceType.BUNDLE, bundleResource.getType()); } @Test public void testFragmentCapability() { assertEquals("The bundle resource is wrong.", Constants.FRAGMENT_ATTACHMENT_ALWAYS, bundleResource.getExportedBundle().getAttributes().get(Constants.FRAGMENT_ATTACHMENT_DIRECTIVE + ":")); } }
8,929
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/utils/PackageRequirementMergerTest.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.utils; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.modelling.ImportedPackage; import org.apache.aries.application.modelling.impl.ImportedPackageImpl; import org.apache.aries.application.modelling.internal.PackageRequirementMerger; import org.apache.aries.util.VersionRange; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.junit.Assert; import org.junit.Test; import org.osgi.framework.Constants; public final class PackageRequirementMergerTest { private static boolean isEqual(Collection<ImportedPackage> reqs1, Collection<ImportedPackage> reqs2) { boolean result = true; if (reqs1.size() != reqs2.size()) { result = false; } else { for (ImportedPackage r1 : reqs1) { boolean foundMatch = false; for (ImportedPackage r2 : reqs2) { if (!r1.getPackageName().equals(r2.getPackageName())) { continue; } if (r1.isOptional() != r2.isOptional()) { continue; } Map<String, String> attribs1 = new HashMap<String, String>(r1.getAttributes()); Map<String, String> attribs2 = new HashMap<String, String>(r2.getAttributes()); VersionRange v1 = ManifestHeaderProcessor.parseVersionRange(attribs1.remove(Constants.VERSION_ATTRIBUTE)); VersionRange v2 = ManifestHeaderProcessor.parseVersionRange(attribs2.remove(Constants.VERSION_ATTRIBUTE)); if (!v1.equals(v2)) { continue; } if (!attribs1.equals(attribs2)) { continue; } foundMatch = true; break; } if (!foundMatch) { result = false; break; } } } return result; } static ImportedPackage newImportedPackage (String name, String version) throws InvalidAttributeException { Map<String, String> attrs = new HashMap<String, String>(); attrs.put(Constants.VERSION_ATTRIBUTE, version); return new ImportedPackageImpl (name, attrs); } static ImportedPackage newImportedPackage (String name, String version, boolean optional) throws InvalidAttributeException { Map<String, String> attrs = new HashMap<String, String>(); attrs.put(Constants.VERSION_ATTRIBUTE, version); attrs.put(Constants.RESOLUTION_DIRECTIVE + ":", (optional)?Constants.RESOLUTION_OPTIONAL:Constants.RESOLUTION_MANDATORY); return new ImportedPackageImpl (name, attrs); } static ImportedPackage newImportedPackage (String name, String version, String attribute) throws InvalidAttributeException { Map<String, String> attrs = new HashMap<String, String>(); attrs.put(Constants.VERSION_ATTRIBUTE, version); attrs.put(attribute.split("=")[0], attribute.split("=")[1]); return new ImportedPackageImpl (name, attrs); } @Test public void testMergeValid() throws Exception { Collection<ImportedPackage> reqs = new ArrayList<ImportedPackage>(); reqs.add(newImportedPackage("a", "1.0.0")); reqs.add(newImportedPackage("a", "2.0.0")); reqs.add(newImportedPackage("a", "3.0.0")); reqs.add(newImportedPackage("b", "1.0.0")); reqs.add(newImportedPackage("b", "2.0.0")); reqs.add(newImportedPackage("c", "1.0.0")); PackageRequirementMerger merger = new PackageRequirementMerger(reqs); Assert.assertTrue(merger.isMergeSuccessful()); Assert.assertTrue(merger.getInvalidRequirements().isEmpty()); Collection<ImportedPackage> result = merger.getMergedRequirements(); Collection<ImportedPackage> expected = new ArrayList<ImportedPackage>(); expected.add(newImportedPackage("a", "3.0.0")); expected.add(newImportedPackage("b", "2.0.0")); expected.add(newImportedPackage("c", "1.0.0")); Assert.assertTrue(result.toString(), isEqual(result, expected)); } @Test public void testMergeInvalid() throws Exception { Collection<ImportedPackage> reqs = new ArrayList<ImportedPackage>(); reqs.add(newImportedPackage("a", "[1.0.0,2.0.0]")); reqs.add(newImportedPackage("a", "[3.0.0,3.0.0]")); reqs.add(newImportedPackage("b", "1.0.0")); reqs.add(newImportedPackage("b", "2.0.0")); reqs.add(newImportedPackage("c", "[1.0.0,2.0.0)")); reqs.add(newImportedPackage("c", "2.0.0")); PackageRequirementMerger merger = new PackageRequirementMerger(reqs); Assert.assertFalse(merger.isMergeSuccessful()); try { merger.getMergedRequirements(); Assert.fail("getMergedRequirements should throw IllegalStateException."); } catch (IllegalStateException e) { } Set<String> result = merger.getInvalidRequirements(); Set<String> expected = new HashSet<String>(); expected.add("a"); expected.add("c"); Assert.assertEquals(expected, result); } @Test public void testMergeOptionalResolution() throws Exception { Collection<ImportedPackage> reqs = new ArrayList<ImportedPackage>(); reqs.add(newImportedPackage("a", "1.0.0", true)); reqs.add(newImportedPackage("a", "2.0.0", true)); PackageRequirementMerger merger = new PackageRequirementMerger(reqs); Assert.assertTrue(merger.isMergeSuccessful()); Assert.assertTrue(merger.getInvalidRequirements().isEmpty()); Collection<ImportedPackage> result = merger.getMergedRequirements(); Collection<ImportedPackage> expected = new ArrayList<ImportedPackage>(); expected.add(newImportedPackage("a", "2.0.0", true)); Assert.assertTrue(result.toString(), isEqual(result, expected)); } @Test public void testMergeMandatoryResolution() throws Exception { Collection<ImportedPackage> reqs = new ArrayList<ImportedPackage>(); reqs.add(newImportedPackage("a", "1.0.0", true)); reqs.add(newImportedPackage("a", "2.0.0", false)); PackageRequirementMerger merger = new PackageRequirementMerger(reqs); Assert.assertTrue(merger.isMergeSuccessful()); Assert.assertTrue(merger.getInvalidRequirements().isEmpty()); Collection<ImportedPackage> result = merger.getMergedRequirements(); Collection<ImportedPackage> expected = new ArrayList<ImportedPackage>(); expected.add(newImportedPackage("a", "2.0.0")); Assert.assertTrue(result.toString(), isEqual(result, expected)); } @Test public void testMergeValidAdditionalAttributes() throws Exception { Collection<ImportedPackage> reqs = new ArrayList<ImportedPackage>(); reqs.add(newImportedPackage("a", "1.0.0", "foo=bar")); reqs.add(newImportedPackage("a", "2.0.0", "foo=bar")); PackageRequirementMerger merger = new PackageRequirementMerger(reqs); Assert.assertTrue(merger.isMergeSuccessful()); Assert.assertTrue(merger.getInvalidRequirements().isEmpty()); Collection<ImportedPackage> result = merger.getMergedRequirements(); Collection<ImportedPackage> expected = new ArrayList<ImportedPackage>(); expected.add(newImportedPackage("a", "2.0.0", "foo=bar")); Assert.assertTrue(result.toString(), isEqual(result, expected)); } @Test public void testMergeInvalidAdditionalAttributes() throws Exception { Collection<ImportedPackage> reqs = new ArrayList<ImportedPackage>(); reqs.add(newImportedPackage("a", "1.0.0", "foo=bar")); reqs.add(newImportedPackage("a", "2.0.0", "foo=blah")); reqs.add(newImportedPackage("b", "1.0.0")); PackageRequirementMerger merger = new PackageRequirementMerger(reqs); Assert.assertFalse(merger.isMergeSuccessful()); try { merger.getMergedRequirements(); Assert.fail("getMergedRequirements should throw IllegalStateException."); } catch (IllegalStateException e) { } Set<String> result = merger.getInvalidRequirements(); Set<String> expected = new HashSet<String>(); expected.add("a"); Assert.assertEquals(expected, result); } }
8,930
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/utils/ImportedPackageTest.java
package org.apache.aries.application.modelling.utils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.HashMap; import java.util.Map; import org.apache.aries.application.InvalidAttributeException; import org.apache.aries.application.modelling.ImportedPackage; import org.apache.aries.application.modelling.impl.ImportedPackageImpl; import org.junit.Test; import org.osgi.framework.Constants; /* * 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. */ public class ImportedPackageTest { @Test public void testEqualsForIdenticalPackages() throws InvalidAttributeException { String packageName = "package.name"; String version = "1.0.0"; ImportedPackage package1 = instantiatePackage(packageName, version); // I should hope so! assertEquals(package1, package1); } @Test public void testEqualsForEqualTrivialPackages() throws InvalidAttributeException { String packageName = "package.name"; String version = "1.0.0"; ImportedPackage package1 = instantiatePackage(packageName, version); ImportedPackage package2 = instantiatePackage(packageName, version); assertEquals(package1, package2); } @Test public void testEqualsForEqualPackagesWithVersionRange() throws InvalidAttributeException { String packageName = "package.name"; String version = "[1.0.0, 1.6.3)"; ImportedPackage package1 = instantiatePackage(packageName, version); ImportedPackage package2 = instantiatePackage(packageName, version); assertEquals(package1, package2); } @Test public void testEqualsForTrivialPackagesWithDifferentName() throws InvalidAttributeException { String version = "1.0.0"; ImportedPackage package1 = instantiatePackage("package.name", version); ImportedPackage package2 = instantiatePackage("other.package.name", version); assertFalse("Unexpectedly reported as equal" + package1 + "==" + package2, package1.equals(package2)); } @Test public void testEqualsForTrivialPackagesWithDifferentVersion() throws InvalidAttributeException { String packageName = "package.name"; ImportedPackage package1 = instantiatePackage(packageName, "1.0.0"); ImportedPackage package2 = instantiatePackage(packageName, "1.0.1"); assertFalse("Unexpectedly reported as equal" + package1 + "==" + package2, package1.equals(package2)); } @Test public void testEqualsForTrivialPackagesWithDifferentVersionRanges() throws InvalidAttributeException { String packageName = "package.name"; ImportedPackage package1 = instantiatePackage(packageName, "[1.0.0, 4.4.4)"); ImportedPackage package2 = instantiatePackage(packageName, "[1.0.0, 4.4.2)"); assertFalse("Unexpectedly reported as equal" + package1 + "==" + package2, package1.equals(package2)); } @Test public void testEqualsForEqualPackagesWithDifferentAttributes() throws InvalidAttributeException { String packageName = "package.name"; String version = "1.0.0"; ImportedPackage package1 = instantiatePackage(packageName, version, "att=something"); ImportedPackage package2 = instantiatePackage(packageName, version, "att=something.else"); assertFalse("Unexpectedly reported as equal" + package1 + "==" + package2, package1.equals(package2)); } private ImportedPackage instantiatePackage(String packageName, String version, String ... attributes) throws InvalidAttributeException { Map<String, String> generatedAttributes = new HashMap<String, String>(); generatedAttributes.put(Constants.VERSION_ATTRIBUTE, version); for (String att : attributes) { String[] bits = att.split("="); generatedAttributes.put(bits[0], bits[1]); } return new ImportedPackageImpl(packageName, generatedAttributes); } }
8,931
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/utils/ExportedPackageTest.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.utils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.HashMap; import java.util.Map; import org.apache.aries.application.modelling.ExportedPackage; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.impl.ExportedPackageImpl; import org.apache.aries.unittest.mocks.Skeleton; import org.junit.Test; import org.osgi.framework.Constants; public class ExportedPackageTest { @Test public void testEqualsForIdenticalPackages() { String packageName = "package.name"; String version = "1.0.0"; ExportedPackage package1 = instantiatePackage(packageName, version); // I should hope so! assertEquals(package1, package1); } @Test public void testEqualsForEqualTrivialPackages() { String packageName = "package.name"; String version = "1.0.0"; ExportedPackage package1 = instantiatePackage(packageName, version); ExportedPackage package2 = instantiatePackage(packageName, version); assertEquals(package1, package2); } @Test public void testEqualsForTrivialPackagesWithDifferentName() { String version = "1.0.0"; ExportedPackage package1 = instantiatePackage("package.name", version); ExportedPackage package2 = instantiatePackage("other.package.name", version); assertFalse("Unexpectedly reported as equal" + package1 + "==" + package2, package1.equals(package2)); } @Test public void testEqualsForTrivialPackagesWithDifferentVersion() { String packageName = "package.name"; ExportedPackage package1 = instantiatePackage(packageName, "1.0.0"); ExportedPackage package2 = instantiatePackage(packageName, "1.0.1"); assertFalse("Unexpectedly reported as equal" + package1 + "==" + package2, package1.equals(package2)); } @Test public void testEqualsForEqualPackagesWithDifferentAttributes() { String packageName = "package.name"; String version = "1.0.0"; ExportedPackage package1 = instantiatePackage(packageName, version, "att=something"); ExportedPackage package2 = instantiatePackage(packageName, version, "att=something.else"); assertFalse("Unexpectedly reported as equal" + package1 + "==" + package2, package1.equals(package2)); } private ExportedPackage instantiatePackage(String packageName, String version, String ... attributes) { ModelledResource mr = Skeleton.newMock(ModelledResource.class); Map<String, Object> generatedAttributes = new HashMap<String, Object>(); generatedAttributes.put(Constants.VERSION_ATTRIBUTE, version); for (String att : attributes) { String[] bits = att.split("="); generatedAttributes.put(bits[0], bits[1]); } return new ExportedPackageImpl(mr, packageName, generatedAttributes); } }
8,932
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/utils/AbstractBundleResourceTest.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.utils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.modelling.ExportedPackage; import org.apache.aries.application.modelling.ExportedService; import org.apache.aries.application.modelling.ImportedBundle; import org.apache.aries.application.modelling.ImportedPackage; import org.apache.aries.application.modelling.ImportedService; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ModellingConstants; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /* This is an abstract class and should not be instantiated, so we have an ignore * annotation to the class. */ @Ignore public abstract class AbstractBundleResourceTest { protected ModelledResource bundleResource; @Before public void setUp() throws Exception { bundleResource = instantiateBundleResource(); } /** * @return * @throws ResolverException * @throws FileNotFoundException * @throws IOException * @throws Exception */ protected abstract ModelledResource instantiateBundleResource() throws Exception; @Test public void testBundleResource() throws Exception { assertEquals("The bundle symbolic name is wrong.", "test.bundle1", bundleResource.getSymbolicName()); assertEquals("The bundle version is wrong.", "2.0.0.build-121", bundleResource.getVersion().toString()); assertEquals("The bundle presentation name is wrong.", "Test Bundle", bundleResource.getExportedBundle() .getAttributes().get(ModellingConstants.OBR_PRESENTATION_NAME)); int count = 0; for (ImportedPackage ip : bundleResource.getImportedPackages()) { String filter = ip.getAttributeFilter(); Map<String, String> parsedFilterElements = ManifestHeaderProcessor.parseFilter(filter); if (ip.getPackageName().equals("org.osgi.framework")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "org.osgi.framework"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "1.3.0"); } else if (ip.getPackageName().equals("aries.ws.kernel.file")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.kernel.file"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0"); } else if (ip.getPackageName().equals("aries.wsspi.application.aries")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.wsspi.application.aries"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0"); assertEquals ("Company wrong", parsedFilterElements.get("company"), "yang"); assertTrue ("mandatory filter missing", filter.contains("(mandatory:<*company)")); } else if (ip.getPackageName().equals("aries.ws.ffdc")) { count++; assertEquals("The filter is wrong.", "(&(package=aries.ws.ffdc)(version>=0.0.0))", ip.getAttributeFilter()); assertTrue ("Optional import not correctly represented", ip.isOptional()); } else if (ip.getPackageName().equals("aries.ws.app.framework.plugin")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.app.framework.plugin"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "[1.0.0,2.0.0)"); } else if (ip.getPackageName().equals("aries.ejs.ras")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ejs.ras"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0"); } else if (ip.getPackageName().equals("aries.ws.event")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.event"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "1.0.0"); } else if (ip.getPackageName().equals("aries.wsspi.app.container.aries")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.wsspi.app.container.aries"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0"); assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("bundle-symbolic-name"), "B"); assertEquals ("Wrong bundle version", parsedFilterElements.get("bundle-version"), "[1.2.0,2.2.0)"); } else if (ip.getPackageName().equals("aries.ws.eba.bla")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.bla"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "0.0.0"); } else if (ip.getPackageName().equals("aries.ws.eba.launcher")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.launcher"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "[1.0.0,2.0.0]"); assertTrue ("Dynamic-ImportPackage should be optional", ip.isOptional()); } else if (ip.getPackageName().equals("aries.ws.eba.bundle4")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.bundle4"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "3.0.0"); } else if (ip.getPackageName().equals("aries.ws.eba.bundle5")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.bundle5"); assertEquals ("Wrong package version", parsedFilterElements.get("version"), "3.0.0"); } else if (ip.getPackageName().equals("aries.ws.eba.bundle6")) { count++; assertEquals ("Wrong package", parsedFilterElements.get("package"), "aries.ws.eba.bundle6"); assertEquals("The filter is wrong.", "(&(package=aries.ws.eba.bundle6)(version>=0.0.0))", ip.getAttributeFilter()); } else if (ip.getPackageName().equals("aries.ws.eba.bundle7")) { count++; assertEquals("The filter is wrong.", "(&(package=aries.ws.eba.bundle7)(version>=0.0.0))", ip.getAttributeFilter()); } } for (ImportedBundle ib : bundleResource.getRequiredBundles()) { String filter = ib.getAttributeFilter(); Map<String, String> parsedFilterElements = ManifestHeaderProcessor.parseFilter(filter); if (ib.getSymbolicName().equals("com.acme.facade")) { count++; assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "com.acme.facade"); assertEquals ("Wrong bundle version", parsedFilterElements.get("version"), "3.0.0"); } else if (ib.getSymbolicName().equals("com.acme.bar")) { count++; assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "com.acme.bar"); } else if (ib.getSymbolicName().equals("aries.ws.eba.framework")) { count++; assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "aries.ws.eba.framework"); assertEquals ("Wrong bundle version", parsedFilterElements.get("version"), "(3.0.0,4.0.0)"); } else if (ib.getSymbolicName().equals("com.de.ba")) { count++; assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "com.de.ba"); } else if (ib.getSymbolicName().equals("com.ab.de")) { count++; assertEquals ("Wrong bundle symbolic name", parsedFilterElements.get("symbolicname"), "com.ab.de"); } } for(ImportedService svc : bundleResource.getImportedServices()) { if (svc.getInterface().equals("aries.ws.eba.import")) { count++; String filter = svc.getAttributeFilter(); Map<String, String> parsedFilterElements = ManifestHeaderProcessor.parseFilter(filter); assertEquals ("Wrong object class", parsedFilterElements.get("objectClass"), "aries.ws.eba.import"); assertTrue("(service=service) should be present", svc.getAttributeFilter().contains("(service=service)")); assertTrue("(mandatory:<*service) should be present", svc.getAttributeFilter().contains("(mandatory:<*service)")); } } assertEquals("Not all requirements are listed.", bundleResource.getImportedPackages().size() + bundleResource.getImportedServices().size() + bundleResource.getRequiredBundles().size() , count); //verify the capability int verifiedExport = 0; for (ExportedPackage cap : bundleResource.getExportedPackages()) { if (cap.getPackageName().equals("aries.ws.eba.bundle1")) { verifiedExport++; assertEquals("The export package is not expected.", "2.2.0", cap.getVersion()); assertEquals("The export package is not expected.", "test.bundle1", cap.getAttributes().get( "bundle-symbolic-name")); assertEquals("The export package is not expected.", "2.0.0.build-121", cap.getAttributes() .get("bundle-version").toString()); } else if (cap.getPackageName().equals("aries.ws.eba.bundle2")) { verifiedExport++; assertEquals("The export package is not expected.", "3", cap.getVersion()); } else if (cap.getPackageName().equals("aries.ws.eba.bundle3")) { verifiedExport++; assertEquals("The export package is not expected.", "3", cap.getVersion()); } } assertEquals("The number of exports are not expected.", bundleResource.getExportedPackages().size() , verifiedExport); // bundle resource assertEquals("The bundle resource is wrong.", "Test Bundle", bundleResource.getExportedBundle(). getAttributes().get(ModellingConstants.OBR_PRESENTATION_NAME)); assertEquals("The bundle resource is wrong.", "2.0.0.build-121", bundleResource.getExportedBundle(). getVersion()); assertEquals("The bundle resource is wrong.", "test.bundle1", bundleResource.getExportedBundle(). getSymbolicName()); for (ExportedService svc : bundleResource.getExportedServices()) { assertEquals("The export service is wrong", "aries.ws.eba.export", svc.getInterfaces(). iterator().next()); } } }
8,933
0
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling
Create_ds/aries/application/application-modeller-common-test/src/test/java/org/apache/aries/application/modelling/utils/DeployedBundlesTest.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.utils; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; 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.ResolverException; import org.apache.aries.application.modelling.DeployedBundles; import org.apache.aries.application.modelling.ExportedService; import org.apache.aries.application.modelling.ImportedBundle; import org.apache.aries.application.modelling.ImportedService; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.impl.ExportedServiceImpl; import org.apache.aries.application.modelling.impl.ImportedBundleImpl; import org.apache.aries.application.modelling.impl.ImportedServiceImpl; import org.apache.aries.application.modelling.impl.ModelledResourceImpl; import org.apache.aries.application.modelling.utils.impl.ModellingHelperImpl; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.aries.util.manifest.ManifestHeaderProcessor.NameValuePair; import org.junit.Assert; import org.junit.Test; import org.osgi.framework.Constants; public final class DeployedBundlesTest { private DeployedBundles validDeployedBundles() throws Exception { Collection<ImportedBundle> content = new ArrayList<ImportedBundle>(); Collection<ImportedBundle> uses = new ArrayList<ImportedBundle>(); content.add(new ImportedBundleImpl("bundle.a", "1.0.0")); content.add(new ImportedBundleImpl("bundle.b", "1.0.0")); uses.add(new ImportedBundleImpl("bundle.c", "1.0.0")); uses.add(new ImportedBundleImpl("bundle.d", "1.0.0")); return new ModellingHelperImpl().createDeployedBundles("test",content, uses, null); } private void basicResolve(DeployedBundles db, boolean cPersistent) throws InvalidAttributeException { db.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.b", "package.c"), Arrays.asList("package.a;version=1.0.0"))); db.addBundle(createModelledResource("bundle.b", "1.0.0", Arrays.asList("package.d;version=1.0.0", "package.e;version=\"[1.0.0,2.0.0)\"", "package.g"), Arrays.asList("package.b;version=1.0.0"))); db.addBundle(createModelledResource("bundle.c", "1.0.0", (cPersistent) ? Arrays.asList("package.d;version=\"[1.0.0,2.0.0)\"", "javax.persistence;version=1.1.0") : Arrays.asList("package.d;version=\"[1.0.0,2.0.0)\""), Arrays.asList("package.c;version=1.0.0"))); db.addBundle(createModelledResource("bundle.d", "1.0.0", Arrays.asList("package.e;version=\"[1.0.0,1.0.0]\""), Arrays.asList("package.d;version=1.0.0"))); } private void packagesResolve(DeployedBundles db) throws InvalidAttributeException { basicResolve(db, false); db.addBundle(createModelledResource("bundle.e", "1.0.0", new ArrayList<String>(), Arrays.asList("package.e;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 ModelledResourceImpl(null, att, null, null); } public static ModelledResource createModelledServiceBundle(String bundleName, String bundleVersion, Collection<String> importService, Collection<String> exportService) 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"); List<ImportedService> importedServices = new ArrayList<ImportedService>(); for (String s : importService) { importedServices.add(new ImportedServiceImpl(false, s, null, null, null, false)); } List<ExportedService> exportedServices = new ArrayList<ExportedService>(); for (String s : exportService) { exportedServices.add(new ExportedServiceImpl(null, 0, Collections.singleton(s), Collections.<String,Object>emptyMap())); } return new ModelledResourceImpl(null, att, importedServices, exportedServices); } /** * Check the actual results match the expected values, regardless of order of the parts. * @param entry the actual manifest entry. * @param expected the expected manifest entry. * @return true if they match; false otherwise. */ private static boolean isEqual(String actual, String expected) { Map<NameValuePair, Integer> actualEntries = parseEntries(actual); Map<NameValuePair, Integer> expectedEntries = parseEntries(expected); return actualEntries.equals(expectedEntries); } /** * Parse manifest entries into a set of values and associated attributes, which can * be directly compared for equality regardless of ordering. * <p> * Example manifest entry format: value1;attrName1=attrValue1;attrName2=attrValue2,value2;attrName1=attrValue1 * @param entries a manifest header entry. * @return a set of parsed entries. */ private static Map<NameValuePair, Integer> parseEntries(String entries) { Map<NameValuePair, Integer> result = new HashMap<NameValuePair, Integer>(); for (NameValuePair entry : ManifestHeaderProcessor.parseExportString(entries)) { Integer count = result.get(entry); if (count != null) { // This entry already exists to increment the count. count++; } else { count = 1; } result.put(entry, count); } return result; } @Test public void testGetContent_Valid() throws Exception { // Get a valid set of deployment information. DeployedBundles deployedBundles = validDeployedBundles(); packagesResolve(deployedBundles); // Check the deployed content entry is correct. String contentEntry = deployedBundles.getContent(); String expectedResult = "bundle.a;deployed-version=1.0.0,bundle.b;deployed-version=1.0.0"; Assert.assertTrue("Content=" + contentEntry, isEqual(contentEntry, expectedResult)); } @Test public void testGetUseBundle_Valid() throws Exception { // Get a valid set of deployment information. DeployedBundles deployedBundles = validDeployedBundles(); packagesResolve(deployedBundles); // Check the deployed use bundle entry is correct. String useBundleEntry = deployedBundles.getUseBundle(); String expectedResult = "bundle.c;deployed-version=1.0.0,bundle.d;deployed-version=1.0.0"; Assert.assertTrue("UseBundle=" + useBundleEntry, isEqual(useBundleEntry, expectedResult)); } @Test public void testGetProvisionBundle_Valid() throws Exception { // Check the provision bundle entry is correct. DeployedBundles deployedBundles = validDeployedBundles(); packagesResolve(deployedBundles); String provisionBundleEntry = deployedBundles.getProvisionBundle(); String expectedResult = "bundle.e;deployed-version=1.0.0"; Assert.assertTrue("ProvisionBundle=" + provisionBundleEntry, isEqual(provisionBundleEntry, expectedResult)); } @Test public void testGetImportPackage_Valid() throws Exception { // Check the import package entry is correct. String importPackageEntry = null; try { DeployedBundles deployedBundles = validDeployedBundles(); packagesResolve(deployedBundles); importPackageEntry = deployedBundles.getImportPackage(); } catch (ResolverException e) { e.printStackTrace(); Assert.fail(e.toString()); } String expectedResult = "package.c;version=\"1.0.0\";bundle-symbolic-name=\"bundle.c\";bundle-version=\"[1.0.0,1.0.0]\"," + "package.d;version=\"1.0.0\";bundle-symbolic-name=\"bundle.d\";bundle-version=\"[1.0.0,1.0.0]\"," + "package.e;version=\"[1.0.0,2.0.0)\"," + "package.g;version=\"0.0.0\""; /* * String expectedResult = "package.c;bundle-symbolic-name=bundle.c;bundle-version=\"[1.0.0,1.0.0]\"" + ",package.d;version=\"1.0.0\";bundle-symbolic-name=bundle.d;bundle-version=\"[1.0.0,1.0.0]\"" + ",package.e;version=\"[1.0.0,2.0.0)\"" + ",package.g"; */ Assert.assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } private enum ternary { CONTENT,USES,NONE } private DeployedBundles getSimpleDeployedBundles(ternary a, ternary b, ternary c) throws InvalidAttributeException { Collection<ImportedBundle> content = new ArrayList<ImportedBundle>(); Collection<ImportedBundle> uses = new ArrayList<ImportedBundle>(); if(a == ternary.CONTENT) content.add(new ImportedBundleImpl("bundle.a", "1.0.0")); else if (a == ternary.USES) uses.add(new ImportedBundleImpl("bundle.a", "1.0.0")); if (b == ternary.CONTENT) content.add(new ImportedBundleImpl("bundle.b", "1.0.0")); else if (b == ternary.USES) uses.add(new ImportedBundleImpl("bundle.b", "1.0.0")); if (c == ternary.CONTENT) content.add(new ImportedBundleImpl("bundle.c", "1.0.0")); else if (c == ternary.USES) uses.add(new ImportedBundleImpl("bundle.c", "1.0.0")); // In a unit test we could go straight to the static method; choosing not to in this case. return new ModellingHelperImpl().createDeployedBundles("test",content, uses, null); } @Test public void testGetImportPackage_ValidDuplicates() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.CONTENT, ternary.CONTENT); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.d;version=\"[1.0.0,3.0.0)\""), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", Arrays.asList("package.d;version=\"2.0.0\""), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.c", "1.0.0", Arrays.asList("package.d;version=\"1.0.0\""), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.d", "1.0.0", new ArrayList<String>(), Arrays.asList("package.d;version=2.0.1"))); // Check that package D is not duplicated in Import-Package, and that the version range // has been narrowed to the intersection of the original requirements. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); } catch (ResolverException e) { e.printStackTrace(); Assert.fail(e.toString()); } String expectedResult = "package.d;version=\"[2.0.0,3.0.0)\""; Assert.assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } @Test public void testGetImportPackage_ValidDuplicatesWithAttributes() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.CONTENT, ternary.NONE); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.c;version=1.0.0;was_internal=true"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", Arrays.asList("package.c;version=2.0.0;was_internal=true"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.c", "1.0.0", new ArrayList<String>(), Arrays.asList("package.c;version=2.0.0;was_internal=true"))); // Check that package C is not duplicated in Import-Package, and that the version range // has been narrowed to the intersection of the original requirements. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); } catch (ResolverException e) { e.printStackTrace(); Assert.fail(e.toString()); } String expectedResult = "package.c;was_internal=\"true\";version=\"2.0.0\""; Assert.assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } @Test public void testGetImportPackage_InvalidDuplicates() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.CONTENT, ternary.NONE); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.c;version=\"[1.0.0,2.0.0)\""), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", Arrays.asList("package.c;version=2.0.0"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.c", "1.0.0", new ArrayList<String>(), Arrays.asList("package.c;version=2.0.0;was_internal=true"))); // Check that the incompatible version requirements cannot be resolved. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); Assert.fail("Expected exception. ImportPackage=" + importPackageEntry); } catch (ResolverException e) { // We expect to reach this point if the test passes. } } @Test public void testGetImportPackage_InvalidDuplicatesWithAttributes() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.CONTENT, ternary.NONE); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.c;version=1.0.0;was_internal=true"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", Arrays.asList("package.c;version=2.0.0"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.c", "1.0.0", new ArrayList<String>(), Arrays.asList("package.c;version=2.0.0;was_internal=true"))); // Check that the incompatible package requirement attributes cause an exception. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); Assert.fail("Expected exception. ImportPackage=" + importPackageEntry); } catch (ResolverException e) { // We expect to reach this point if the test passes. } } @Test public void testGetImportPackage_bundleSymbolicNameOK() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.CONTENT, ternary.NONE); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.b;version=1.0.0;bundle-symbolic-name=bundle.b;bundle-version=\"[1.0.0,2.0.0)\""), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", new ArrayList<String>(), Arrays.asList("package.b;version=2.0.0"))); // Check that the bundle-symbolic-name attribute for a bundle within deployed-content is ok. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); } catch (ResolverException e) { e.printStackTrace(); Assert.fail(e.toString()); } String expectedResult = ""; // All packages are satisfied internally Assert.assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } @Test public void testGetImportPackage_rfc138PreventsBundleSymbolicNameWorking() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.USES, ternary.NONE); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.b;version=1.0.0;bundle-symbolic-name=bundle.b"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", new ArrayList<String>(), Arrays.asList("package.b;version=2.0.0"))); // Check that the bundle-symbolic-name attribute for a bundle outside use-bundle causes an exception. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); Assert.fail("Expected exception. ImportPackage=" + importPackageEntry); } catch (ResolverException e) { // We expect to reach this point if the test passes. } } @Test public void testGetImportPackage_rfc138PreventsBundleVersionWorking() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.NONE, ternary.NONE); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.b;version=1.0.0;bundle-version=1.0.0"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", new ArrayList<String>(), Arrays.asList("package.b;version=2.0.0"))); // Check that the bundle-symbolic-name attribute for a bundle outside use-bundle causes an exception. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); Assert.fail("Expected exception. ImportPackage=" + importPackageEntry); } catch (ResolverException e) { // We expect to reach this point if the test passes. } } @Test public void testGetImportPackage_ValidResolutionAttribute() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.CONTENT, ternary.NONE); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.c;version=1.0.0;resolution:=optional"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", Arrays.asList("package.c;version=1.0.0"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.c", "1.0.0", new ArrayList<String>(), Arrays.asList("package.c;version=1.0.0"))); // Check that the resulting resolution directive is not optional. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); } catch (ResolverException e) { e.printStackTrace(); Assert.fail(e.toString()); } String expectedResult = "package.c;version=1.0.0"; Assert.assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } @Test public void testGetRequiredUseBundle_RedundantEntry() throws Exception { // Bundle A requires package B from bundle B with no version requirement. // Bundle B requires package C from bundle C with no version requirement. // Bundle C requires package B from bundle B with explicit version requirement. DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.USES, ternary.USES); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.b"), new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", Arrays.asList("package.c"), Arrays.asList("package.b;version=1.0.0"))); deployedBundles.addBundle(createModelledResource("bundle.c", "1.0.0", Arrays.asList("package.b;version=1.0.0"), Arrays.asList("package.c;version=1.0.0"))); // Check the redundant use-bundle entry is identified. // Bundle C is not required by app content, although it is specified in use-bundle. Collection<ModelledResource> requiredUseBundle = null; try { requiredUseBundle = deployedBundles.getRequiredUseBundle(); } catch (ResolverException e) { e.printStackTrace(); Assert.fail(e.toString()); } Assert.assertTrue("RequiredUseBundle=" + requiredUseBundle, requiredUseBundle.size() == 1); } @Test public void testGetRequiredUseBundle_Valid() throws Exception { // Get a valid set of deployment information. DeployedBundles deployedBundles = validDeployedBundles(); packagesResolve(deployedBundles); // Check all the use-bundle entries are required. Collection<ModelledResource> requiredUseBundle = null; try { requiredUseBundle = deployedBundles.getRequiredUseBundle(); } catch (ResolverException e) { e.printStackTrace(); Assert.fail(e.toString()); } Assert.assertTrue("RequiredUseBundle=" + requiredUseBundle, requiredUseBundle.size() == 2); } //Inside cannot bundle-symbolic-name an outside bundle until the new RFC 138! @Test public void testGetImportPackage_InvalidBundleVersion() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.USES, ternary.NONE); deployedBundles.addBundle(createModelledResource("bundle.a", "1.0.0", Arrays.asList("package.b;version=\"[1.0.0,1.0.0]\";bundle-symbolic-name=bundle.b;bundle-version=\"[0.0.0,1.0.0)\"") , new ArrayList<String>())); deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", new ArrayList<String>(), Arrays.asList("package.b;version=1.0.0"))); // Check that the bundle version requirement generates an error because it doesn't match the a bundle in use-bundle. String importPackageEntry = null; try { importPackageEntry = deployedBundles.getImportPackage(); Assert.fail("Expected exception. ImportPackage=" + importPackageEntry); } catch (ResolverException e) { // We expect to reach this point if the test passes. } } @Test public void testImportedService() throws Exception { DeployedBundles deployedBundles = getSimpleDeployedBundles(ternary.CONTENT, ternary.NONE, ternary.NONE); deployedBundles.addBundle(createModelledServiceBundle("bundle.a", "1.0.0", Collections.singleton("java.util.List"), Collections.<String>emptyList())); deployedBundles.addBundle(createModelledServiceBundle("bundle.b", "1.0.0", Collections.singleton("java.util.Set"), Collections.singleton("java.util.List"))); deployedBundles.addBundle(createModelledServiceBundle("bundle.c", "1.0.0", Collections.<String>emptyList(), Collections.singleton("java.util.Set"))); assertEquals("(objectClass=java.util.List)", deployedBundles.getDeployedImportService()); } }
8,934
0
Create_ds/aries/application/application-runtime-repository/src/main/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-runtime-repository/src/main/java/org/apache/aries/application/runtime/repository/BundleRepositoryManagerImpl.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.repository; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import static org.apache.aries.application.utils.AppConstants.LOG_EXCEPTION; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.management.spi.repository.BundleRepository; import org.apache.aries.application.management.spi.repository.BundleRepositoryManager; import org.apache.aries.application.management.spi.repository.ContextException; import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion; import org.apache.aries.application.utils.service.ArrayServiceList; import org.apache.aries.application.utils.service.ServiceCollection; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BundleRepositoryManagerImpl implements BundleRepositoryManager { private static final Logger LOGGER = LoggerFactory.getLogger(BundleRepositoryManagerImpl.class); private BundleContext bc; public void setBundleContext(BundleContext bc) { LOGGER.debug(LOG_ENTRY, "setBundleContext"); this.bc = bc; LOGGER.debug(LOG_EXIT, "setBundleContext"); } public Collection<BundleRepository> getAllBundleRepositories() { LOGGER.debug(LOG_ENTRY, "getAllBundleRepositories"); ServiceCollection<BundleRepository> providers = new ArrayServiceList<BundleRepository>(bc); try { ServiceReference[] refs = bc.getServiceReferences( BundleRepository.class.getName(), null); if (refs != null) { for (ServiceReference ref : refs) { providers.addService(ref); } } } catch (InvalidSyntaxException e) { LOGGER.error(LOG_EXCEPTION, e); } LOGGER.debug(LOG_EXIT, "getAllBundleRepositories"); return providers; } public Collection<BundleRepository> getBundleRepositoryCollection(String appName, String appVersion) { LOGGER.debug(LOG_ENTRY, "getBundleRepositoryCollection", new Object[] {appName, appVersion}); ServiceCollection<BundleRepository> providers = new ArrayServiceList<BundleRepository>(bc); String appScope = appName + "_" + appVersion; String filter = "(|(" + BundleRepository.REPOSITORY_SCOPE + "=" + BundleRepository.GLOBAL_SCOPE + ")(" + BundleRepository.REPOSITORY_SCOPE + "=" + appScope + "))"; try { ServiceReference[] refs = bc.getServiceReferences( BundleRepository.class.getName(), filter); if (refs != null) { for (ServiceReference ref : refs) { providers.addService(ref); } } } catch (InvalidSyntaxException e) { LOGGER.error(LOG_EXCEPTION, e); } LOGGER.debug(LOG_EXIT, "getBundleRepositoryCollection"); return providers; } public Map<DeploymentContent, BundleSuggestion> getBundleSuggestions(Collection<BundleRepository> providers, Collection<DeploymentContent> content) throws ContextException { LOGGER.debug(LOG_ENTRY, "getBundleSuggestions", new Object[] {content, providers}); Map<DeploymentContent, BundleSuggestion> urlToBeInstalled = new HashMap<DeploymentContent, BundleSuggestion>(); Iterator<DeploymentContent> it = content.iterator(); while (it.hasNext()) { DeploymentContent bundleToFind = it.next(); Map<Version, List<BundleSuggestion>> bundlesuggestions = new HashMap<Version, List<BundleSuggestion>>(); for (BundleRepository obj : providers) { BundleSuggestion suggestion = obj.suggestBundleToUse(bundleToFind); if (suggestion != null) { List<BundleSuggestion> suggestions = bundlesuggestions.get(suggestion.getVersion()); if (suggestions == null) { suggestions = new ArrayList<BundleSuggestion>(); bundlesuggestions.put(suggestion.getVersion(), suggestions); } suggestions.add(suggestion); } } BundleSuggestion suggestion = null; if (!!!bundlesuggestions.isEmpty()) { List<BundleSuggestion> thoughts = bundlesuggestions.get(bundleToFind.getExactVersion()); if (thoughts != null) { Collections.sort(thoughts, new Comparator<BundleSuggestion>() { public int compare(BundleSuggestion o1, BundleSuggestion o2) { return o1.getCost() - o2.getCost(); } }); suggestion = thoughts.get(0); } } // add the suggestion to the list if (suggestion != null) { urlToBeInstalled.put(bundleToFind, suggestion); } else { throw new ContextException("Unable to find bundle "+bundleToFind.getContentName() + "/" + bundleToFind.getExactVersion()); } } LOGGER.debug(LOG_EXIT, "getBundleSuggestions", new Object[] { urlToBeInstalled }); return urlToBeInstalled; } public Map<DeploymentContent, BundleSuggestion> getBundleSuggestions(String applicationName, String applicationVersion, Collection<DeploymentContent> content) throws ContextException { return getBundleSuggestions(getBundleRepositoryCollection(applicationName, applicationVersion), content); } public Map<DeploymentContent, BundleSuggestion> getBundleSuggestions( Collection<DeploymentContent> content) throws ContextException { return getBundleSuggestions(getAllBundleRepositories(), content); } }
8,935
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/sample
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/sample/impl/HelloWorldImpl.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.sample.impl; import org.apache.aries.sample.HelloWorld; public class HelloWorldImpl implements HelloWorld { public String getMessage() { return "hello world"; } }
8,936
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/helloworld
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/helloworld/client/HelloWorldClientImpl.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.helloworld.client; import java.util.List; import org.apache.aries.sample.HelloWorld; import org.apache.aries.sample.HelloWorldManager; public class HelloWorldClientImpl implements HelloWorldManager { List<HelloWorld> helloWorldServices; public List<HelloWorld> getHelloWorldServices() { return helloWorldServices; } public void setHelloWorldServices(List<HelloWorld> helloWorldServices) { this.helloWorldServices = helloWorldServices; } public int getNumOfHelloServices() { return helloWorldServices.size(); } }
8,937
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/IsolatedRuntimeTest.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.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.File; import java.io.FileOutputStream; import java.util.concurrent.atomic.AtomicBoolean; 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.application.management.ResolveConstraint; import org.apache.aries.application.management.spi.repository.RepositoryGenerator; import org.apache.aries.application.modelling.ModellingManager; import org.apache.aries.application.runtime.itests.util.IsolationTestUtils; import org.apache.aries.isolated.sample.HelloWorld; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.util.VersionRange; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.junit.Before; import org.junit.Ignore; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import org.osgi.framework.BundleEvent; import org.osgi.framework.SynchronousBundleListener; import org.osgi.service.framework.CompositeBundle; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class IsolatedRuntimeTest extends AbstractIntegrationTest { /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ static boolean createdApplications = false; @Before public void createApplications() throws Exception { if (createdApplications) { return; } ZipFixture testEba = ArchiveFixture.newZip() .jar("sample.jar") .manifest().symbolicName("org.apache.aries.isolated.sample") .attribute("Bundle-Version", "1.0.0") .attribute("Import-Package", "org.osgi.service.blueprint, org.apache.aries.isolated.shared") // needed for testFrameworkResolvedBeforeInnerBundlesStart() .attribute("Bundle-ActivationPolicy", "lazy") .end() .binary("org/apache/aries/isolated/sample/HelloWorld.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorld.class")) .binary("org/apache/aries/isolated/sample/HelloWorldImpl.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorldImpl.class")) .binary("org/apache/aries/isolated/sample/SharedImpl.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/SharedImpl.class")) .binary("OSGI-INF/blueprint/sample-blueprint.xml", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("isolated/sample-blueprint.xml")) .end() .jar("shared.jar") .manifest().symbolicName("org.apache.aries.isolated.shared") .attribute("Bundle-Version", "1.0.0") .attribute("Export-Package", "org.apache.aries.isolated.shared") .end() .binary("org/apache/aries/isolated/shared/Shared.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/shared/Shared.class")) .end(); FileOutputStream fout = new FileOutputStream("test.eba"); testEba.writeOut(fout); fout.close(); ZipFixture testEba2 = testEba.binary("META-INF/APPLICATION.MF", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("isolated/APPLICATION.MF")) .end(); fout = new FileOutputStream("test2.eba"); testEba2.writeOut(fout); fout.close(); ZipFixture sampleJar2 = ArchiveFixture.newJar() .manifest().symbolicName("org.apache.aries.isolated.sample") .attribute("Bundle-Version", "2.0.0") .end() .binary("org/apache/aries/isolated/sample/HelloWorld.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorld.class")) .binary("org/apache/aries/isolated/sample/HelloWorldImpl.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorldImpl.class")) .binary("OSGI-INF/blueprint/aries.xml", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("isolated/sample2-blueprint.xml")) .end(); fout = new FileOutputStream("sample_2.0.0.jar"); sampleJar2.writeOut(fout); fout.close(); ZipFixture ebaWithFragment = ArchiveFixture.newZip() .jar("sample.jar") .manifest().symbolicName("org.apache.aries.isolated.sample") .attribute("Bundle-Version", "1.0.0") .end() .end() .jar("fragment.jar") .manifest().symbolicName("org.apache.aries.isolated.fragment") .attribute("Bundle-Version", "1.0.0") .attribute("Fragment-Host", "org.apache.aries.isolated.sample") .end() .binary("org/apache/aries/isolated/sample/HelloWorld.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorld.class")) .binary("org/apache/aries/isolated/sample/HelloWorldImpl.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorldImpl.class")) .binary("OSGI-INF/blueprint/sample-blueprint.xml", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("isolated/sample-blueprint.xml")) .end(); fout = new FileOutputStream("withFragment.eba"); ebaWithFragment.writeOut(fout); fout.close(); createdApplications = true; } @Test @Ignore public void testAppWithoutApplicationManifest() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test.eba"))); AriesApplicationContext ctx = manager.install(app); ctx.start(); assertHelloWorldService("test.eba"); manager.uninstall(ctx); } @Test @Ignore public void testAppWithApplicationManifest() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test2.eba"))); AriesApplicationContext ctx = manager.install(app); ctx.start(); assertHelloWorldService("org.apache.aries.sample2"); manager.uninstall(ctx); } @Test @Ignore public void testUninstallReinstall() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test2.eba"))); AriesApplicationContext ctx = manager.install(app); app = ctx.getApplication(); ctx.start(); assertHelloWorldService("org.apache.aries.sample2"); ctx.stop(); manager.uninstall(ctx); assertNull(IsolationTestUtils.findIsolatedAppBundleContext(bundleContext, "org.apache.aries.sample2")); ctx = manager.install(app); ctx.start(); assertHelloWorldService("org.apache.aries.sample2"); manager.uninstall(ctx); } @Test @Ignore public void testAppWithFragment() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("withFragment.eba"))); AriesApplicationContext ctx = manager.install(app); ctx.start(); assertHelloWorldService("withFragment.eba"); manager.uninstall(ctx); } @Test @Ignore public void testAppWithGlobalRepositoryBundle() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test2.eba"))); IsolationTestUtils.prepareSampleBundleV2(bundleContext, context().getService(RepositoryGenerator.class), context().getService(RepositoryAdmin.class), context().getService(ModellingManager.class)); AriesApplication newApp = manager.resolve(app, new ResolveConstraint() { @Override public String getBundleName() { return "org.apache.aries.isolated.sample"; } @Override public VersionRange getVersionRange() { return ManifestHeaderProcessor.parseVersionRange("[2.0.0,2.0.0]", true); } }); AriesApplicationContext ctx = manager.install(newApp); ctx.start(); assertHelloWorldService("org.apache.aries.sample2", "hello brave new world"); manager.uninstall(ctx); } @Test @Ignore public void testFrameworkResolvedBeforeInnerBundlesStart() throws Exception { /* * Lazy bundles have in the past triggered recursive bundle trackers to handle them before * the composite bundle framework was even resolved. In such a case the below loadClass * operation on a class that depends on a class imported from the outside of the composite * will fail with an NPE. */ final AtomicBoolean loadedClass = new AtomicBoolean(false); context().addBundleListener(new SynchronousBundleListener() { public void bundleChanged(BundleEvent event) { Bundle b = event.getBundle(); if (event.getType() == BundleEvent.STARTING || event.getType() == BundleEvent.LAZY_ACTIVATION) { if (b.getEntry("org/apache/aries/isolated/sample/SharedImpl.class") != null) { try { Class<?> cl = b.loadClass("org.apache.aries.isolated.sample.SharedImpl"); cl.newInstance(); loadedClass.set(true); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } else if (event.getType() == BundleEvent.INSTALLED && b instanceof CompositeBundle) { ((CompositeBundle) b).getCompositeFramework().getBundleContext().addBundleListener(this); } } }); AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test2.eba"))); AriesApplicationContext ctx = manager.install(app); try { ctx.start(); app = ctx.getApplication(); assertEquals(1, app.getDeploymentMetadata().getApplicationDeploymentContents().size()); assertEquals(1, app.getDeploymentMetadata().getApplicationProvisionBundles().size()); assertTrue(loadedClass.get()); } finally { manager.uninstall(ctx); } } private void assertHelloWorldService(String appName) throws Exception { assertHelloWorldService(appName, "hello world"); } private void assertHelloWorldService(String appName, String message) throws Exception { HelloWorld hw = IsolationTestUtils.findHelloWorldService(bundleContext, appName); assertNotNull("The Hello World service could not be found.", hw); assertEquals(message, hw.getMessage()); } @Configuration public static Option[] configuration() { return options( // framework / core bundles mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Repository repository("http://repository.ops4j.org/maven2"), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // Bundles junitBundles(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), // Bundles 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.transaction", "org.apache.aries.transaction.blueprint").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.isolated").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.framework").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.framework.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.repository").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec").versionAsInProject()); } }
8,938
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/OBRResolverAdvancedTest.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.itests; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.aries.application.Content; 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.AriesApplicationManager; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.repository.RepositoryGenerator; 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.utils.AppConstants; import org.apache.aries.application.utils.manifest.ContentFactory; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.sample.HelloWorld; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.filesystem.IDirectory; import org.apache.felix.bundlerepository.Repository; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.junit.After; import org.junit.Before; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class OBRResolverAdvancedTest extends AbstractIntegrationTest { public static final String CORE_BUNDLE_BY_VALUE = "core.bundle.by.value"; public static final String CORE_BUNDLE_BY_REFERENCE = "core.bundle.by.reference"; public static final String TRANSITIVE_BUNDLE_BY_VALUE = "transitive.bundle.by.value"; public static final String TRANSITIVE_BUNDLE_BY_REFERENCE = "transitive.bundle.by.reference"; public static final String USE_BUNDLE_BY_REFERENCE = "use.bundle.by.reference"; public static final String REPO_BUNDLE = "aries.bundle1"; public static final String HELLO_WORLD_CLIENT_BUNDLE = "hello.world.client.bundle"; public static final String HELLO_WORLD_SERVICE_BUNDLE1 = "hello.world.service.bundle1"; public static final String HELLO_WORLD_SERVICE_BUNDLE2 = "hello.world.service.bundle2"; /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ @Before public void createApplications() throws Exception { ZipFixture bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, CORE_BUNDLE_BY_VALUE) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute(Constants.IMPORT_PACKAGE, "a.b.c, p.q.r, x.y.z, javax.naming") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end(); FileOutputStream fout = new FileOutputStream(CORE_BUNDLE_BY_VALUE + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, TRANSITIVE_BUNDLE_BY_VALUE) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute(Constants.EXPORT_PACKAGE, "p.q.r") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end(); fout = new FileOutputStream(TRANSITIVE_BUNDLE_BY_VALUE + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, TRANSITIVE_BUNDLE_BY_REFERENCE) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute(Constants.EXPORT_PACKAGE, "x.y.z") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end(); fout = new FileOutputStream(TRANSITIVE_BUNDLE_BY_REFERENCE + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, CORE_BUNDLE_BY_REFERENCE) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute(Constants.EXPORT_PACKAGE, "d.e.f") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end(); fout = new FileOutputStream(CORE_BUNDLE_BY_REFERENCE + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, CORE_BUNDLE_BY_REFERENCE) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute(Constants.EXPORT_PACKAGE, "d.e.f").end(); fout = new FileOutputStream(CORE_BUNDLE_BY_REFERENCE + "_0.0.0.jar"); bundle.writeOut(fout); fout.close(); // jar up a use bundle bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, USE_BUNDLE_BY_REFERENCE) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute(Constants.EXPORT_PACKAGE, "a.b.c") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end(); fout = new FileOutputStream(USE_BUNDLE_BY_REFERENCE + ".jar"); bundle.writeOut(fout); fout.close(); // Create the EBA application ZipFixture testEba = ArchiveFixture.newZip() .binary("META-INF/APPLICATION.MF", OBRResolverAdvancedTest.class.getClassLoader().getResourceAsStream("obr/APPLICATION-UseBundle.MF")) .end() .binary(CORE_BUNDLE_BY_VALUE + ".jar", new FileInputStream(CORE_BUNDLE_BY_VALUE + ".jar")).end() .binary(TRANSITIVE_BUNDLE_BY_VALUE + ".jar", new FileInputStream(TRANSITIVE_BUNDLE_BY_VALUE + ".jar")).end(); fout = new FileOutputStream("demo.eba"); testEba.writeOut(fout); fout.close(); //create the bundle bundle = ArchiveFixture.newJar() .binary("META-INF/MANIFEST.MF", OBRResolverAdvancedTest.class.getClassLoader().getResourceAsStream("obr/aries.bundle1/META-INF/MANIFEST.MF")).end() .binary("OSGI-INF/blueprint/blueprint.xml", OBRResolverAdvancedTest.class.getClassLoader().getResourceAsStream("obr/hello-world-client.xml")).end() .binary("OSGI-INF/blueprint/anotherBlueprint.xml", OBRResolverAdvancedTest.class.getClassLoader().getResourceAsStream("obr/aries.bundle1/OSGI-INF/blueprint/sample-blueprint.xml")).end(); fout = new FileOutputStream(REPO_BUNDLE + ".jar"); bundle.writeOut(fout); fout.close(); /////////////////////////////////////////////// //create an eba with a helloworld client, which get all 'HelloWorld' services //create a helloworld client bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, HELLO_WORLD_CLIENT_BUNDLE) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute("Import-Package", "org.apache.aries.sample") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end() .binary("org/apache/aries/application/helloworld/client/HelloWorldClientImpl.class", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("org/apache/aries/application/helloworld/client/HelloWorldClientImpl.class")) .binary("OSGI-INF/blueprint/helloClient.xml", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("obr/hello-world-client.xml")) .end(); fout = new FileOutputStream(HELLO_WORLD_CLIENT_BUNDLE + ".jar"); bundle.writeOut(fout); fout.close(); //create two helloworld services // create the 1st helloworld service bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, HELLO_WORLD_SERVICE_BUNDLE1) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute("Import-Package", "org.apache.aries.sample") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end() .binary("org/apache/aries/sample/impl/HelloWorldImpl.class", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("org/apache/aries/sample/impl/HelloWorldImpl.class")) .binary("OSGI-INF/blueprint/sample-blueprint.xml", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("basic/sample-blueprint.xml")) .end(); //create the 2nd helloworld service fout = new FileOutputStream(HELLO_WORLD_SERVICE_BUNDLE1 + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, HELLO_WORLD_SERVICE_BUNDLE2) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute("Import-Package", "org.apache.aries.sample") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end() .binary("org/apache/aries/sample/impl/HelloWorldImpl.class", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("org/apache/aries/sample/impl/HelloWorldImpl.class")) .binary("OSGI-INF/blueprint/sample-blueprint.xml", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("basic/sample-blueprint.xml")) .end(); fout = new FileOutputStream(HELLO_WORLD_SERVICE_BUNDLE2 + ".jar"); bundle.writeOut(fout); fout.close(); //Create a helloworld eba with the client included ZipFixture multiServiceHelloEba = ArchiveFixture.newZip() .binary(HELLO_WORLD_CLIENT_BUNDLE + ".jar", new FileInputStream(HELLO_WORLD_CLIENT_BUNDLE + ".jar")).end(); fout = new FileOutputStream("hello.eba"); multiServiceHelloEba.writeOut(fout); fout.close(); } @Test(expected = ResolverException.class) public void testDemoAppResolveFail() throws ResolverException, Exception { // do not provision against the local runtime System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "true"); generateOBRRepoXML(false, TRANSITIVE_BUNDLE_BY_REFERENCE + ".jar", CORE_BUNDLE_BY_REFERENCE + "_0.0.0.jar", USE_BUNDLE_BY_REFERENCE + ".jar"); RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL()); AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("demo.eba"))); app = manager.resolve(app); } @Test(expected = ModellerException.class) public void testModellerException() throws Exception { ZipFixture bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, CORE_BUNDLE_BY_VALUE) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute(Constants.IMPORT_PACKAGE, "a.b.c, p.q.r, x.y.z, javax.naming") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end(); FileOutputStream fout = new FileOutputStream("delete.jar"); bundle.writeOut(fout); fout.close(); generateOBRRepoXML(false, "delete.jar"); } @Test public void testDemoApp() throws Exception { // do not provision against the local runtime System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "true"); generateOBRRepoXML(false, TRANSITIVE_BUNDLE_BY_REFERENCE + ".jar", CORE_BUNDLE_BY_REFERENCE + ".jar", USE_BUNDLE_BY_REFERENCE + ".jar"); RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL()); AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("demo.eba"))); //installing requires a valid url for the bundle in repository.xml. app = manager.resolve(app); DeploymentMetadata depMeta = app.getDeploymentMetadata(); List<DeploymentContent> provision = depMeta.getApplicationProvisionBundles(); Collection<DeploymentContent> useBundles = depMeta.getDeployedUseBundle(); Collection<Content> importPackages = depMeta.getImportPackage(); assertEquals(provision.toString(), 2, provision.size()); assertEquals(useBundles.toString(), 1, useBundles.size()); assertEquals(importPackages.toString(), 4, importPackages.size()); List<String> bundleSymbolicNames = new ArrayList<String>(); for (DeploymentContent dep : provision) { bundleSymbolicNames.add(dep.getContentName()); } assertTrue("Bundle " + TRANSITIVE_BUNDLE_BY_REFERENCE + " not found.", bundleSymbolicNames.contains(TRANSITIVE_BUNDLE_BY_REFERENCE)); assertTrue("Bundle " + TRANSITIVE_BUNDLE_BY_VALUE + " not found.", bundleSymbolicNames.contains(TRANSITIVE_BUNDLE_BY_VALUE)); bundleSymbolicNames.clear(); for (DeploymentContent dep : useBundles) { bundleSymbolicNames.add(dep.getContentName()); } assertTrue("Bundle " + USE_BUNDLE_BY_REFERENCE + " not found.", bundleSymbolicNames.contains(USE_BUNDLE_BY_REFERENCE)); Collection<String> packages = new ArrayList<String>(); Map<String, String> maps = new HashMap<String, String>(); maps.put("version", "0.0.0"); maps.put("bundle-symbolic-name", "use.bundle.by.reference"); maps.put("bundle-version", "[1.0.0,1.0.0]"); Content useContent = ContentFactory.parseContent("a.b.c", maps); assertTrue("Use Bundle not found in import packags", importPackages.contains(useContent)); for (Content c : importPackages) { packages.add(c.getContentName()); } assertTrue("package javax.naming not found", packages.contains("javax.naming")); assertTrue("package p.q.r not found", packages.contains("p.q.r")); assertTrue("package x.y.z not found", packages.contains("x.y.z")); assertTrue("package a.b.c not found", packages.contains("a.b.c")); AriesApplicationContext ctx = manager.install(app); ctx.start(); Set<Bundle> bundles = ctx.getApplicationContent(); assertEquals("Number of bundles provisioned in the app", 5, bundles.size()); ctx.stop(); manager.uninstall(ctx); } /** * This test just verifies whether every entry in the MANIFEST.MF was fed into the repository generator. * Since the IBM JRE generates a slightly different repository file from the Sun JRE as far as the order of xml elements is concerned. It is not feasible * to perform a file comparison. * * @throws Exception */ @Test public void testRepo() throws Exception { // do not provision against the local runtime System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "true"); generateOBRRepoXML(true, REPO_BUNDLE + ".jar"); //print out the repository.xml BufferedReader reader = new BufferedReader(new FileReader(new File("repository.xml"))); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // compare the generated with the expected file Document real_doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("repository.xml")); Document expected_doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(OBRResolverAdvancedTest.class.getClassLoader().getResourceAsStream("/obr/aries.bundle1/expectedRepository.xml")); // parse two documents to make sure they have the same number of elements Element element_real = real_doc.getDocumentElement(); Element element_expected = expected_doc.getDocumentElement(); NodeList nodes_real = element_real.getElementsByTagName("capability"); NodeList nodes_expected = element_expected.getElementsByTagName("capability"); assertEquals("The number of capability is not expected. ", nodes_expected.getLength(), nodes_real.getLength()); nodes_real = element_real.getElementsByTagName("require"); nodes_expected = element_expected.getElementsByTagName("require"); assertEquals("The number of require elements is not expected. ", nodes_expected.getLength(), nodes_real.getLength()); nodes_real = element_real.getElementsByTagName("p"); nodes_expected = element_expected.getElementsByTagName("p"); assertEquals("The number of properties is not expected. ", nodes_expected.getLength(), nodes_real.getLength()); // Let's verify all p elements are shown as expected. for (int index = 0; index < nodes_expected.getLength(); index++) { Node node = nodes_expected.item(index); boolean contains = false; // make sure the node exists in the real generated repository for (int i = 0; i < nodes_real.getLength(); i++) { Node real_node = nodes_real.item(i); if (node.isEqualNode(real_node)) { contains = true; break; } } assertTrue("The node " + node.toString() + "should exist.", contains); } } @Test public void testRepoAgain() throws Exception { // do not provision against the local runtime System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "true"); RepositoryGenerator repositoryGenerator = context().getService(RepositoryGenerator.class); String fileURI = new File(REPO_BUNDLE + ".jar").toURI().toString(); File repoXml = new File("repository.xml"); if (repoXml.exists()) { repoXml.delete(); } repositoryGenerator.generateRepository(new String[]{fileURI}, new FileOutputStream(repoXml)); //print out the repository.xml BufferedReader reader = new BufferedReader(new FileReader(new File("repository.xml"))); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // compare the generated with the expected file Document real_doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("repository.xml")); Document expected_doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(OBRResolverAdvancedTest.class.getClassLoader().getResourceAsStream("/obr/aries.bundle1/expectedRepository.xml")); // parse two documents to make sure they have the same number of elements Element element_real = real_doc.getDocumentElement(); Element element_expected = expected_doc.getDocumentElement(); NodeList nodes_real = element_real.getElementsByTagName("capability"); NodeList nodes_expected = element_expected.getElementsByTagName("capability"); assertEquals("The number of capability is not expected. ", nodes_expected.getLength(), nodes_real.getLength()); nodes_real = element_real.getElementsByTagName("require"); nodes_expected = element_expected.getElementsByTagName("require"); assertEquals("The number of require elements is not expected. ", nodes_expected.getLength(), nodes_real.getLength()); nodes_real = element_real.getElementsByTagName("p"); nodes_expected = element_expected.getElementsByTagName("p"); assertEquals("The number of properties is not expected. ", nodes_expected.getLength(), nodes_real.getLength()); // Let's verify all p elements are shown as expected. for (int index = 0; index < nodes_expected.getLength(); index++) { Node node = nodes_expected.item(index); boolean contains = false; // make sure the node exists in the real generated repository for (int i = 0; i < nodes_real.getLength(); i++) { Node real_node = nodes_real.item(i); if (node.isEqualNode(real_node)) { contains = true; break; } } assertTrue("The node " + node.toString() + "should exist.", contains); } } @Test public void testMutlipleServices() throws Exception { // provision against the local runtime System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "false"); generateOBRRepoXML(false, HELLO_WORLD_SERVICE_BUNDLE1 + ".jar", HELLO_WORLD_SERVICE_BUNDLE2 + ".jar"); RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL()); AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("hello.eba"))); AriesApplicationContext ctx = manager.install(app); ctx.start(); // Wait 5 seconds just to give the blueprint-managed beans a chance to come up try { Thread.sleep(5000); } catch (InterruptedException ix) { } HelloWorld hw = context().getService(HelloWorld.class); String result = hw.getMessage(); assertEquals(result, "hello world"); // Uncomment the block below after https://issues.apache.org/jira/browse/FELIX-2546, // "Only one service is provisioned even when specifying for mulitple services" // is fixed. This tracks the problem of provisioning only one service even when we // specify multiple services. /** HelloWorldManager hwm = context().getService(HelloWorldManager.class); * int numberOfServices = hwm.getNumOfHelloServices(); * assertEquals(2, numberOfServices); */ ctx.stop(); manager.uninstall(ctx); } private void generateOBRRepoXML(boolean nullURI, String... bundleFiles) throws Exception { Set<ModelledResource> mrs = new HashSet<ModelledResource>(); FileOutputStream fout = new FileOutputStream("repository.xml"); RepositoryGenerator repositoryGenerator = context().getService(RepositoryGenerator.class); ModelledResourceManager modelledResourceManager = context().getService(ModelledResourceManager.class); for (String fileName : bundleFiles) { File bundleFile = new File(fileName); IDirectory jarDir = FileSystem.getFSRoot(bundleFile); String uri = ""; if (!!!nullURI) { uri = bundleFile.toURI().toString(); } if ("delete.jar".equals(fileName)) { jarDir = null; } mrs.add(modelledResourceManager.getModelledResource(uri, jarDir)); } repositoryGenerator.generateRepository("Test repo description", mrs, fout); fout.close(); } @After public void clearRepository() { RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); if ((repos != null) && (repos.length > 0)) { for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } } } @Configuration public static Option[] configuration() { return options( // framework / core bundles mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // Bundles junitBundles(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), // Bundles mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").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()); } }
8,939
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/MinimumImportsTest.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.itests; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.OutputStream; 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.itest.AbstractIntegrationTest; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.util.filesystem.FileSystem; import org.apache.felix.bundlerepository.Repository; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.junit.Before; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.blueprint.container.BlueprintEvent; import org.osgi.service.blueprint.container.BlueprintListener; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class MinimumImportsTest extends AbstractIntegrationTest { /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ static boolean createdApplications = false; static String fake_app_management = "application.management.fake"; @Before public void createApplications() throws Exception { if (createdApplications) { return; } // need to fake a application manager to export the service in order to pass the resolving for the client // In the real situation, we don't allow customers' bundles to explicitly import the runtime services. ZipFixture bundle = ArchiveFixture.newJar().manifest() .attribute(Constants.BUNDLE_SYMBOLICNAME, fake_app_management) .attribute(Constants.BUNDLE_MANIFESTVERSION, "2") .attribute(Constants.BUNDLE_VERSION, "1.0.0").end(); OutputStream out = new FileOutputStream(fake_app_management + ".jar"); bundle.writeOut(out); out.close(); ZipFixture testEba = ArchiveFixture.newZip() .jar("org.apache.aries.application.itests.minimports.jar") .manifest().symbolicName("org.apache.aries.application.itests.minimports") .attribute("Bundle-Version", "1.0.0") .attribute("Import-Package", "org.apache.aries.application.management") .end() .binary("org/apache/aries/application/sample/appmgrclient/AppMgrClient.class", MinimumImportsTest.class.getClassLoader().getResourceAsStream("org/apache/aries/application/sample/appmgrclient/AppMgrClient.class")) .binary("OSGI-INF/blueprint/app-mgr-client.xml", MinimumImportsTest.class.getClassLoader().getResourceAsStream("app-mgr-client.xml")) .end(); FileOutputStream fout = new FileOutputStream("appmgrclienttest.eba"); testEba.writeOut(fout); fout.close(); StringBuilder repositoryXML = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(MinimumImportsTest.class.getResourceAsStream("/basic/fakeAppMgrServiceRepo.xml"))); String line; while ((line = reader.readLine()) != null) { repositoryXML.append(line); repositoryXML.append("\r\n"); } String repo = repositoryXML.toString().replaceAll("bundle_location", new File(fake_app_management + ".jar").toURI().toString()); System.out.println(repo); FileWriter writer = new FileWriter("repository.xml"); writer.write(repo); writer.close(); createdApplications = true; } public static class AppMgrClientBlueprintListener implements BlueprintListener { Boolean success = null; public void blueprintEvent(BlueprintEvent event) { if (event.getBundle().getSymbolicName().equals( "org.apache.aries.application.itests.minimports")) { if (event.getType() == event.FAILURE) { success = Boolean.FALSE; } if (event.getType() == event.CREATED) { success = Boolean.TRUE; } } } } @Test public void testAppUsingAriesApplicationManager() throws Exception { // Register a BlueprintListener to listen for the events from the BlueprintContainer for the bundle in the appmgrclienttest.eba AppMgrClientBlueprintListener acbl = new AppMgrClientBlueprintListener(); ServiceRegistration sr = bundleContext.registerService("org.osgi.service.blueprint.container.BlueprintListener", acbl, null); AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("appmgrclienttest.eba"))); RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL()); AriesApplicationContext ctx = manager.install(app); ctx.start(); int sleepfor = 3000; while ((acbl.success == null || acbl.success == false) && sleepfor > 0) { Thread.sleep(100); sleepfor -= 100; } assertNotNull("Timed out - didn't receive Blueprint CREATED or FAILURE event", acbl.success); assertTrue("Received Blueprint FAILURE event", acbl.success); ctx.stop(); manager.uninstall(ctx); sr.unregister(); } @Configuration public static Option[] configuration() { return options( // framework / core bundles mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // Bundles junitBundles(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), // Bundles mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").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()); } }
8,940
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/OBRAppManagerTest.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.itests; import static org.junit.Assert.assertEquals; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStreamReader; 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.itest.AbstractIntegrationTest; import org.apache.aries.sample.HelloWorld; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.util.filesystem.FileSystem; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Repository; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.apache.felix.bundlerepository.Resource; import org.junit.Before; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class OBRAppManagerTest extends AbstractIntegrationTest { /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ static boolean createdApplications = false; @Before public void createApplications() throws Exception { if (createdApplications) { return; } ZipFixture testBundle = ArchiveFixture.newZip() .manifest().symbolicName("org.apache.aries.sample.bundle") .attribute("Bundle-Version", "1.0.0") .attribute("Import-Package", "org.apache.aries.sample") .attribute("Export-Package", "org.apache.aries.sample.impl") .end() .binary("org/apache/aries/sample/impl/HelloWorldImpl.class", OBRAppManagerTest.class.getClassLoader().getResourceAsStream("org/apache/aries/sample/impl/HelloWorldImpl.class")) .end(); FileOutputStream fout = new FileOutputStream("bundle.jar"); testBundle.writeOut(fout); fout.close(); ZipFixture testEba = ArchiveFixture.newZip() .jar("sample.jar") .manifest().symbolicName("org.apache.aries.sample") .attribute("Bundle-Version", "1.0.0") .attribute("Import-Package", "org.apache.aries.sample.impl,org.apache.aries.sample") .end() .binary("OSGI-INF/blueprint/sample-blueprint.xml", OBRAppManagerTest.class.getClassLoader().getResourceAsStream("basic/sample-blueprint.xml")) .end() .binary("META-INF/APPLICATION.MF", OBRAppManagerTest.class.getClassLoader().getResourceAsStream("basic/APPLICATION.MF")) .end(); fout = new FileOutputStream("test.eba"); testEba.writeOut(fout); fout.close(); StringBuilder repositoryXML = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(OBRAppManagerTest.class.getResourceAsStream("/obr/repository.xml"))); String line; while ((line = reader.readLine()) != null) { repositoryXML.append(line); repositoryXML.append("\r\n"); } String repo = repositoryXML.toString().replaceAll("bundle_location", new File("bundle.jar").toURI().toString()); System.out.println(repo); FileWriter writer = new FileWriter("repository.xml"); writer.write(repo); writer.close(); createdApplications = true; } @Test public void testAppWithApplicationManifest() throws Exception { RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL()); Repository[] repos = repositoryAdmin.listRepositories(); for (Repository repo : repos) { Resource[] resources = repo.getResources(); for (Resource r : resources) { Capability[] cs = r.getCapabilities(); for (Capability c : cs) { System.out.println(c.getName() + " : " + c.getProperties()); } } } AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test.eba"))); app = manager.resolve(app); //installing requires a valid url for the bundle in repository.xml. AriesApplicationContext ctx = manager.install(app); ctx.start(); HelloWorld hw = context().getService(HelloWorld.class); String result = hw.getMessage(); assertEquals(result, "hello world"); ctx.stop(); manager.uninstall(ctx); } @Configuration public static Option[] configuration() { return options( // framework / core bundles mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // Bundles junitBundles(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), // Bundles 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.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces").versionAsInProject()); } }
8,941
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/BasicNoOpResolverTest.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.itests; import static org.ops4j.pax.exam.CoreOptions.*; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileOutputStream; 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.itest.AbstractIntegrationTest; import org.apache.aries.sample.HelloWorld; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.util.filesystem.FileSystem; import org.junit.Before; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class BasicNoOpResolverTest extends AbstractIntegrationTest { /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ static boolean createdApplications = false; @Before public void createApplications() throws Exception { if (createdApplications) { return; } ZipFixture testEba = ArchiveFixture.newZip() .jar("sample.jar") .manifest().symbolicName("org.apache.aries.sample") .attribute("Bundle-Version", "1.0.0") .attribute("Import-Package", "org.apache.aries.sample") .end() .binary("org/apache/aries/sample/impl/HelloWorldImpl.class", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("org/apache/aries/sample/impl/HelloWorldImpl.class")) .binary("OSGI-INF/blueprint/sample-blueprint.xml", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("basic/sample-blueprint.xml")) .end(); FileOutputStream fout = new FileOutputStream("test.eba"); testEba.writeOut(fout); fout.close(); ZipFixture testEba2 = testEba.binary("META-INF/APPLICATION.MF", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("basic/APPLICATION.MF")) .end(); fout = new FileOutputStream("test2.eba"); testEba2.writeOut(fout); fout.close(); createdApplications = true; } @Test public void testAppWithoutApplicationManifest() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test.eba"))); // application name should be equal to eba name since application.mf is not provided assertEquals("test.eba", app.getApplicationMetadata().getApplicationName()); AriesApplicationContext ctx = manager.install(app); ctx.start(); HelloWorld hw = context().getService(HelloWorld.class); String result = hw.getMessage(); assertEquals(result, "hello world"); ctx.stop(); manager.uninstall(ctx); } @Test public void testAppWithApplicationManifest() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test2.eba"))); // application name should equal to whatever Application name provided in the application.mf assertEquals("test application 2", app.getApplicationMetadata().getApplicationName()); AriesApplicationContext ctx = manager.install(app); ctx.start(); HelloWorld hw = context().getService(HelloWorld.class); String result = hw.getMessage(); assertEquals(result, "hello world"); ctx.stop(); manager.uninstall(ctx); } @Configuration public static Option[] configuration() { return options( // framework / core bundles mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // Bundles junitBundles(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.noop").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").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()); } }
8,942
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/IsolatedCfgAdminRuntimeTest.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.itests; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.*; import java.net.URL; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.Assert; 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.application.runtime.itests.util.IsolationTestUtils; import org.apache.aries.isolated.sample.HelloWorld; import org.apache.aries.isolated.sample.HelloWorldImpl; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.itest.RichBundleContext; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.unittest.mocks.Skeleton; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.filesystem.IDirectory; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ManagedService; import org.osgi.service.url.URLStreamHandlerService; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; /** * This test suite is responsible for validating that an application can package and use the * isolated configuration admin deployed. This includes both from Blueprint and manually. * <p/> * Blueprint Specific: * <p/> * Note that, the CmNamespaceHandler has been rewired to create a service reference to the configuration * admin that resides within the application framework. This will allow the configuration admin bundle * activator sufficient time to register a config admin service before the blueprint container for the bundle * requiring it is started (i.e. no configuration admin race condition). * <p/> * Other notes: * <p/> * In order to avoid boundary issues (i.e. class casting exceptions etc), the actual configuration admin bundle * classes are loaded from the shared framework. This is necessary as the blueprint-cm bundle refers to the * configuration admin classes directly, as we register a configuration admin and managed service in the * application scope, any attempt to use those services from the CM bundle would end up in a class cast exception. * This is why we use the classes already loaded in the root container, which are imported into the shared framework. * Behind the scenes a manifest transformer is used to make sure that the DEPLOYMENT.MF is augmented with the * necessary org.osgi.service.cm package import to make the class space consistent everywhere. From the developers * perspective, it appears as if they are deploying into a flat container as the wiring magic is hidden when the * application is created and installed. Note that the config package import only includes the CM API, nothing else. * * @version $Rev$ $Date$ */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class IsolatedCfgAdminRuntimeTest extends AbstractIntegrationTest { private static final String APP_HWBP = "helloworld-bp.eba"; private static final String APP_HWMN = "helloworld-mn.eba"; private static final List<String> APPLICATIONS = Arrays.asList(APP_HWBP, APP_HWMN); /** * Creates two applications, as follows: * <p/> * - helloworld-bp.eba ------ * | * | This application contains a helloworld bundle which contains an interface and impl for HelloWorld. Upon being started * | blueprint will create a new container for this bundle and register the HelloWorld service. The service will be injected * | with a message coming from the ConfigurationAdmin service using the PID: helloworld-bp. As a CM property placeholder is * | used, a ManagedService will also be registered on the bundles behalf so that further updates can be captured. Note that * | the blueprint configuration is wired to reload the container on a configuration update (to allow easier tracking of when * | to test service contents etc). * | * | The application also contains a configuration admin bundle (pulled from Maven). * --------------------------- * <p/> * - helloworld-mn.eba ------- * | * | This application contains a helloworld bundle containing an activator that will register itself as a ManagedService for the * | PID: helloworld-mn. The activator will also expose out a HelloWorld service. Upon recieving an update from the packaged * | Configuration Admin service, the HelloWorld service will be re-registered using the latest configuration, namely the "message". * | * | The application also contains a configuration admin bundle (pulled from Maven). * --------------------------- * * @throws Exception */ @Before public void constructApplications() throws Exception { Assert.assertNotNull("Could not find Maven URL handler", (new RichBundleContext(context())).getService(URLStreamHandlerService.class, "url.handler.protocol=mvn", 300000)); MavenArtifactProvisionOption configAdminProvisionOption = mavenBundleInTest(getClass().getClassLoader(), "org.apache.felix", "org.apache.felix.configadmin"); Assert.assertNotNull("Unable to lookup config admin maven bundle", configAdminProvisionOption); URL configAdminUrl = new URL(configAdminProvisionOption.getURL()); ZipFixture helloWorldBluePrintEba = ArchiveFixture .newZip() .binary("META-INF/APPLICATION.MF", IsolatedCfgAdminRuntimeTest.class.getClassLoader() .getResourceAsStream("isolated/config/APPLICATION-BP.MF") ) .binary("org.apache.felix.configadmin.jar", configAdminUrl.openStream()) .jar("helloworld-bundle.jar") .manifest() .symbolicName("org.apache.aries.isolated.helloworldbp") .attribute("Bundle-Version", "1.0.0") .attribute("Import-Package", "org.osgi.service.cm") .end() .binary("org/apache/aries/isolated/sample/HelloWorld.class", IsolatedCfgAdminRuntimeTest.class.getClassLoader().getResourceAsStream( "org/apache/aries/isolated/sample/HelloWorld.class") ) .binary("org/apache/aries/isolated/sample/HelloWorldImpl.class", IsolatedCfgAdminRuntimeTest.class.getClassLoader().getResourceAsStream( "org/apache/aries/isolated/sample/HelloWorldImpl.class") ) .binary("OSGI-INF/blueprint/blueprint.xml", IsolatedCfgAdminRuntimeTest.class.getClassLoader() .getResourceAsStream("isolated/config/blueprint.xml") ).end(); ZipFixture helloWorldManualEba = ArchiveFixture .newZip() .binary("META-INF/APPLICATION.MF", IsolatedCfgAdminRuntimeTest.class.getClassLoader() .getResourceAsStream("isolated/config/APPLICATION-MN.MF") ) .binary("org.apache.felix.configadmin.jar", configAdminUrl.openStream()) .jar("helloworld-bundle.jar") .manifest() .symbolicName("org.apache.aries.isolated.helloworldmn") .attribute("Bundle-Version", "1.0.0") .attribute("Bundle-Activator", "org.apache.aries.isolated.config.HelloWorldManagedServiceImpl") .attribute("Import-Package", "org.osgi.framework,org.osgi.service.cm") .end() .binary("org/apache/aries/isolated/sample/HelloWorld.class", IsolatedCfgAdminRuntimeTest.class.getClassLoader().getResourceAsStream( "org/apache/aries/isolated/sample/HelloWorld.class") ) .binary("org/apache/aries/isolated/sample/HelloWorldImpl.class", IsolatedCfgAdminRuntimeTest.class.getClassLoader().getResourceAsStream( "org/apache/aries/isolated/sample/HelloWorldImpl.class") ) .binary("org/apache/aries/isolated/config/HelloWorldManagedServiceImpl.class", IsolatedCfgAdminRuntimeTest.class.getClassLoader().getResourceAsStream( "org/apache/aries/isolated/config/HelloWorldManagedServiceImpl.class") ).end(); FileOutputStream fout = new FileOutputStream(APP_HWBP); helloWorldBluePrintEba.writeOut(fout); fout.close(); fout = new FileOutputStream(APP_HWMN); helloWorldManualEba.writeOut(fout); fout.close(); } /** * Try and clean up the applications created by {@link #constructApplications()} */ @After public void deleteApplications() { for (String application : APPLICATIONS) { File eba = new File(application); if (eba.exists()) { eba.delete(); } } } /** * The purpose of this test is to make sure an application that contains an config admin bundle * can be used by Blueprint. The following steps are performed: * <p/> * - install the application * - start the application * - assert we have the following services in the isolated service registry (ConfigurationAdmin, ManagedService, HelloWorld) * - assert no configuration existed when the CM-PPH was invoked by BP (default message will be the token i.e. ${message}) * - update the configuration (the message) for the PID (using a primitive boundary proxy), this will cause the blueprint container to reload * - check that the re-registered HelloWorld service contains the updated message * - clean up * * @throws Exception */ @Test @Ignore public void testIsolatedCfgAdminBPReload() throws Exception { validateApplicationConfiguration( APP_HWBP, "org.apache.aries.helloworldbpapp", "helloworld-bp", "${message}", "blueprint"); } /** * The purpose of this test is to make sure an application that contains an config admin bundle * can be used by manually. The following steps are performed: * <p/> * - install the application * - start the application * - assert we have the following services in the isolated service registry (ConfigurationAdmin, ManagedService, HelloWorld) * - assert no configuration existed when the CM-PPH was invoked by BP (default message will be the token i.e. ${message}) * - update the configuration (the message) for the PID (using a primitive boundary proxy), this will cause the HW service to be re-registered ({@link org.apache.aries.isolated.config.HelloWorldManagedServiceImpl} * - check that the re-registered HelloWorld service contains the updated message * - clean up * * @throws Exception */ @Test @Ignore public void testIsolatedCfgAdminManualReload() throws Exception { validateApplicationConfiguration( APP_HWMN, "org.apache.aries.helloworldmnapp", "helloworld-mn", (new HelloWorldImpl()).getMessage(), "manual"); } /** * Central validation method for verifying configuration can be published and consumed correctly within * an isolated scope. * * @param application the application file name * @param applicationName the application name * @param pid the service.pid * @param defaultMessage the default message for the HelloWorld service (checked before any configuration updates occur) * @param newMessage the new message to set during a configuration update * @throws Exception */ private void validateApplicationConfiguration(String application, String applicationName, String pid, String defaultMessage, String newMessage) throws Exception { //install and start the application Context ctx = installApplication(FileSystem.getFSRoot(new File(application)), applicationName); //assert we have the services that we're expecting assertExpectedServices(ctx.getBundleContext(), pid); //make sure we have the defaults set Assert.assertEquals("Invalid message set on the HW service", defaultMessage, IsolationTestUtils.findHelloWorldService(ctx.getBundleContext()).getMessage()); //cause a configuration update to occur which should reload our HW service Dictionary<String, String> dictionary = new Hashtable<String, String>(); dictionary.put("message", newMessage); Assert.assertTrue("Configuration update failed", executeConfigurationUpdate(ctx.getBundleContext(), pid, dictionary)); //now make sure we have our new message set in the HW service Assert.assertEquals("Invalid message set on the HW service", newMessage, IsolationTestUtils.findHelloWorldService(ctx.getBundleContext()).getMessage()); //clean up uninstallApplication(ctx); } /** * Executes a configuration update using the given dictionary. A HelloWorld service will be tracked * to ensure the configuration was successful (listening for add/remove tracker events). * * @param ctx the application bundle context * @param pid the service-pid to track * @param dictionary the dictionary containing updated properties * @return if the configuration update was successful * @throws Exception */ private boolean executeConfigurationUpdate(BundleContext ctx, String pid, Dictionary<String, String> dictionary) throws Exception { boolean result = true; MonitorTask monitor = new MonitorTask(ctx, "(" + Constants.OBJECTCLASS + "=" + HelloWorld.class.getName() + ")", 2, 1); try { monitor.beginTracking(); result &= (new ConfigurationTask(ctx, pid, dictionary)).execute(); result &= monitor.execute(); } finally { monitor.endTracking(); } return result; } /** * Assert that the following services are present in the service registry: * <p/> * - ConfigurationAdmin * - ManagedService * - HelloWorld * * @param ctx the bundle context * @param pid the service pid used to register the underlying ManagedService * @throws Exception */ private void assertExpectedServices(RichBundleContext ctx, String pid) throws Exception { //assert the CfgAdmin service was registered Assert.assertNotNull("Missing the ConfigurationAdmin service", ctx.getService(ConfigurationAdmin.class)); //assert we have the ManagedService exposed Assert.assertNotNull("Missing the Managed service", ctx.getService(ManagedService.class, "(" + Constants.SERVICE_PID + "=" + pid + ")")); //now just make sure we can see it through the context of our config admin bundle context (should be in the same scope) ServiceReference ref = ctx.getServiceReference(ConfigurationAdmin.class.getName()); Assert.assertNotNull("Couldn't find the ManagedService using the ConfigAdmin bundle context", new RichBundleContext(ref.getBundle().getBundleContext()).getService(ManagedService.class, "(" + Constants.SERVICE_PID + "=" + pid + ")")); //make sure we have the helloworld service registered HelloWorld helloWorldBluePrint = IsolationTestUtils.findHelloWorldService(ctx); Assert.assertNotNull("Missing the HelloWorld service", helloWorldBluePrint); } private Context installApplication(IDirectory application, String applicationName) throws Exception { //install the application and start it AriesApplicationManager appManager = context().getService(AriesApplicationManager.class); AriesApplication app = appManager.createApplication(application); AriesApplicationContext appCtx = appManager.install(app); appCtx.start(); return new Context(appCtx, IsolationTestUtils.findIsolatedAppBundleContext(context(), applicationName)); } private void uninstallApplication(Context ctx) throws Exception { AriesApplicationManager appManager = context().getService(AriesApplicationManager.class); appManager.uninstall(ctx.getApplicationContext()); } /** * Create the configuration for the PAX container * * @return the various required options * @throws Exception */ @org.ops4j.pax.exam.Configuration public static Option[] configuration() throws Exception { return options( // framework / core bundles mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Repository repository("http://repository.ops4j.org/maven2"), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // Bundles junitBundles(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), // Bundles 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.transaction", "org.apache.aries.transaction.blueprint").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolve.transform.cm").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.isolated").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.framework").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.framework.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.repository").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.configadmin").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec").versionAsInProject(), mavenBundle("org.ops4j.pax.url", "pax-url-aether").versionAsInProject()); } /** * High level interface for executing a unit of work * * @version $Rev$ $Date$ */ private static interface Task { /** * Executes the task logic * * @return if the task was successful * @throws Exception */ public boolean execute() throws Exception; } /** * Base class for a task implementation * * @version $Rev$ $Date$ */ private static abstract class BaseTask implements Task { private BundleContext ctx; public BaseTask(BundleContext ctx) { this.ctx = ctx; } protected BundleContext getBundleContext() { return ctx; } } /** * Trackable task that allows a service tracker to pickup service registration/un-registration events using the * supplied filter. Remember that if a service exists matching a filter while opening the underlying tracker * it will cause a addedService event to be fired, this must be taken into account when instantiating this type * task. For example if you had a ManagedService present in the container matching the given filter, you should * set the expected registerCount as 2 if you expect a re-register to occur due to a container reload etc. * * @version $Rev$ $Date$ */ public static abstract class TrackableTask extends BaseTask implements Task, ServiceTrackerCustomizer { private static final long DEFAULT_TIMEOUT = 5000; private String filter; private ServiceTracker tracker; private CountDownLatch addedLatch; private CountDownLatch removedLatch; public TrackableTask(BundleContext ctx, String filter) { this(ctx, filter, 1, 1); } public TrackableTask(BundleContext ctx, String filter, int registerCount) { this(ctx, filter, registerCount, 0); } public TrackableTask(BundleContext ctx, String filter, int registerCount, int unregisterCount) { super(ctx); this.filter = filter; this.addedLatch = new CountDownLatch(registerCount); this.removedLatch = new CountDownLatch(unregisterCount); this.tracker = null; } /** * Initiates the underlying service tracker * * @throws InvalidSyntaxException */ protected synchronized void beginTracking() throws InvalidSyntaxException { if (tracker == null) { tracker = new ServiceTracker(getBundleContext(), getBundleContext().createFilter(filter), this); tracker.open(); } } /** * Stops and clears the underlying service tracker */ protected synchronized void endTracking() { if (tracker != null) { tracker.close(); tracker = null; } } /* * (non-Javadoc) * @see org.apache.aries.application.runtime.itests.IsolatedCfgAdminRuntimeTest.Task#execute() */ public boolean execute() throws Exception { boolean result = true; try { beginTracking(); doExecute(); result &= addedLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); result &= removedLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); } finally { endTracking(); } return result; } /* * (non-Javadoc) * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference) */ public synchronized Object addingService(ServiceReference serviceRef) { addedLatch.countDown(); return serviceRef; } /* * (non-Javadoc) * @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference, java.lang.Object) */ public void modifiedService(ServiceReference serviceRef, Object service) { } /* * (non-Javadoc) * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ public synchronized void removedService(ServiceReference serviceRef, Object service) { removedLatch.countDown(); } /** * Performs the task logic * * @throws Exception */ protected abstract void doExecute() throws Exception; } /** * The configuration task is responsible for executing a configuration update within the scope * of the given context. Note, this task assumes the class space is inconsistent will not try * casting to classes that may exist in the test world and also in the application. * * @version $Rev$ $Date$ */ private static class ConfigurationTask extends BaseTask { private String pid; private Dictionary<String, String> dictionary; public ConfigurationTask(BundleContext ctx, String pid, Dictionary<String, String> dictionary) { super(ctx); this.pid = pid; this.dictionary = dictionary; } /* * (non-Javadoc) * @see org.apache.aries.application.runtime.itests.IsolatedCfgAdminRuntimeTest.Task#execute() */ public boolean execute() throws Exception { boolean result = false; ServiceTracker tracker = new ServiceTracker(getBundleContext(), getBundleContext().createFilter("(" + Constants.OBJECTCLASS + "=" + ConfigurationAdmin.class.getName() + ")"), null); try { tracker.open(); Object cfgAdminService = tracker.waitForService(5000); if (cfgAdminService != null) { ConfigurationAdmin proxy = Skeleton.newMock(cfgAdminService, ConfigurationAdmin.class); Configuration configuration = proxy.getConfiguration(pid); configuration.setBundleLocation(null); configuration.update(dictionary); result = true; } } finally { tracker.close(); } return result; } } /** * Simple monitor class to keep track of services using the supplied filter, acts as a wrapper * so that it can be placed in side a composite task. * * @version $Rev$ $Date$ */ private static final class MonitorTask extends TrackableTask { public MonitorTask(BundleContext ctx, String filter, int registerCount, int unregisterCount) { super(ctx, filter, registerCount, unregisterCount); } /* * (non-Javadoc) * @see org.apache.aries.application.runtime.itests.IsolatedCfgAdminRuntimeTest.TrackableTask#doExecute() */ @Override protected void doExecute() throws Exception { //do nothing, we just care about tracking } } /** * Simple wrapper for the various contexts required in this test suite * * @version $Rev$ $Date$ */ private static class Context { private AriesApplicationContext applicationContext; private RichBundleContext bundleContext; public Context(AriesApplicationContext applicationContext, BundleContext bundleContext) { this.applicationContext = applicationContext; this.bundleContext = new RichBundleContext(bundleContext); } public AriesApplicationContext getApplicationContext() { return applicationContext; } public RichBundleContext getBundleContext() { return bundleContext; } } public static MavenArtifactProvisionOption mavenBundleInTest(ClassLoader loader, String groupId, String artifactId) { return mavenBundle().groupId(groupId).artifactId(artifactId) .version(getArtifactVersion(loader, groupId, artifactId)); } //TODO getArtifactVersion and getFileFromClasspath are borrowed and modified from pax-exam. They should be moved back ASAP. private static String getArtifactVersion(ClassLoader loader, final String groupId, final String artifactId) { final Properties dependencies = new Properties(); try { InputStream in = getFileFromClasspath(loader, "META-INF/maven/dependencies.properties"); try { dependencies.load(in); } finally { in.close(); } final String version = dependencies.getProperty(groupId + "/" + artifactId + "/version"); if (version == null) { throw new RuntimeException( "Could not resolve version. Do you have a dependency for " + groupId + "/" + artifactId + " in your maven project?" ); } return version; } catch (IOException e) { // TODO throw a better exception throw new RuntimeException( "Could not resolve version. Did you configured the plugin in your maven project?" + "Or maybe you did not run the maven build and you are using an IDE?" ); } } private static InputStream getFileFromClasspath(ClassLoader loader, final String filePath) throws FileNotFoundException { try { URL fileURL = loader.getResource(filePath); if (fileURL == null) { throw new FileNotFoundException("File [" + filePath + "] could not be found in classpath"); } return fileURL.openStream(); } catch (IOException e) { throw new FileNotFoundException("File [" + filePath + "] could not be found: " + e.getMessage()); } } }
8,943
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/BasicAppManagerTest.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.itests; import static org.junit.Assert.assertEquals; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.File; import java.io.FileOutputStream; 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.itest.AbstractIntegrationTest; import org.apache.aries.sample.HelloWorld; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.util.filesystem.FileSystem; import org.junit.Before; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class BasicAppManagerTest extends AbstractIntegrationTest { /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ static boolean createdApplications = false; @Before public void createApplications() throws Exception { if (createdApplications) { return; } ZipFixture testEba = ArchiveFixture.newZip() .jar("sample.jar") .manifest().symbolicName("org.apache.aries.sample") .attribute("Bundle-Version", "1.0.0") .attribute("Import-Package", "org.apache.aries.sample") .end() .binary("org/apache/aries/sample/impl/HelloWorldImpl.class", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("org/apache/aries/sample/impl/HelloWorldImpl.class")) .binary("OSGI-INF/blueprint/sample-blueprint.xml", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("basic/sample-blueprint.xml")) .end(); FileOutputStream fout = new FileOutputStream("test.eba"); testEba.writeOut(fout); fout.close(); ZipFixture testEba2 = testEba.binary("META-INF/APPLICATION.MF", BasicAppManagerTest.class.getClassLoader().getResourceAsStream("basic/APPLICATION.MF")) .end(); fout = new FileOutputStream("test2.eba"); testEba2.writeOut(fout); fout.close(); createdApplications = true; } @Test public void testAppWithoutApplicationManifest() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test.eba"))); // application name should be equal to eba name since application.mf is not provided assertEquals("test.eba", app.getApplicationMetadata().getApplicationName()); AriesApplicationContext ctx = manager.install(app); ctx.start(); HelloWorld hw = context().getService(HelloWorld.class); String result = hw.getMessage(); assertEquals(result, "hello world"); ctx.stop(); manager.uninstall(ctx); } @Test public void testAppWithApplicationManifest() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test2.eba"))); // application name should equal to whatever Application name provided in the application.mf assertEquals("test application 2", app.getApplicationMetadata().getApplicationName()); AriesApplicationContext ctx = manager.install(app); ctx.start(); HelloWorld hw = context().getService(HelloWorld.class); String result = hw.getMessage(); assertEquals(result, "hello world"); ctx.stop(); manager.uninstall(ctx); } @Test public void testAppStore() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test2.eba"))); app = manager.resolve(app); app.store(new FileOutputStream("test2-resolved.eba")); app = manager.createApplication(FileSystem.getFSRoot(new File("test2-resolved.eba"))); // application name should equal to whatever Application name provided in the application.mf assertEquals("test application 2", app.getApplicationMetadata().getApplicationName()); AriesApplicationContext ctx = manager.install(app); ctx.start(); HelloWorld hw = context().getService(HelloWorld.class); String result = hw.getMessage(); assertEquals(result, "hello world"); ctx.stop(); manager.uninstall(ctx); } @Configuration public static Option[] configuration() { return options( // framework / core bundles mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"), // Bundles junitBundles(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").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() ); } }
8,944
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/OBRResolverTest.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.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.osgi.framework.Constants.BUNDLE_MANIFESTVERSION; import static org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME; import static org.osgi.framework.Constants.BUNDLE_VERSION; import static org.osgi.framework.Constants.EXPORT_PACKAGE; import static org.osgi.framework.Constants.IMPORT_PACKAGE; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.aries.application.Content; 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.AriesApplicationManager; import org.apache.aries.application.management.ResolverException; import org.apache.aries.application.management.spi.repository.RepositoryGenerator; import org.apache.aries.application.management.spi.resolve.AriesApplicationResolver; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ModelledResourceManager; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.application.utils.manifest.ContentFactory; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.filesystem.IDirectory; import org.apache.felix.bundlerepository.Repository; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.junit.After; import org.junit.Before; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class OBRResolverTest extends AbstractIntegrationTest { public static final String CORE_BUNDLE_BY_VALUE = "core.bundle.by.value"; public static final String CORE_BUNDLE_BY_REFERENCE = "core.bundle.by.reference"; public static final String TRANSITIVE_BUNDLE_BY_VALUE = "transitive.bundle.by.value"; public static final String TRANSITIVE_BUNDLE_BY_REFERENCE = "transitive.bundle.by.reference"; public static final String BUNDLE_IN_FRAMEWORK = "org.apache.aries.util"; /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ @Before public void createApplications() throws Exception { ZipFixture bundle = ArchiveFixture.newJar().manifest() .attribute(BUNDLE_SYMBOLICNAME, CORE_BUNDLE_BY_VALUE) .attribute(BUNDLE_MANIFESTVERSION, "2") .attribute(IMPORT_PACKAGE, "p.q.r, x.y.z, javax.naming, " + BUNDLE_IN_FRAMEWORK) .attribute(BUNDLE_VERSION, "1.0.0").end(); FileOutputStream fout = new FileOutputStream(CORE_BUNDLE_BY_VALUE + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(BUNDLE_SYMBOLICNAME, TRANSITIVE_BUNDLE_BY_VALUE) .attribute(BUNDLE_MANIFESTVERSION, "2") .attribute(EXPORT_PACKAGE, "p.q.r") .attribute(BUNDLE_VERSION, "1.0.0").end(); fout = new FileOutputStream(TRANSITIVE_BUNDLE_BY_VALUE + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(BUNDLE_SYMBOLICNAME, TRANSITIVE_BUNDLE_BY_REFERENCE) .attribute(BUNDLE_MANIFESTVERSION, "2") .attribute(EXPORT_PACKAGE, "x.y.z") .attribute(BUNDLE_VERSION, "1.0.0").end(); fout = new FileOutputStream(TRANSITIVE_BUNDLE_BY_REFERENCE + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(BUNDLE_SYMBOLICNAME, CORE_BUNDLE_BY_REFERENCE) .attribute(BUNDLE_MANIFESTVERSION, "2") .attribute(EXPORT_PACKAGE, "d.e.f") .attribute(BUNDLE_VERSION, "1.0.0").end(); fout = new FileOutputStream(CORE_BUNDLE_BY_REFERENCE + ".jar"); bundle.writeOut(fout); fout.close(); bundle = ArchiveFixture.newJar().manifest() .attribute(BUNDLE_SYMBOLICNAME, CORE_BUNDLE_BY_REFERENCE) .attribute(BUNDLE_MANIFESTVERSION, "2") .attribute(EXPORT_PACKAGE, "d.e.f").end(); fout = new FileOutputStream(CORE_BUNDLE_BY_REFERENCE + "_0.0.0.jar"); bundle.writeOut(fout); fout.close(); ZipFixture testEba = ArchiveFixture.newZip() .binary("META-INF/APPLICATION.MF", OBRResolverTest.class.getClassLoader().getResourceAsStream("obr/APPLICATION.MF")) .end() .binary(CORE_BUNDLE_BY_VALUE + ".jar", new FileInputStream(CORE_BUNDLE_BY_VALUE + ".jar")).end() .binary(TRANSITIVE_BUNDLE_BY_VALUE + ".jar", new FileInputStream(TRANSITIVE_BUNDLE_BY_VALUE + ".jar")).end(); fout = new FileOutputStream("blog.eba"); testEba.writeOut(fout); fout.close(); } @After public void clearRepository() { RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); if ((repos != null) && (repos.length > 0)) { for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } } } @Test(expected = ResolverException.class) public void testBlogAppResolveFail() throws ResolverException, Exception { // provision against the local runtime System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "false"); generateOBRRepoXML(TRANSITIVE_BUNDLE_BY_REFERENCE + ".jar", CORE_BUNDLE_BY_REFERENCE + "_0.0.0.jar"); RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL()); AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("blog.eba"))); //installing requires a valid url for the bundle in repository.xml. app = manager.resolve(app); } /** * Test the resolution should fail because the required package org.apache.aries.util is provided by the local runtime, * which is not included when provisioning. * * @throws Exception */ @Test(expected = ResolverException.class) public void testProvisionExcludeLocalRepo() throws Exception { // do not provision against the local runtime System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "true"); generateOBRRepoXML(TRANSITIVE_BUNDLE_BY_REFERENCE + ".jar", CORE_BUNDLE_BY_REFERENCE + ".jar"); RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL()); AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("blog.eba"))); //installing requires a valid url for the bundle in repository.xml. app = manager.resolve(app); } @Test public void test_resolve_self_contained_app_in_isolation() throws Exception { assertEquals(2, createAndResolveSelfContainedApp("org.osgi.framework").size()); } @Test(expected = ResolverException.class) public void test_resolve_non_self_contained_app_in_isolation() throws Exception { createAndResolveSelfContainedApp("org.osgi.service.blueprint"); } private Collection<ModelledResource> createAndResolveSelfContainedApp(String extraImport) throws Exception { FileOutputStream fout = new FileOutputStream(new File("a.bundle.jar")); ArchiveFixture.newJar() .manifest() .attribute(BUNDLE_SYMBOLICNAME, "a.bundle") .attribute(BUNDLE_VERSION, "1.0.0") .attribute(BUNDLE_MANIFESTVERSION, "2") .attribute(IMPORT_PACKAGE, "a.pack.age") .end().writeOut(fout); fout.close(); fout = new FileOutputStream(new File("b.bundle.jar")); ArchiveFixture.newJar() .manifest() .attribute(BUNDLE_SYMBOLICNAME, "b.bundle") .attribute(BUNDLE_VERSION, "1.0.0") .attribute(BUNDLE_MANIFESTVERSION, "2") .attribute(IMPORT_PACKAGE, extraImport) .attribute(EXPORT_PACKAGE, "a.pack.age") .end().writeOut(fout); fout.close(); ModelledResourceManager mrm = context().getService(ModelledResourceManager.class); ModelledResource aBundle = mrm.getModelledResource(FileSystem.getFSRoot(new File("a.bundle.jar"))); ModelledResource bBundle = mrm.getModelledResource(FileSystem.getFSRoot(new File("b.bundle.jar"))); AriesApplicationResolver resolver = context().getService(AriesApplicationResolver.class); return resolver.resolveInIsolation("test.app", "1.0.0", Arrays.asList(aBundle, bBundle), Arrays.<Content>asList(ContentFactory.parseContent("a.bundle", "1.0.0"), ContentFactory.parseContent("b.bundle", "1.0.0"))); } @Test public void testBlogApp() throws Exception { // provision against the local runtime System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "false"); generateOBRRepoXML(TRANSITIVE_BUNDLE_BY_REFERENCE + ".jar", CORE_BUNDLE_BY_REFERENCE + ".jar"); RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class); Repository[] repos = repositoryAdmin.listRepositories(); for (Repository repo : repos) { repositoryAdmin.removeRepository(repo.getURI()); } repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL()); AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("blog.eba"))); //installing requires a valid url for the bundle in repository.xml. app = manager.resolve(app); DeploymentMetadata depMeta = app.getDeploymentMetadata(); List<DeploymentContent> provision = depMeta.getApplicationProvisionBundles(); assertEquals(provision.toString(), 3, provision.size()); List<String> bundleSymbolicNames = new ArrayList<String>(); for (DeploymentContent dep : provision) { bundleSymbolicNames.add(dep.getContentName()); } assertTrue("Bundle " + TRANSITIVE_BUNDLE_BY_REFERENCE + " not found.", bundleSymbolicNames.contains(TRANSITIVE_BUNDLE_BY_REFERENCE)); assertTrue("Bundle " + TRANSITIVE_BUNDLE_BY_VALUE + " not found.", bundleSymbolicNames.contains(TRANSITIVE_BUNDLE_BY_VALUE)); assertTrue("Bundle " + BUNDLE_IN_FRAMEWORK + " not found.", bundleSymbolicNames.contains(BUNDLE_IN_FRAMEWORK)); AriesApplicationContext ctx = manager.install(app); ctx.start(); Set<Bundle> bundles = ctx.getApplicationContent(); assertEquals("Number of bundles provisioned in the app", 4, bundles.size()); ctx.stop(); manager.uninstall(ctx); } private void generateOBRRepoXML(String... bundleFiles) throws Exception { Set<ModelledResource> mrs = new HashSet<ModelledResource>(); FileOutputStream fout = new FileOutputStream("repository.xml"); RepositoryGenerator repositoryGenerator = context().getService(RepositoryGenerator.class); ModelledResourceManager modelledResourceManager = context().getService(ModelledResourceManager.class); for (String fileName : bundleFiles) { File bundleFile = new File(fileName); IDirectory jarDir = FileSystem.getFSRoot(bundleFile); mrs.add(modelledResourceManager.getModelledResource(bundleFile.toURI().toString(), jarDir)); } repositoryGenerator.generateRepository("Test repo description", mrs, fout); fout.close(); } @Configuration public static Option[] configuration() { return options( // framework / core bundles mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // Bundles junitBundles(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), // Bundles 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.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces").versionAsInProject()); } }
8,945
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/UpdateAppTest.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.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.File; import java.io.FileOutputStream; import java.util.Hashtable; 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.AriesApplicationContext; import org.apache.aries.application.management.AriesApplicationManager; import org.apache.aries.application.management.ResolveConstraint; 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.BundleSuggestion; import org.apache.aries.application.management.spi.repository.RepositoryGenerator; import org.apache.aries.application.management.spi.update.UpdateStrategy; import org.apache.aries.application.modelling.ModellingManager; import org.apache.aries.application.runtime.itests.util.IsolationTestUtils; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.isolated.sample.HelloWorld; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.apache.aries.util.VersionRange; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.junit.Before; import org.junit.Ignore; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class UpdateAppTest extends AbstractIntegrationTest { private static final String SAMPLE_APP_NAME = "org.apache.aries.sample2"; /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ static boolean createdApplications = false; @Before public void createApplications() throws Exception { if (createdApplications) { return; } ZipFixture testEba = ArchiveFixture.newZip() .binary("META-INF/APPLICATION.MF", UpdateAppTest.class.getClassLoader().getResourceAsStream("isolated/APPLICATION.MF")) .jar("sample.jar") .manifest().symbolicName("org.apache.aries.isolated.sample") .attribute("Bundle-Version", "1.0.0") .end() .binary("org/apache/aries/isolated/sample/HelloWorld.class", UpdateAppTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorld.class")) .binary("org/apache/aries/isolated/sample/HelloWorldImpl.class", UpdateAppTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorldImpl.class")) .binary("OSGI-INF/blueprint/aries.xml", UpdateAppTest.class.getClassLoader().getResourceAsStream("isolated/sample-blueprint.xml")) .end(); FileOutputStream fout = new FileOutputStream("test.eba"); testEba.writeOut(fout); fout.close(); ZipFixture sample2 = ArchiveFixture.newJar() .manifest().symbolicName("org.apache.aries.isolated.sample") .attribute("Bundle-Version", "2.0.0") .end() .binary("org/apache/aries/isolated/sample/HelloWorld.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorld.class")) .binary("org/apache/aries/isolated/sample/HelloWorldImpl.class", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("org/apache/aries/isolated/sample/HelloWorldImpl.class")) .binary("OSGI-INF/blueprint/aries.xml", IsolatedRuntimeTest.class.getClassLoader().getResourceAsStream("isolated/sample2-blueprint.xml")) .end(); fout = new FileOutputStream("sample_2.0.0.jar"); sample2.writeOut(fout); fout.close(); createdApplications = true; } @Test @Ignore public void testFullUpdate() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = setupApp(); updateApp(manager, app); assertAppMessage("hello brave new world"); } @Test @Ignore public void testFineUpdate() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = setupApp(); BundleContext oldCtx = IsolationTestUtils.findIsolatedAppBundleContext(bundleContext, SAMPLE_APP_NAME); installMockUpdateStrategy(); updateApp(manager, app); BundleContext newCtx = IsolationTestUtils.findIsolatedAppBundleContext(bundleContext, SAMPLE_APP_NAME); assertAppMessage("hello brave new world"); assertTrue("We bounced the app where the update was supposed to do an update in place", oldCtx == newCtx); } @Test @Ignore public void testUpdateThenStart() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test.eba"))); AriesApplicationContext ctx = manager.install(app); app = ctx.getApplication(); BundleContext oldCtx = IsolationTestUtils.findIsolatedAppBundleContext(bundleContext, SAMPLE_APP_NAME); installMockUpdateStrategy(); ctx = updateApp(manager, app); BundleContext newCtx = IsolationTestUtils.findIsolatedAppBundleContext(bundleContext, SAMPLE_APP_NAME); assertNull("App is not started yet but HelloWorld service is already there", IsolationTestUtils.findHelloWorldService(bundleContext, SAMPLE_APP_NAME)); ctx.start(); assertAppMessage("hello brave new world"); assertTrue("We bounced the app where the update was supposed to do an update in place", oldCtx == newCtx); } private void installMockUpdateStrategy() { bundleContext.registerService(UpdateStrategy.class.getName(), new UpdateStrategy() { public boolean allowsUpdate(DeploymentMetadata newMetadata, DeploymentMetadata oldMetadata) { return true; } public void update(UpdateInfo info) throws UpdateException { BundleFramework fwk = info.getAppFramework(); Bundle old = null; for (Bundle b : fwk.getBundles()) { if (b.getSymbolicName().equals("org.apache.aries.isolated.sample")) { old = b; break; } } if (old == null) throw new RuntimeException("Could not find old bundle"); try { info.unregister(old); fwk.uninstall(old); // only contains one element at most Map<DeploymentContent, BundleSuggestion> suggestions = info.suggestBundle(info.getNewMetadata().getApplicationDeploymentContents()); BundleSuggestion toInstall = suggestions.values().iterator().next(); Bundle newBundle = fwk.install(toInstall, info.getApplication()); info.register(newBundle); if (info.startBundles()) fwk.start(newBundle); } catch (Exception e) { throw new RuntimeException(e); } } }, new Hashtable<String, String>()); } private AriesApplication setupApp() throws Exception { AriesApplicationManager manager = context().getService(AriesApplicationManager.class); AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test.eba"))); AriesApplicationContext ctx = manager.install(app); app = ctx.getApplication(); ctx.start(); assertAppMessage("hello world"); return app; } private AriesApplicationContext updateApp(AriesApplicationManager manager, AriesApplication app) throws Exception { IsolationTestUtils.prepareSampleBundleV2(bundleContext, context().getService(RepositoryGenerator.class), context().getService(RepositoryAdmin.class), context().getService(ModellingManager.class)); AriesApplication newApp = manager.resolve(app, new ResolveConstraint() { public String getBundleName() { return "org.apache.aries.isolated.sample"; } public VersionRange getVersionRange() { return ManifestHeaderProcessor.parseVersionRange("[2.0.0,2.0.0]", true); } }); return manager.update(app, newApp.getDeploymentMetadata()); } private void assertAppMessage(String message) throws Exception { HelloWorld hw = IsolationTestUtils.findHelloWorldService(bundleContext, SAMPLE_APP_NAME); assertNotNull(hw); assertEquals(message, hw.getMessage()); } @Configuration public static Option[] configuration() { return options( // framework / core bundles mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Logging systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // do not provision against the local runtime systemProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP).value("true"), // Bundles junitBundles(), 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.transaction", "org.apache.aries.transaction.blueprint").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.framework").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.framework.management").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.repository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.isolated").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec").versionAsInProject()); } }
8,946
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/runtime/itests/util/IsolationTestUtils.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.itests.util; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Hashtable; import java.util.Set; import java.util.jar.Attributes; 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.apache.aries.application.management.spi.repository.BundleRepository; import org.apache.aries.application.management.spi.repository.RepositoryGenerator; import org.apache.aries.application.modelling.ModelledResource; import org.apache.aries.application.modelling.ModellingManager; import org.apache.aries.isolated.sample.HelloWorld; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.Version; import org.osgi.service.framework.CompositeBundle; import org.osgi.util.tracker.ServiceTracker; public class IsolationTestUtils { public static final long DEFAULT_TIMEOUT = 10000; /** * Retrieve the bundle context for an isolated application framework */ public static BundleContext findIsolatedAppBundleContext(BundleContext runtimeCtx, String appName) { for (Bundle sharedBundle : runtimeCtx.getBundles()) { if (sharedBundle.getSymbolicName().equals("shared.bundle.framework")) { BundleContext sharedContext = ((CompositeBundle)sharedBundle).getCompositeFramework().getBundleContext(); for (Bundle appBundle : sharedContext.getBundles()) { if (appBundle.getSymbolicName().equals(appName)) { return ((CompositeBundle)appBundle).getCompositeFramework().getBundleContext(); } } break; } } return null; } /** * Set up the necessary resources for installing version 2 of the org.apache.aries.isolated.sample sample bundle, * which returns the message "hello brave new world" rather than "hello world" * * This means setting up a global bundle repository as well as a global OBR repository */ public static void prepareSampleBundleV2(BundleContext runtimeCtx, RepositoryGenerator repoGen, RepositoryAdmin repoAdmin, ModellingManager modellingManager) throws Exception { BundleRepository repo = new BundleRepository() { public int getCost() { return 1; } public BundleSuggestion suggestBundleToUse(DeploymentContent content) { if (content.getContentName().equals("org.apache.aries.isolated.sample")) { return new BundleSuggestion() { public Bundle install(BundleFramework framework, AriesApplication app) throws BundleException { File f = new File("sample_2.0.0.jar"); try { return framework.getIsolatedBundleContext().installBundle(f.toURL().toString()); } catch (MalformedURLException mue) { throw new RuntimeException(mue); } } public Version getVersion() { return new Version("2.0.0"); } public Set<Content> getImportPackage() { return Collections.emptySet(); } public Set<Content> getExportPackage() { return Collections.emptySet(); } public int getCost() { return 1; } }; } else { return null; } } }; Hashtable<String, String> props = new Hashtable<String,String>(); props.put(BundleRepository.REPOSITORY_SCOPE, BundleRepository.GLOBAL_SCOPE); runtimeCtx.registerService(BundleRepository.class.getName(), repo, props); Attributes attrs = new Attributes(); attrs.putValue("Bundle-ManifestVersion", "2"); attrs.putValue("Bundle-Version", "2.0.0"); attrs.putValue("Bundle-SymbolicName", "org.apache.aries.isolated.sample"); attrs.putValue("Manifest-Version", "1"); ModelledResource res = modellingManager.getModelledResource( new File("sample_2.0.0.jar").toURI().toString(), attrs, Collections.EMPTY_LIST, Collections.EMPTY_LIST); repoGen.generateRepository("repo.xml", Arrays.asList(res), new FileOutputStream("repo.xml")); repoAdmin.addRepository(new File("repo.xml").toURI().toString()); } public static HelloWorld findHelloWorldService(BundleContext ctx) throws Exception { if (ctx != null) { // Dive into the context and pull out the composite bundle for the app Filter osgiFilter = FrameworkUtil.createFilter("(" + Constants.OBJECTCLASS + "=" + HelloWorld.class.getName() + ")"); ServiceTracker tracker = new ServiceTracker(ctx, osgiFilter, null); tracker.open(); final Object hw = tracker.waitForService(DEFAULT_TIMEOUT); tracker.close(); if (hw != null) { // proxy because the class space between the sample app and the test bundle is not consistent return new HelloWorld() { public String getMessage() { try { Method m = hw.getClass().getMethod("getMessage"); return (String) m.invoke(hw); } catch (Exception e) { throw new RuntimeException(e); } } }; } else { return null; } } else { return null; } } /** * Find the {@link HelloWorld} service for the isolated app * @return the service object, suitably proxied so that it can be actually used, or null if the service is not present * @throws IllegalStateException if the isolated app is not installed */ public static HelloWorld findHelloWorldService(BundleContext runtimeCtx, String appName) throws Exception { BundleContext appContext = IsolationTestUtils.findIsolatedAppBundleContext(runtimeCtx, appName); if (appContext != null) { return findHelloWorldService(appContext); } else { throw new IllegalStateException("Expected to find isolated app ctx, but didn't"); } } }
8,947
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/sample
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/application/sample/appmgrclient/AppMgrClient.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.sample.appmgrclient; import java.net.MalformedURLException; import java.net.URL; import org.apache.aries.application.management.AriesApplicationManager; import org.apache.aries.application.management.ManagementException; public class AppMgrClient { private AriesApplicationManager applicationManager; public AriesApplicationManager getApplicationManager() { return applicationManager; } public void setApplicationManager(AriesApplicationManager applicationManager) { this.applicationManager = applicationManager; } public void doSomething() throws MalformedURLException, ManagementException { applicationManager.createApplication(new URL("foo")); } }
8,948
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated/config/HelloWorldManagedServiceImpl.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.isolated.config; import java.util.Dictionary; import java.util.Properties; import org.apache.aries.isolated.sample.HelloWorld; import org.apache.aries.isolated.sample.HelloWorldImpl; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; public class HelloWorldManagedServiceImpl implements BundleActivator, ManagedService { private BundleContext context; private HelloWorldImpl hw; private ServiceRegistration msRegistration; private ServiceRegistration hwRegistration; /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { Properties props = new Properties(); props.put(Constants.SERVICE_PID, "helloworld-mn"); this.context = context; this.msRegistration = context.registerService(ManagedService.class.getName(), this, (Dictionary) props); this.hwRegistration = null; //manually call our update to make sure the HW service is exposed out updated(null); } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public synchronized void stop(BundleContext context) throws Exception { this.msRegistration.unregister(); if (this.hwRegistration != null) { this.hwRegistration.unregister(); } this.context = null; this.hwRegistration = null; this.msRegistration = null; } /** * This method will re-register the helloworld service to easily track when updates * occur to configuration. */ public synchronized void updated(Dictionary properties) throws ConfigurationException { if (context != null) //means we have been stopped { if (hwRegistration != null) { hwRegistration.unregister(); } if (hw == null) { hw = new HelloWorldImpl(); } if (properties != null) { hw.setMessage((String)properties.get("message")); } hwRegistration = context.registerService(HelloWorld.class.getName(), hw, null); } } }
8,949
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated/shared/Shared.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.isolated.shared; public interface Shared { public void something(); }
8,950
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated/sample/SharedImpl.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.isolated.sample; import org.apache.aries.isolated.shared.Shared; public class SharedImpl implements Shared { @Override public void something() {} }
8,951
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated/sample/HelloWorld.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.isolated.sample; public interface HelloWorld { public String getMessage(); }
8,952
0
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated
Create_ds/aries/application/application-itests/src/test/java/org/apache/aries/isolated/sample/HelloWorldImpl.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.isolated.sample; import org.apache.aries.isolated.sample.HelloWorld; public class HelloWorldImpl implements HelloWorld { private String msg = "hello world"; public void setMessage(String msg) { this.msg = msg; } public String getMessage() { return msg; } }
8,953
0
Create_ds/aries/application/application-utils/src/test/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/test/java/org/apache/aries/application/impl/DeploymentContentImplTest.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.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.aries.util.VersionRange; import org.junit.Test; import org.osgi.framework.Version; public class DeploymentContentImplTest { @Test public void testDeploymentContent001() throws Exception { DeploymentContentImpl dc = new DeploymentContentImpl("com.travel.reservation.web;deployed-version=\"1.1.0\""); assertEquals("1.1.0", dc.getAttribute("deployed-version")); VersionRange vi = dc.getVersion(); assertTrue(vi.isExactVersion()); assertEquals(new Version("1.1.0"), dc.getExactVersion()); assertEquals("com.travel.reservation.web", dc.getContentName()); assertEquals("{deployed-version=1.1.0}", dc.getNameValueMap().toString()); } @Test public void testDeploymentContent002() throws Exception { DeploymentContentImpl dc = new DeploymentContentImpl("com.travel.reservation.business;deployed-version=2.0"); assertEquals("2.0", dc.getAttribute("deployed-version")); VersionRange vi = dc.getVersion(); assertTrue(vi.isExactVersion()); assertEquals(new Version("2.0"), dc.getExactVersion()); assertEquals("com.travel.reservation.business", dc.getContentName()); assertEquals("{deployed-version=2.0}", dc.getNameValueMap().toString()); } @Test public void testDeploymentContent003() throws Exception { DeploymentContentImpl dc = new DeploymentContentImpl("com.travel.reservation.data;deployed-version=2.1.1"); assertEquals("2.1.1", dc.getAttribute("deployed-version")); VersionRange vi = dc.getVersion(); assertTrue(vi.isExactVersion()); assertEquals(new Version("2.1.1"), dc.getExactVersion()); assertEquals("com.travel.reservation.data", dc.getContentName()); assertEquals("{deployed-version=2.1.1}", dc.getNameValueMap().toString()); } }
8,954
0
Create_ds/aries/application/application-utils/src/test/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/test/java/org/apache/aries/application/impl/ApplicationMetadataImplTest.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.impl; import static org.junit.Assert.*; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.ApplicationMetadataFactory; import org.apache.aries.application.Content; import org.apache.aries.application.ServiceDeclaration; import org.apache.aries.application.impl.ApplicationMetadataFactoryImpl; import org.junit.Test; import org.osgi.framework.Version; public class ApplicationMetadataImplTest { @Test public void testBasicMetadataCreation() throws IOException { ApplicationMetadataFactory manager = new ApplicationMetadataFactoryImpl(); ApplicationMetadata app = manager.parseApplicationMetadata(getClass().getResourceAsStream("/META-INF/APPLICATION.MF")); Assert.assertEquals("Travel Reservation", app.getApplicationName()); } @Test public void testMetadataCreation() throws Exception { ApplicationMetadataFactory manager = new ApplicationMetadataFactoryImpl(); ApplicationMetadata app = manager.parseApplicationMetadata(getClass().getResourceAsStream("/META-INF/APPLICATION4.MF")); assertEquals("Travel Reservation", app.getApplicationName()); assertEquals("com.travel.reservation", app.getApplicationSymbolicName()); assertEquals(Version.parseVersion("1.2.0"), app.getApplicationVersion()); List<Content> appContents = app.getApplicationContents(); assertEquals(2, appContents.size()); Content appContent1 = new ContentImpl("com.travel.reservation.business"); Map<String, String> attrs = new HashMap<String, String>(); attrs.put("version", "\"[1.1.0,1.2.0)\""); Content appContent2 = new ContentImpl("com.travel.reservation.web", attrs); assertTrue(appContents.contains(appContent2)); assertTrue(appContents.contains(appContent1)); List<ServiceDeclaration> importedService = app.getApplicationImportServices(); assertEquals(2, importedService.size()); assertTrue(importedService.contains(new ServiceDeclarationImpl("com.travel.flight.api"))); assertTrue(importedService.contains(new ServiceDeclarationImpl("com.travel.rail.api"))); List<ServiceDeclaration> exportedService = app.getApplicationExportServices(); assertTrue(exportedService.contains(new ServiceDeclarationImpl("com.travel.reservation"))); } }
8,955
0
Create_ds/aries/application/application-utils/src/test/java/org/apache/aries/application/utils
Create_ds/aries/application/application-utils/src/test/java/org/apache/aries/application/utils/manifest/ManifestProcessorTest.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.utils.manifest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.Manifest; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.Content; import org.apache.aries.application.impl.ApplicationMetadataFactoryImpl; import org.apache.aries.util.VersionRange; import org.apache.aries.util.manifest.ManifestProcessor; import org.junit.Test; import org.osgi.framework.Version; public class ManifestProcessorTest { private String appName = "Travel Reservation"; /** * Check a simple manifest can be read. * @throws Exception */ @Test public void testSimpleManifest() throws Exception { //the values of the manifest //intentionally include a couple of long lines Map<String, String> pairs = new HashMap<String, String>(); pairs.put("Manifest-Version", "1.0"); pairs.put("Application-ManifestVersion", "1.0"); pairs.put("Application-Name", appName ); pairs.put("Application-SymbolicName", "com.travel.reservation"); pairs.put("Application-Version", "1.2"); pairs.put("Application-Content", "com.travel.reservation.web;version=\"[1.1.0,1.2.0)\",com.travel.reservation.business"); pairs.put("Export-Package", "com.travel.reservation.api;version=1.2"); pairs.put("Import-Package", "com.travel.flight.api;version=\"[2.1.1,3.0.0)\",com.travel.rail.api;version=\"[1.0.0,2.0.0)\""); pairs.put("Application-Services", "services.xml"); InputStream in = getClass().getClassLoader().getResourceAsStream("META-INF/APPLICATION.MF"); Manifest mf = new Manifest(in); Map<String, String> map = ManifestProcessor.readManifestIntoMap(mf); assertNotNull(map); //check all the expected keys and values for (String key : pairs.keySet()){ assertTrue("Key: " + key + " was not found",map.containsKey(key)); String value = map.get(key); assertNotNull("Value was not present for key: " + key ,value); assertEquals("Value was not correct for key: " + key ,pairs.get(key),value); } //check there aren't any extra entries in the map that weren't expected assertEquals("The maps did not match",pairs,map); } /** * Check metadata can be extracted from a simple manifest. */ @Test public void testManifestMetadata() throws Exception { ApplicationMetadataFactoryImpl manager = new ApplicationMetadataFactoryImpl(); InputStream in = getClass().getClassLoader().getResourceAsStream("META-INF/APPLICATION.MF"); ApplicationMetadata am = manager.parseApplicationMetadata(in); assertNotNull(am); assertEquals(am.getApplicationName(),appName); //"com.travel.reservation.web;version=\"[1.1.0,1.2.0)\",com.travel.reservation.business", List<Content> contents = am.getApplicationContents(); for (Content content : contents){ if ("com.travel.reservation.web".equals(content.getContentName())){ VersionRange vr = content.getVersion(); assertEquals(vr.getMinimumVersion(),new Version("1.1.0")); assertEquals(vr.getMaximumVersion(),new Version("1.2.0")); } else if("com.travel.reservation.business".equals(content.getContentName())){ VersionRange vr = content.getVersion(); assertEquals(new Version(0,0,0), vr.getMinimumVersion()); } else fail("Unexepcted content name " + content.getContentName()); } } /** * Check metadata can be extracted from a manifest that uses multiple lines * for a single manifest attribute. */ @Test public void testManifestMetadataWithMultiLineEntries() throws Exception { ApplicationMetadataFactoryImpl manager = new ApplicationMetadataFactoryImpl(); InputStream in = getClass().getClassLoader().getResourceAsStream("META-INF/APPLICATION2.MF"); ApplicationMetadata am = manager.parseApplicationMetadata(in); assertNotNull(am); assertEquals(am.getApplicationName(),appName); //"com.travel.reservation.web;version=\"[1.1.0,1.2.0)\",com.travel.reservation.business", List<Content> contents = am.getApplicationContents(); for (Content content : contents){ if ("com.travel.reservation.web".equals(content.getContentName())){ VersionRange vr = content.getVersion(); assertEquals(vr.getMinimumVersion(),new Version("1.1.0")); assertEquals(vr.getMaximumVersion(),new Version("1.2.0")); } else if("com.travel.reservation.business".equals(content.getContentName())){ VersionRange vr = content.getVersion(); assertEquals(new Version(0,0,0), vr.getMinimumVersion()); } else fail("Unexepcted content name " + content.getContentName()); } } @Test public void testManifestWithoutEndingInNewLine() throws Exception { ApplicationMetadataFactoryImpl manager = new ApplicationMetadataFactoryImpl(); InputStream in = getClass().getClassLoader().getResourceAsStream("META-INF/APPLICATION3.MF"); ApplicationMetadata am = manager.parseApplicationMetadata(in); assertNotNull(am); assertEquals("Wrong number of bundles are in the application", 1, am.getApplicationContents().size()); assertEquals("Wrong bundle name", "org.apache.aries.applications.test.bundle", am.getApplicationContents().get(0).getContentName()); } }
8,956
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/impl/ApplicationMetadataFactoryImpl.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.impl; import java.io.IOException; import java.io.InputStream; import java.util.jar.Manifest; import org.apache.aries.application.ApplicationMetadata; import org.apache.aries.application.ApplicationMetadataFactory; import org.apache.aries.util.manifest.ManifestProcessor; import org.osgi.framework.Version; public class ApplicationMetadataFactoryImpl implements ApplicationMetadataFactory { public ApplicationMetadata parseApplicationMetadata(InputStream in) throws IOException { Manifest man = ManifestProcessor.parseManifest(in); ApplicationMetadata metadata = new ApplicationMetadataImpl(man); return metadata; } public ApplicationMetadata createApplicationMetadata(Manifest man) { return new ApplicationMetadataImpl(man); } }
8,957
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/impl/DeploymentMetadataImpl.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.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; 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 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.DeploymentContent; import org.apache.aries.application.DeploymentMetadata; 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.ResolverException; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.application.utils.FilterUtils; import org.apache.aries.util.VersionRange; import org.apache.aries.util.manifest.ManifestProcessor; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.Version; public class DeploymentMetadataImpl implements DeploymentMetadata { private ApplicationMetadata _applicationMetadata; private List<DeploymentContent> _deploymentContent = new ArrayList<DeploymentContent>(); private List<DeploymentContent> _provisionSharedContent = new ArrayList<DeploymentContent>(); private List<DeploymentContent> _deployedUseBundleContent = new ArrayList<DeploymentContent>(); private Set<Content> _deploymentImportPackage = new HashSet<Content>(); private Map<String, String> _deploymentCustomEntries = new HashMap<String, String>(); private Map<String, String> _deploymentEntries = new HashMap<String, String>(); private Collection<Filter> _deployedImportService = new ArrayList<Filter>(); public DeploymentMetadataImpl (AriesApplication app, Set<BundleInfo> bundlesRequired) throws ResolverException { _applicationMetadata = app.getApplicationMetadata(); _deploymentContent = new ArrayList<DeploymentContent>(); _provisionSharedContent = new ArrayList<DeploymentContent>(); _deployedUseBundleContent = new ArrayList<DeploymentContent>(); Map<String, VersionRange> appContent = new HashMap<String, VersionRange>(); for (Content c : app.getApplicationMetadata().getApplicationContents()) { appContent.put(c.getContentName(), c.getVersion()); } Map<String, VersionRange> useBundles = new HashMap<String, VersionRange>(); for (Content c : app.getApplicationMetadata().getUseBundles()) { useBundles.put(c.getContentName(), c.getVersion()); } for (BundleInfo info : bundlesRequired) { VersionRange appContentRange = appContent.get(info.getSymbolicName()); VersionRange useBundleRange = useBundles.get(info.getSymbolicName()); DeploymentContent dp = new DeploymentContentImpl(info.getSymbolicName(), info.getVersion()); if ((appContentRange == null) && (useBundleRange == null)){ _provisionSharedContent.add(dp); } else if (appContentRange.matches(info.getVersion())) { _deploymentContent.add(dp); } else if (useBundleRange.matches(info.getVersion())) { _deployedUseBundleContent.add(dp); } else { throw new ResolverException("Bundle " + info.getSymbolicName() + " at version " + info.getVersion() + " is not in the range " + appContentRange + " or " + useBundleRange); } } } /** * Construct a DeploymentMetadata from Manifest * @param src * @throws IOException */ public DeploymentMetadataImpl(Manifest mf) throws InvalidAttributeException{ _applicationMetadata = new ApplicationMetadataImpl (mf); Attributes attributes = mf.getMainAttributes(); parseDeploymentContent(attributes.getValue(AppConstants.DEPLOYMENT_CONTENT), _deploymentContent); parseDeploymentContent(attributes.getValue(AppConstants.DEPLOYMENT_PROVISION_BUNDLE), _provisionSharedContent); parseDeploymentContent(attributes.getValue(AppConstants.DEPLOYMENT_USE_BUNDLE), _deployedUseBundleContent); parseContent(attributes.getValue(AppConstants.DEPLOYMENT_IMPORT_PACKAGES), _deploymentImportPackage); _deployedImportService = getFilters(attributes.getValue(AppConstants.DEPLOYMENTSERVICE_IMPORT)); _deploymentCustomEntries = getCustomEntries(attributes); _deploymentEntries = getEntries(attributes); } public DeploymentMetadataImpl(Map<String, String> map) throws InvalidAttributeException{ Attributes attributes = new Attributes(); if (map != null) { for (Map.Entry<String, String> entry : map.entrySet()) { attributes.putValue(entry.getKey(), entry.getValue()); } } parseDeploymentContent(map.get(AppConstants.DEPLOYMENT_CONTENT), _deploymentContent); parseDeploymentContent(map.get(AppConstants.DEPLOYMENT_PROVISION_BUNDLE), _provisionSharedContent); parseDeploymentContent(map.get(AppConstants.DEPLOYMENT_USE_BUNDLE), _deployedUseBundleContent); parseContent(attributes.getValue(AppConstants.DEPLOYMENT_IMPORT_PACKAGES), _deploymentImportPackage); _deployedImportService = getFilters(attributes.getValue(AppConstants.DEPLOYMENTSERVICE_IMPORT)); _deploymentCustomEntries = getCustomEntries(attributes); _deploymentEntries = getEntries(attributes); } private Collection<Attributes.Name> getDeploymentStandardHeaders() { Collection<Attributes.Name> standardKeys = new HashSet<Attributes.Name> (); standardKeys.add(new Attributes.Name(AppConstants.APPLICATION_MANIFEST_VERSION)); standardKeys.add(new Attributes.Name(AppConstants.DEPLOYMENT_CONTENT)); standardKeys.add(new Attributes.Name(AppConstants.DEPLOYMENT_PROVISION_BUNDLE)); standardKeys.add(new Attributes.Name(AppConstants.DEPLOYMENT_USE_BUNDLE)); standardKeys.add(new Attributes.Name(AppConstants.DEPLOYMENT_IMPORT_PACKAGES)); standardKeys.add(new Attributes.Name(AppConstants.DEPLOYMENTSERVICE_IMPORT)); standardKeys.add(new Attributes.Name(AppConstants.APPLICATION_SYMBOLIC_NAME)); standardKeys.add(new Attributes.Name(AppConstants.APPLICATION_VERSION)); return standardKeys; } private Collection<String> getCustomHeaders(Attributes attrs) { Collection<String> customKeys = new HashSet<String>(); Collection<Attributes.Name> standardKeys = getDeploymentStandardHeaders(); if ((attrs != null) && (!!!attrs.isEmpty())) { Set<Object> keys = attrs.keySet(); if ((keys != null) && (!!!keys.isEmpty())) { for (Object eachKey : keys) { String key = eachKey.toString(); customKeys.add(key); } customKeys.removeAll(standardKeys); } } return customKeys; } private String getContentsAsString (Collection<Content> contents) { StringBuilder builder = new StringBuilder(); boolean beginning = true; for (Content c : contents) { if (!!!beginning) { builder.append(","); } builder.append(c); beginning = false; } return builder.toString(); } public List<DeploymentContent> getApplicationDeploymentContents() { return Collections.unmodifiableList(_deploymentContent); } public List<DeploymentContent> getApplicationProvisionBundles() { return Collections.unmodifiableList(_provisionSharedContent); } public ApplicationMetadata getApplicationMetadata() { return _applicationMetadata; } public String getApplicationSymbolicName() { return _applicationMetadata.getApplicationSymbolicName(); } public Version getApplicationVersion() { return _applicationMetadata.getApplicationVersion(); } public void store(File f) throws FileNotFoundException, IOException{ FileOutputStream fos = new FileOutputStream (f); store(fos); fos.close(); } public void store(OutputStream out) throws IOException { // We weren't built from a Manifest, so construct one. Manifest mf = new Manifest(); Attributes attributes = mf.getMainAttributes(); attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), AppConstants.MANIFEST_VERSION); attributes.putValue(AppConstants.APPLICATION_VERSION, getApplicationVersion().toString()); attributes.putValue(AppConstants.APPLICATION_SYMBOLIC_NAME, getApplicationSymbolicName()); if ((_deploymentContent != null) && (!_deploymentContent.isEmpty())) { attributes.putValue(AppConstants.DEPLOYMENT_CONTENT, getDeploymentContentsAsString(_deploymentContent)); } if ((_provisionSharedContent != null) && (!_provisionSharedContent.isEmpty())) { attributes.putValue(AppConstants.DEPLOYMENT_PROVISION_BUNDLE, getDeploymentContentsAsString(_provisionSharedContent)); } if ((_deployedUseBundleContent != null) && (!_deployedUseBundleContent.isEmpty())) { attributes.putValue(AppConstants.DEPLOYMENT_USE_BUNDLE, getDeploymentContentsAsString(_deployedUseBundleContent)); } if ((_deploymentImportPackage != null) && (!_deploymentImportPackage.isEmpty())) { attributes.putValue(AppConstants.DEPLOYMENT_IMPORT_PACKAGES, getContentsAsString(_deploymentImportPackage)); } if ((_deployedImportService != null) && (!!!_deployedImportService.isEmpty())) { attributes.putValue(AppConstants.DEPLOYMENTSERVICE_IMPORT, convertFiltersToString(_deployedImportService, ",") ); } // let's write out the custom headers if ((_deploymentCustomEntries != null) && (_deploymentCustomEntries.isEmpty())) { for (Map.Entry<String, String> customEntry : _deploymentCustomEntries.entrySet()) { attributes.putValue(customEntry.getKey(), customEntry.getValue()); } } mf.write(out); } private String getDeploymentContentsAsString (List<DeploymentContent> content) { StringBuilder builder = new StringBuilder(); for (DeploymentContent dc : content) { builder.append(dc.getContentName()); builder.append(';' + AppConstants.DEPLOYMENT_BUNDLE_VERSION + "="); builder.append(dc.getExactVersion()); builder.append(","); } if (builder.length() > 0) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } private void parseDeploymentContent(String content, List<DeploymentContent> contents) { List<String> pcList = ManifestProcessor.split(content, ","); for (String s : pcList) { contents.add(new DeploymentContentImpl(s)); } } private void parseContent(String content, Collection<Content> contents) { List<String> pcList = ManifestProcessor.split(content, ","); for (String s : pcList) { contents.add(new ContentImpl(s)); } } public List<DeploymentContent> getDeployedUseBundle() { return Collections.unmodifiableList(_deployedUseBundleContent); } public Set<Content> getImportPackage() { return Collections.unmodifiableSet(_deploymentImportPackage); } public Collection<Filter> getDeployedServiceImport() { return Collections.unmodifiableCollection(_deployedImportService); } public Map<String, String> getHeaders() { return Collections.unmodifiableMap(_deploymentEntries); } private Map<String, String> getEntries(Attributes attrs) { Map<String, String> entries = new HashMap<String, String>(); if ((attrs != null) && (!attrs.isEmpty())) { Set<Object> keys = attrs.keySet(); for (Object key : keys) { entries.put(key.toString(), attrs.getValue((Attributes.Name)key)); } } return entries; } private Map<String, String> getCustomEntries(Attributes attrs) { Map<String, String> customEntry = new HashMap<String, String> (); Collection<String> customHeaders = getCustomHeaders(attrs); if ((customHeaders != null) && (customHeaders.isEmpty())) { for (String customHeader : customHeaders) customEntry.put(customHeader, attrs.getValue(customHeader)); } return customEntry; } private Collection<Filter> getFilters(String filterString) throws InvalidAttributeException{ Collection<Filter> filters = new ArrayList<Filter>(); List<String> fs = ManifestProcessor.split(filterString, ","); if ((fs != null) && (!!!fs.isEmpty())) { for (String filter : fs) { try { filters.add(FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(filter))); } catch (InvalidSyntaxException ise) { InvalidAttributeException iae = new InvalidAttributeException(ise); throw iae; } } } return filters; } private String convertFiltersToString(Collection<Filter> contents, String separator) { StringBuilder newContent = new StringBuilder(); if ((contents != null) && (!!!contents.isEmpty())) { boolean beginning = true; for (Filter content: contents) { if (beginning) newContent.append(separator); newContent.append(content.toString()); beginning = false; } } return newContent.toString(); } }
8,958
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/impl/ApplicationMetadataImpl.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.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; 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.Set; import java.util.Map.Entry; 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.ServiceDeclaration; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of ApplicationMetadata and DeploymentMetadata * */ public final class ApplicationMetadataImpl implements ApplicationMetadata { private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.application.management.impl"); private String appSymbolicName; private Version appVersion; private String appName; private String appScope; private final List<Content> appContents; private final List<ServiceDeclaration> importServices; private final List<ServiceDeclaration> exportServices; private final Manifest manifest; private final List<Content> useBundle; /** * create the applicationMetadata from appManifest * @param appManifest the Application.mf manifest */ public ApplicationMetadataImpl(Manifest appManifest) { this.appContents = new ArrayList<Content>(); this.useBundle = new ArrayList<Content>(); this.importServices = new ArrayList<ServiceDeclaration>(); this.exportServices = new ArrayList<ServiceDeclaration>(); setup(appManifest); // As of 7 Jan 2010 we have no setter methods. Hence it's currently // fine to keep a copy of appManifest, and to use it in the store() // method. manifest = appManifest; } /** * setup the application metadata from the appManifest * @param appManifest application.mf manifest */ private void setup(Manifest appManifest) { Map<String, String> appMap = readManifestIntoMap(appManifest); // configure the appSymbolicName and appVersion this.appSymbolicName = appMap.get(AppConstants.APPLICATION_SYMBOLIC_NAME); this.appVersion = new Version(appMap.get(AppConstants.APPLICATION_VERSION)); this.appName = appMap.get(AppConstants.APPLICATION_NAME); this.appScope = this.appSymbolicName + "_" + this.appVersion.toString(); if (this.appSymbolicName == null || this.appVersion == null) { throw new IllegalArgumentException("Failed to create ApplicationMetadataImpl object from Manifest " + appManifest); } // configure appContents // use parseImportString as we don't allow appContents to be duplicate String applicationContents = appMap.get(AppConstants.APPLICATION_CONTENT); Map<String, Map<String, String>> appContentsMap = ManifestHeaderProcessor.parseImportString(applicationContents); for (Map.Entry<String, Map<String, String>> e : appContentsMap.entrySet()) { this.appContents.add(new ContentImpl(e.getKey(), e.getValue())); } String useBundleStr = appMap.get(AppConstants.APPLICATION_USE_BUNDLE); if (useBundleStr != null) { Map<String, Map<String, String>> useBundleMap = ManifestHeaderProcessor.parseImportString(useBundleStr); for (Map.Entry<String, Map<String, String>> e : useBundleMap.entrySet()) { this.useBundle.add(new ContentImpl(e.getKey(), e.getValue())); } } String allServiceImports = appMap.get(AppConstants.APPLICATION_IMPORT_SERVICE); List<String> serviceImports = ManifestHeaderProcessor.split(allServiceImports, ","); for (String s: serviceImports) { try { ServiceDeclaration dec = new ServiceDeclarationImpl(s); importServices.add(dec); } catch (InvalidSyntaxException ise) { _logger.warn("APPUTILS0013E", new Object[] {s, appSymbolicName}); } } String allServiceExports = appMap.get(AppConstants.APPLICATION_EXPORT_SERVICE); List<String> serviceExports = ManifestHeaderProcessor.split(allServiceExports, ","); for (String s: serviceExports) { try { ServiceDeclaration dec = new ServiceDeclarationImpl(s); exportServices.add(dec); } catch (InvalidSyntaxException ise) { _logger.warn("APPUTILS0014E", new Object[] {s, appSymbolicName}); } } } /** * Reads a manifest's main attributes into a String->String map. * <p> * Will always return a map, empty if the manifest had no attributes. * * @param mf The manifest to read. * @return Map of manifest main attributes. */ private Map<String, String> readManifestIntoMap(Manifest mf){ HashMap<String, String> props = new HashMap<String, String>(); Attributes mainAttrs = mf.getMainAttributes(); if (mainAttrs!=null){ Set<Entry<Object, Object>> attributeSet = mainAttrs.entrySet(); if (attributeSet != null){ // Copy all the manifest headers across. The entry set should be a set of // Name to String mappings, by calling String.valueOf we do the conversion // to a string and we do not NPE. for (Map.Entry<Object, Object> entry : attributeSet) { props.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); } } } return props; } public List<Content> getApplicationContents() { return Collections.unmodifiableList(this.appContents); } public List<ServiceDeclaration> getApplicationExportServices() { return Collections.unmodifiableList(this.exportServices); } public List<ServiceDeclaration> getApplicationImportServices() { return Collections.unmodifiableList(this.importServices); } public String getApplicationSymbolicName() { return this.appSymbolicName; } public Version getApplicationVersion() { return this.appVersion; } public String getApplicationName() { return this.appName; } public String getApplicationScope() { return appScope; } public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (other instanceof ApplicationMetadataImpl) { return appScope.equals(((ApplicationMetadataImpl)other).appScope); } return false; } @Override public int hashCode() { return appScope.hashCode(); } public void store(File f) throws IOException { FileOutputStream fos = new FileOutputStream (f); store(fos); fos.close(); } public void store(OutputStream out) throws IOException { if (manifest != null) { Attributes att = manifest.getMainAttributes(); if ((att.getValue(Attributes.Name.MANIFEST_VERSION.toString())) == null) { att.putValue(Attributes.Name.MANIFEST_VERSION.toString(), AppConstants.MANIFEST_VERSION); } manifest.write(out); } } public Collection<Content> getUseBundles() { return this.useBundle; } }
8,959
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/impl/DeploymentContentImpl.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.impl; import java.util.HashMap; import java.util.Map; import org.apache.aries.application.DeploymentContent; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.util.VersionRange; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Version; public final class DeploymentContentImpl implements DeploymentContent { private final ContentImpl _content; /** * DeploymentContent relates to a bundle at a particular version. * We can therefore assume that the Version passed into this * constructor is the exact version in question. * @param bundleSymbolicName * @param version */ public DeploymentContentImpl (String bundleSymbolicName, Version version) { Map<String, String> nvMap = new HashMap<String, String>(); nvMap.put(AppConstants.DEPLOYMENT_BUNDLE_VERSION, version.toString()); _content = new ContentImpl (bundleSymbolicName, nvMap); } /** * Construct a DeploymentContent from a string of the form, * bundle.symbolic.name;deployedContent="1.2.3" * @param deployedContent */ public DeploymentContentImpl (String deployedContent) { _content = new ContentImpl (deployedContent); } public Version getExactVersion() { return getVersion().getExactVersion(); } public String getAttribute(String key) { return _content.getAttribute(key); } public Map<String, String> getAttributes() { return _content.getAttributes(); } public String getContentName() { return _content.getContentName(); } public String getDirective(String key) { return _content.getDirective(key); } public Map<String, String> getDirectives() { return _content.getDirectives(); } public VersionRange getVersion() { String deployedVersion = _content.getAttribute(AppConstants.DEPLOYMENT_BUNDLE_VERSION); VersionRange vr = null; if (deployedVersion != null && deployedVersion.length() > 0) { vr = ManifestHeaderProcessor.parseVersionRange(deployedVersion, true); } return vr; } @Override public boolean equals(Object other) { if (other == null) return false; if (this == other) return true; if (other instanceof DeploymentContentImpl) { return _content.equals(((DeploymentContentImpl) other)._content); } else { return false; } } public int hashCode() { return _content.hashCode(); } public Map<String, String> getNameValueMap() { return _content.getNameValueMap(); } @Override public String toString() { return _content.toString(); } }
8,960
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/impl/DeploymentMetadataFactoryImpl.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.impl; import java.io.IOException; import java.io.InputStream; import java.util.Set; import java.util.jar.Manifest; import org.apache.aries.application.DeploymentMetadata; import org.apache.aries.application.DeploymentMetadataFactory; 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.ResolverException; import org.apache.aries.util.filesystem.IFile; import org.apache.aries.util.io.IOUtils; import org.apache.aries.util.manifest.ManifestProcessor; public class DeploymentMetadataFactoryImpl implements DeploymentMetadataFactory { public DeploymentMetadata createDeploymentMetadata(AriesApplication app, Set<BundleInfo> additionalBundlesRequired) throws ResolverException { return new DeploymentMetadataImpl(app, additionalBundlesRequired); } public DeploymentMetadata parseDeploymentMetadata(IFile src) throws IOException { InputStream is = src.open(); try { return parseDeploymentMetadata(is); } finally { IOUtils.close(is); } } public DeploymentMetadata parseDeploymentMetadata(InputStream in) throws IOException { return createDeploymentMetadata(ManifestProcessor.parseManifest(in)); } public DeploymentMetadata createDeploymentMetadata(Manifest manifest) throws IOException { try { return new DeploymentMetadataImpl(manifest); } catch (InvalidAttributeException iae) { IOException e = new IOException(); e.initCause(iae); throw e; } } public DeploymentMetadata createDeploymentMetadata(IFile src) throws IOException { return parseDeploymentMetadata(src); } public DeploymentMetadata createDeploymentMetadata(InputStream in) throws IOException { return parseDeploymentMetadata(in); } }
8,961
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/impl/ServiceDeclarationImpl.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.impl; import org.apache.aries.application.Content; import org.apache.aries.application.ServiceDeclaration; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; /** * this class represents the Import-Services and Export-Services * in the Application.mf file * */ public class ServiceDeclarationImpl implements ServiceDeclaration { private static final String FILTER = "filter"; private String interfaceName; private Filter filter; /** * construct the ServiceDeclaration from the service string * @param service A single service string value from the Import-Services or Export-Services header * @throws InvalidSyntaxException */ public ServiceDeclarationImpl(String service) throws InvalidSyntaxException { Content content = new ContentImpl(service); this.interfaceName = content.getContentName(); String filterString = content.getAttribute(FILTER); if (filterString != null) { try { this.filter = FrameworkUtil.createFilter(filterString); } catch (InvalidSyntaxException ise) { throw new InvalidSyntaxException("Failed to create filter for " + service, ise.getFilter(), ise.getCause()); } } } /* (non-Javadoc) * @see org.apache.aries.application.impl.ServiceDeclaration#getInterfaceName() */ public String getInterfaceName() { return this.interfaceName; } /* (non-Javadoc) * @see org.apache.aries.application.impl.ServiceDeclaration#getFilter() */ public Filter getFilter() { return this.filter; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((filter == null) ? 0 : filter.hashCode()); result = prime * result + ((interfaceName == null) ? 0 : interfaceName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ServiceDeclarationImpl other = (ServiceDeclarationImpl) obj; if (filter == null) { if (other.filter != null) return false; } else if (!filter.equals(other.filter)) return false; if (interfaceName == null) { if (other.interfaceName != null) return false; } else if (!interfaceName.equals(other.interfaceName)) return false; return true; } }
8,962
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/impl/ContentImpl.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.impl; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.application.Content; import org.apache.aries.application.utils.internal.MessageUtil; import org.apache.aries.util.VersionRange; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Constants; import org.osgi.framework.Version; /** * Implementation of Content * */ public final class ContentImpl implements Content { private String contentName; protected Map<String, String> attributes; private Map<String, String> directives; private Map<String, String> nameValueMap; /** * * @param content Application-Content, Import-Package content */ public ContentImpl(String content) { Map<String, Map<String, String>> appContentsMap = ManifestHeaderProcessor.parseImportString(content); if (appContentsMap.size() != 1) { throw new IllegalArgumentException(MessageUtil.getMessage("APPUTILS0004E",content)); } for (Map.Entry<String, Map<String, String>> entry : appContentsMap.entrySet()) { this.contentName = entry.getKey(); this.nameValueMap= entry.getValue(); setup(); break; } } public ContentImpl (String bundleSymbolicName, Version version) { this.contentName = bundleSymbolicName; this.nameValueMap = new HashMap<String, String>(); nameValueMap.put("version", version.toString()); setup(); } public ContentImpl (String bundleSymbolicName, VersionRange version) { this.contentName = bundleSymbolicName; this.nameValueMap = new HashMap<String, String>(); nameValueMap.put("version", version.toString()); setup(); } /** * * @param contentName * @param nameValueMap */ public ContentImpl(String contentName, Map<String, String> nameValueMap) { this.contentName = contentName; this.nameValueMap= nameValueMap; setup(); } public String getContentName() { return this.contentName; } public Map<String, String> getAttributes() { return Collections.unmodifiableMap(this.attributes); } public Map<String, String> getDirectives() { return Collections.unmodifiableMap(this.directives); } public String getAttribute(String key) { String toReturn = this.attributes.get(key); return toReturn; } /** * add key value to the attributes map * @param key * @param value */ public void addAttribute(String key, String value) { this.attributes.put(key, value); } public String getDirective(String key) { String toReturn = this.directives.get(key); return toReturn; } public Map<String, String> getNameValueMap() { Map<String, String> nvm = new HashMap<String, String>(); for (String key : this.nameValueMap.keySet()) { nvm.put(key, this.nameValueMap.get(key)); } return nvm; } /** * add key value to the directives map * @param key * @param value */ public void addDirective(String key, String value) { this.directives.put(key, value); } public VersionRange getVersion() { VersionRange vi = null; if (this.attributes.get(Constants.VERSION_ATTRIBUTE) != null && this.attributes.get(Constants.VERSION_ATTRIBUTE).length() > 0) { vi = ManifestHeaderProcessor.parseVersionRange(this.attributes.get(Constants.VERSION_ATTRIBUTE)); } else { // what if version is not specified? let's interpret it as 0.0.0 vi = ManifestHeaderProcessor.parseVersionRange("0.0.0"); } return vi; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.contentName); if (!!!nameValueMap.isEmpty()) { for (Map.Entry<String, String> entry : nameValueMap.entrySet()) { builder.append(';'); builder.append(entry.getKey()); builder.append('=').append('\"'); builder.append(entry.getValue()); builder.append('\"'); } } return builder.toString(); } @Override public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (other instanceof ContentImpl) { ContentImpl otherContent = (ContentImpl)other; Map<String,String> attributesWithoutVersion = attributes; if (attributes.containsKey("version")) { attributesWithoutVersion = new HashMap<String, String>(attributes); attributesWithoutVersion.remove("version"); } Map<String, String> otherAttributesWithoutVersion = otherContent.attributes; if (otherContent.attributes.containsKey("version")) { otherAttributesWithoutVersion = new HashMap<String, String>(otherContent.attributes); otherAttributesWithoutVersion.remove("version"); } return contentName.equals(otherContent.contentName) && attributesWithoutVersion.equals(otherAttributesWithoutVersion) && directives.equals(otherContent.directives) && getVersion().equals(otherContent.getVersion()); } return false; } @Override public int hashCode() { return contentName.hashCode(); } /** * set up directives and attributes */ protected void setup() { this.attributes = new HashMap<String, String>(); this.directives = new HashMap<String, String>(); for (String key : this.nameValueMap.keySet()) { if (key.endsWith(":")) { this.directives.put(key.substring(0, key.length() - 1), this.nameValueMap.get(key)); } else { this.attributes.put(key, this.nameValueMap.get(key)); } } } }
8,963
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/FilterUtils.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.utils; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FilterUtils { private static final Pattern regexp = Pattern.compile("\\(mandatory:.*?\\)"); private static final Logger logger = LoggerFactory.getLogger(FilterUtils.class); /** * Filters we generate may contain stanzas like (mandatory:<*symbolicname) * These are for OBR, and are not OSGi friendly!!! This method removes them. * * @param filter * @return A filter with the mandatory stanzas removed or null if a null filter is supplied */ public static String removeMandatoryFilterToken(String filter) { logger.debug(LOG_ENTRY, "areMandatoryAttributesPresent", new Object[]{filter}); if(filter != null) { filter = regexp.matcher(filter).replaceAll(""); int openBraces = 0; for (int i=0; openBraces < 3; i++) { i = filter.indexOf('(', i); if (i == -1) { break; } else { openBraces++; } } // Need to prune (& or (| off front and ) off end if (openBraces < 3 && (filter.startsWith("(&") || filter.startsWith("(|"))) { filter = filter.substring(2, filter.length() - 1); } } logger.debug(LOG_EXIT, "removeMandatoryFilterToken", filter); return filter; } }
8,964
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/AppConstants.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.utils; /** * Widely used constants in parsing Aries applications */ public interface AppConstants { /** Trace group for this bundle */ public String TRACE_GROUP = "Aries.app.utils"; /** The Manifest version */ public static final String APPLICATION_MANIFEST_VERSION="Manifest-Version"; /** The application scope (used to find the applications bundle repository */ public static final String APPLICATION_SCOPE = "Application-Scope"; /** The application content directive for the application manifest */ public static final String APPLICATION_CONTENT = "Application-Content"; /** The application version directive for the application manifest */ public static final String APPLICATION_VERSION = "Application-Version"; /** The application name directive for the application manifest */ public static final String APPLICATION_NAME = "Application-Name"; /** The application symbolic name directive for the application manifest */ public static final String APPLICATION_SYMBOLIC_NAME = "Application-SymbolicName"; /** The default version for applications that do not have one */ public static final String DEFAULT_VERSION = "0.0.0"; /** The name of the application manifest in the application */ public static final String APPLICATION_MF = "META-INF/APPLICATION.MF"; /** The name of the deployment manifest in the application */ public static final String DEPLOYMENT_MF = "META-INF/DEPLOYMENT.MF"; /** The name of the META-INF directory */ public static final String META_INF = "META-INF"; /** The name of an application.xml file which will be used in processing legacy .war files */ public static final String APPLICATION_XML = "META-INF/application.xml"; /** The expected lower case suffix of a jar file */ public static final String LOWER_CASE_JAR_SUFFIX = ".jar"; /** The expected lower case suffix of a war file */ public static final String LOWER_CASE_WAR_SUFFIX = ".war"; /** The attribute used to record the deployed version of a bundle */ public static final String DEPLOYMENT_BUNDLE_VERSION = "deployed-version"; /** The name of the bundle manifest */ public static final String MANIFEST_MF = "META-INF/MANIFEST.MF"; public static final String MANIFEST_VERSION="1.0"; /** The application import service directive for the application manifest */ public static final String APPLICATION_IMPORT_SERVICE = "Application-ImportService"; /** The application export service directive for the application manifest */ public static final String APPLICATION_EXPORT_SERVICE = "Application-ExportService"; /** The use-bundle entry for the application manifest. */ public static final String APPLICATION_USE_BUNDLE = "Use-Bundle"; /* The Deployed-Content header in DEPLOYMENT.MF records all the bundles * to be deployed for a particular application. */ public static final String DEPLOYMENT_CONTENT = "Deployed-Content"; /** deployment.mf entry corresponding to application.mf Use-Bundle. */ public static final String DEPLOYMENT_USE_BUNDLE = "Deployed-Use-Bundle"; /** deployment.mf entry 'Import-Package' */ public static final String DEPLOYMENT_IMPORT_PACKAGES="Import-Package"; /** Bundle dependencies required by bundles listed in Deployed-Content or Deployed-Use-Bundle. */ public static final String DEPLOYMENT_PROVISION_BUNDLE = "Provision-Bundle"; /** Blueprint managed services imported by the isolated bundles */ public static final String DEPLOYMENTSERVICE_IMPORT = "DeployedService-Import"; public static final String PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP="provision.exclude.local.repository"; /** * Logging insert strings */ public final static String LOG_ENTRY = "Method entry: {}, args {}"; public final static String LOG_EXIT = "Method exit: {}, returning {}"; public final static String LOG_EXCEPTION = "Caught exception"; }
8,965
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/ServiceDeclarationFactory.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.utils; import org.apache.aries.application.ServiceDeclaration; import org.apache.aries.application.impl.ServiceDeclarationImpl; import org.osgi.framework.InvalidSyntaxException; public class ServiceDeclarationFactory { public static ServiceDeclaration getServiceDeclaration (String s) throws InvalidSyntaxException { return new ServiceDeclarationImpl(s); } }
8,966
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/ManifestDefaultsInjector.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.utils.manifest; import java.io.File; import java.util.Map; import java.util.jar.Manifest; import org.apache.aries.application.utils.AppConstants; import org.apache.aries.util.filesystem.FileSystem; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; import org.apache.aries.util.manifest.BundleManifest; import org.apache.aries.util.manifest.ManifestProcessor; import org.osgi.framework.Version; public class ManifestDefaultsInjector { /** * Quick adapter to update a Manifest, using content of a Zip File. * <p> * This is really a wrapper of updateManifest(Manifest,String,IDirectory), with the * IDirectory being being created from the Zip File. This method avoids other Bundles * requiring IDirectory solely for calling updateManifest. * <p> * @param mf Manifest to be updated * @param appName The name to use for this app, if the name contains * a '_' char then the portion after the '_' is used, if possible, as * the application version. * @param zip Content to use for application. * @return true if manifest modified, false otherwise. */ public static boolean updateManifest(Manifest mf, String appName, File zip){ IDirectory appPathIDir = FileSystem.getFSRoot(zip); boolean result = updateManifest(mf, appName, appPathIDir); return result; } /** * Tests the supplied manifest for the presence of expected * attributes, and where missing, adds them, and defaults * their values appropriately. * * @param mf The manifest to test & update if needed. * @param appName The name to use for this app, if the name contains * a '_' char then the portion after the '_' is used, if possible, as * the application version. * @param appDir The IDirectory to scan to build application content * property * @return true if manifest modified, false otherwise. */ public static boolean updateManifest(Manifest mf, String appName, IDirectory appDir){ Map<String, String> props = ManifestProcessor.readManifestIntoMap(mf); String extracted[] = extractAppNameAndVersionFromNameIfPossible(appName); String name = extracted[0]; String version = extracted[1]; boolean updated = false; updated |= defaultAppSymbolicName(mf, props, name); updated |= defaultAppName(mf, props, name); updated |= defaultVersion(mf, props, version); updated |= defaultAppScope(mf, props, name, version); updated |= defaultAppContent(mf, props, appDir); return updated; } /** * Takes a compound name_version string, and returns the Name & Version information. * <p> * @param name Contains name data related to this app. Expected format is name_version * @return Array of String, index 0 is appName, index 1 is Version. * <br> Name will be the appname retrieved from the 'name' argument, Version will be the * version if found and valid, otherwise will be defaulted. */ private static String[] extractAppNameAndVersionFromNameIfPossible(String name){ String retval[] = new String[2]; String appName = name; String defaultedVersion; int index = name.indexOf('_'); if (index != -1) { appName = name.substring(0, index); defaultedVersion = name.substring(index + 1); try { new Version(defaultedVersion); } catch (IllegalArgumentException e) { // this is not an error condition defaultedVersion = AppConstants.DEFAULT_VERSION; } } else { defaultedVersion = AppConstants.DEFAULT_VERSION; } retval[0] = appName; retval[1] = defaultedVersion; return retval; } /** * Sets the app symbolic name into the manifest, if not already present. * * @param mf manifest to update * @param props parsed manifest used to test if already present. * @param appName used for name if missing * @return true if manifest is modified, false otherwise. */ private static boolean defaultAppSymbolicName(Manifest mf, Map<String, String> props, String appName){ boolean updated = false; if (!props.containsKey(AppConstants.APPLICATION_SYMBOLIC_NAME)) { mf.getMainAttributes().putValue(AppConstants.APPLICATION_SYMBOLIC_NAME, appName); updated = true; } return updated; } /** * Sets the app name into the manifest, if not already present. * * @param mf manifest to update * @param props parsed manifest used to test if already present. * @param appName used for name if missing * @return true if manifest is modified, false otherwise. */ private static boolean defaultAppName(Manifest mf, Map<String, String> props, String appName){ boolean updated = false; if (!props.containsKey(AppConstants.APPLICATION_NAME)) { mf.getMainAttributes().putValue(AppConstants.APPLICATION_NAME, appName); updated = true; } return updated; } /** * Sets the app version into the manifest, if not already present. * * @param mf manifest to update * @param props parsed manifest used to test if already present. * @param appVersion used for version if missing * @return true if manifest is modified, false otherwise. */ private static boolean defaultVersion(Manifest mf, Map<String, String> props, String appVersion){ boolean updated = false; if (!props.containsKey(AppConstants.APPLICATION_VERSION)) { mf.getMainAttributes().putValue(AppConstants.APPLICATION_VERSION, appVersion); updated = true; } return updated; } /** * Sets the app scope into the manifest, if not already present. * * @param mf manifest to update * @param props parsed manifest used to test if already present. * @param name used to build appScope if app symbolic name not set. * @param version used to build appScope if app version missing. * @return true if manifest is modified, false otherwise. */ private static boolean defaultAppScope(Manifest mf, Map<String, String> props, String name, String version){ boolean updated = false; if (!props.containsKey(AppConstants.APPLICATION_SCOPE)) { String appSymbolicName; if (props.containsKey(AppConstants.APPLICATION_SYMBOLIC_NAME)) { appSymbolicName = props.get(AppConstants.APPLICATION_SYMBOLIC_NAME); } else { appSymbolicName = name; } String appVersion; if (props.containsKey(AppConstants.APPLICATION_VERSION)) { appVersion = props.get(AppConstants.APPLICATION_VERSION); } else { appVersion = version; } String appScope = appSymbolicName + '_' + appVersion; mf.getMainAttributes().putValue(AppConstants.APPLICATION_SCOPE, appScope); updated = true; } return updated; } /** * Sets the app content into the manifest, if not already present. * <p> * This method will NOT set the appcontent if it is unable to build it. * This is important, as the absence of appcontent is used by some callers * to test if a manifest contains all required content. * * @param mf manifest to update * @param props parsed manifest used to test if already present. * @param appDir used to build app content if missing. * @return true if manifest is modified, false otherwise. */ private static boolean defaultAppContent(Manifest mf, Map<String, String> props, IDirectory appDir){ boolean updated = false; if (!props.containsKey(AppConstants.APPLICATION_CONTENT)) { String appContent = calculateAppContent(appDir); if (appContent != null) { mf.getMainAttributes().putValue(AppConstants.APPLICATION_CONTENT, appContent); updated = true; } } return updated; } /** * Processes an IDirectory to find targets that require adding to the application content attrib. * * @param appDir The IDirectory to scan * @return AppContent string, or null if no content was found. */ private static String calculateAppContent(IDirectory appDir){ StringBuilder builder = new StringBuilder(); for (IFile file : appDir) { processPossibleBundle(file, builder); } String returnVal = null; if (builder.length() > 0) { builder.deleteCharAt(builder.length() - 1); returnVal = builder.toString(); } return returnVal; } /** * This method works out if the given IFile represents an OSGi bundle and if * it is then we append a matching rule to the String builder. * * @param file to file to check. * @param builder the builder to append to. */ private static void processPossibleBundle(IFile file, StringBuilder builder) { if (file.isDirectory() || (file.isFile() && (file.getName().endsWith(".jar") || file.getName().endsWith(".war")))) { BundleManifest bundleMf = BundleManifest.fromBundle(file); if (bundleMf != null) { String manifestVersion = bundleMf.getManifestVersion(); String name = bundleMf.getSymbolicName(); String version = bundleMf.getVersion().toString(); // if the bundle manifest version is 2 AND a symbolic name is specified we have a valid bundle if ("2".equals(manifestVersion) && name != null) { builder.append(name); // bundle version is not a required manifest header if (version != null) { builder.append(";version=\"["); builder.append(version); builder.append(','); builder.append(version); builder.append("]\""); } // the last comma will be removed once all content has been added builder.append(","); } } } } }
8,967
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/ContentFactory.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.utils.manifest; import java.util.Map; import org.apache.aries.application.Content; import org.apache.aries.application.impl.ContentImpl; import org.apache.aries.util.manifest.ManifestHeaderProcessor; public class ContentFactory { /** * Parse a content object * @param bundleSymbolicName bundle symbolic name * @param versionRange version range in the String format * @return Content object */ public static Content parseContent(String bundleSymbolicName, String versionRange) { return new ContentImpl(bundleSymbolicName, ManifestHeaderProcessor.parseVersionRange(versionRange)); } /** * Parse a content * @param contentName The content name * @param nameValueMap The map containing the content attributes/directives * @return a content object */ public static Content parseContent(String contentName, Map<String, String> nameValueMap) { return new ContentImpl(contentName, nameValueMap); } }
8,968
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/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.utils.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.utils.messages.APPUTILSmessages"); /** * 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,969
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/management/SimpleBundleInfo.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.utils.management; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.util.jar.Attributes; import org.apache.aries.application.Content; import org.apache.aries.application.impl.ContentImpl; import org.apache.aries.application.management.BundleInfo; import org.apache.aries.util.manifest.BundleManifest; import org.apache.aries.util.manifest.ManifestHeaderProcessor; import org.osgi.framework.Constants; import org.osgi.framework.Version; public final class SimpleBundleInfo implements BundleInfo { private Content _contentName; private Version _version; private Attributes _attributes; private Set<Content> _exportPackages = null; private Set<Content> _importPackages = null; private Set<Content> _exportServices = null; private Set<Content> _importServices = null; private Set<Content> _requireBundle = null; private String _location; public SimpleBundleInfo(BundleManifest bm, String location) { _contentName = new ContentImpl( bm.getSymbolicName(), ManifestHeaderProcessor.parseBundleSymbolicName(bm.getSymbolicName()).getAttributes()); _version = bm.getVersion(); _attributes = bm.getRawAttributes(); _location = location; } public Set<Content> getExportPackage() { if (_exportPackages == null) { _exportPackages = getContentSetFromHeader (_attributes, Constants.EXPORT_PACKAGE); } return _exportPackages; } public Set<Content> getExportService() { if (_exportServices == null) { _exportServices = getContentSetFromHeader (_attributes, Constants.EXPORT_SERVICE); } return _exportServices; } public Map<String, String> getHeaders() { Map<String, String> result = new HashMap<String, String>(); for (Entry<Object, Object> h: _attributes.entrySet()) { Attributes.Name name = (Attributes.Name) h.getKey(); String value = (String) h.getValue(); result.put(name.toString(), value); } return result; } public Set<Content> getImportPackage() { if (_importPackages == null) { _importPackages = getContentSetFromHeader (_attributes, Constants.IMPORT_PACKAGE); } return _importPackages; } public Set<Content> getImportService() { if (_importServices == null) { _importServices = getContentSetFromHeader (_attributes, Constants.IMPORT_SERVICE); } return _importServices; } public String getLocation() { return _location; } public String getSymbolicName() { return _contentName.getContentName(); } public Version getVersion() { return _version; } private Set<Content> getContentSetFromHeader (Attributes attributes, String key) { String header = _attributes.getValue(key); List<String> splitHeader = ManifestHeaderProcessor.split(header, ","); HashSet<Content> result = new HashSet<Content>(); for (String s: splitHeader) { Content c = new ContentImpl(s); result.add(c); } return result; } public Map<String, String> getBundleAttributes() { return _contentName.getAttributes(); } public Map<String, String> getBundleDirectives() { return _contentName.getDirectives(); } public Set<Content> getRequireBundle() { if (_requireBundle == null) { _requireBundle = getContentSetFromHeader(_attributes, Constants.REQUIRE_BUNDLE); } return _requireBundle; } /** * Equality is just based on the location. If you install a bundle from the same location string * you get the same Bundle, even if the underlying bundle had a different symbolic name/version. * This seems reasonable and quick. */ public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; if (other instanceof SimpleBundleInfo) { return _location.equals(((SimpleBundleInfo)other)._location); } return false; } public int hashCode() { return _location.hashCode(); } public String toString() { return _contentName.getContentName() + "_" + getVersion(); } public Attributes getRawAttributes() { return _attributes; } }
8,970
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/service/ServiceCollection.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.utils.service; import java.util.Collection; import org.osgi.framework.ServiceReference; public interface ServiceCollection<E> extends Collection<E> { public void addService(ServiceReference ref); }
8,971
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/service/ArrayServiceList.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.utils.service; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; public class ArrayServiceList<E> implements ServiceCollection<E>, List<E> { private List<E> list = new ArrayList<E>(); private List<ServiceReference> refList = new ArrayList<ServiceReference>(); private BundleContext context; public ArrayServiceList(BundleContext ctx) { context = ctx; } public boolean add(E o) { throw new UnsupportedOperationException("The operation add is not supported. Use addService with a service reference."); } public void add(int index, E element) { throw new UnsupportedOperationException("The operation add is not supported. Use addService with a service reference."); } public boolean addAll(Collection<? extends E> c) { throw new UnsupportedOperationException("The operation addAll is not supported. Use addService with a service reference."); } public boolean addAll(int index, Collection<? extends E> c) { throw new UnsupportedOperationException("The operation addAll is not supported. Use addService with a service reference."); } public synchronized void clear() { list.clear(); for (ServiceReference ref : refList) { context.ungetService(ref); } refList.clear(); } public boolean contains(Object o) { return list.contains(o); } public boolean containsAll(Collection<?> c) { return list.containsAll(c); } public E get(int index) { return list.get(index); } public int indexOf(Object o) { return list.indexOf(o); } public boolean isEmpty() { return list.isEmpty(); } public Iterator<E> iterator() { return listIterator(); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public ListIterator<E> listIterator() { return listIterator(0); } public ListIterator<E> listIterator(int index) { final ListIterator<E> it = list.listIterator(index); final ListIterator<ServiceReference> refIt = refList.listIterator(index); ListIterator<E> result = new ListIterator<E>() { private ServiceReference current; public void add(E o) { throw new UnsupportedOperationException(); } public boolean hasNext() { return it.hasNext(); } public boolean hasPrevious() { return it.hasPrevious(); } public E next() { E result = it.next(); current = refIt.next(); return result; } public int nextIndex() { return it.nextIndex(); } public E previous() { E result = it.previous(); current = refIt.previous(); return result; } public int previousIndex() { return it.previousIndex(); } public void remove() { it.remove(); refIt.remove(); context.ungetService(current); } public void set(E o) { throw new UnsupportedOperationException(); } }; return result; } public synchronized boolean remove(Object o) { int index = list.indexOf(o); ServiceReference ref = refList.remove(index); context.ungetService(ref); return list.remove(o); } public synchronized E remove(int index) { ServiceReference ref = refList.remove(index); context.ungetService(ref); return list.remove(index); } public synchronized boolean removeAll(Collection<?> c) {boolean worked = false; for (Object obj : c) { worked |= remove(obj); } return worked; } public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException("The operation retainAll is not supported."); } public E set(int index, E element) { throw new UnsupportedOperationException("The operation set is not supported."); } public int size() { return list.size(); } public List<E> subList(int fromIndex, int toIndex) { throw new UnsupportedOperationException("The operation subList is not supported."); } public Object[] toArray() { return list.toArray(); } public Object[] toArray(Object[] a) { return list.toArray(a); } public synchronized void addService(ServiceReference ref) { @SuppressWarnings("unchecked") E service = (E)context.getService(ref); if (service != null) { list.add(service); refList.add(ref); } } }
8,972
0
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils
Create_ds/aries/application/application-utils/src/main/java/org/apache/aries/application/utils/service/ExportedServiceHelper.java
package org.apache.aries.application.utils.service; 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.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.aries.application.modelling.ExportedService; import org.apache.aries.application.modelling.WrappedServiceMetadata; /* * 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. */ public class ExportedServiceHelper { public static String generatePortableExportedServiceToString(ExportedService svc) { List<String> interfaces = new ArrayList<String>(svc.getInterfaces()); Collections.sort(interfaces); List<String> props = new ArrayList<String>(); for (Map.Entry<String, Object> entry : svc.getServiceProperties().entrySet()) { Object entryValue = entry.getValue(); String entryText; if (entryValue.getClass().isArray()) { // Turn arrays into comma separated Strings Object [] entryArray = (Object[]) entryValue; StringBuilder sb = new StringBuilder(); for (Object o: entryArray) { sb.append(String.valueOf(o) + ","); } sb = sb.deleteCharAt(sb.length()-1); entryText = sb.toString(); } else { entryText = String.valueOf(entryValue); } props.add ("<entry> key=\"" + entry.getKey() + "\" value=\"" + entryText + "\"/>"); } Collections.sort(props); StringBuffer buf = new StringBuffer("<service>"); if(svc.getName() != null) { buf.append("<name>" + svc.getName() + "</name>"); } if (interfaces.size() > 0) { buf.append("<interfaces>"); } for (String i : interfaces) { buf.append("<value>" + i + "</value>"); } if (interfaces.size() > 0) { buf.append("</interfaces>"); } if (svc.getServiceProperties().size() > 0) { buf.append("<service-properties>"); } for (String p : props) { buf.append(p); } if (svc.getServiceProperties().size() > 0) { buf.append("</service-properties>"); } buf.append("</service>"); return buf.toString(); } public static boolean portableExportedServiceIdenticalOrDiffersOnlyByName(ExportedService svc, WrappedServiceMetadata wsmi) { if (svc.equals(wsmi)) { return true; } Set<String> svcInterfaces = new HashSet<String>(svc.getInterfaces()); Set<String> cmpInterfaces = new HashSet<String>(wsmi.getInterfaces()); if (!svcInterfaces.equals(cmpInterfaces)) { return false; } boolean propertiesEqual = svc.getServiceProperties().equals(wsmi.getServiceProperties()); if (!propertiesEqual) { return false; } return true; } public static boolean portableExportedServiceEquals (ExportedService left, Object right) { // Doubles as a null check if (!(right instanceof WrappedServiceMetadata)) { return false; } if (right == left) { return true; } boolean eq = left.toString().equals(right.toString()); return eq; } public static int portableExportedServiceHashCode(ExportedService svc) { int result = svc.toString().hashCode(); return result; } public static int portableExportedServiceCompareTo(ExportedService svc, WrappedServiceMetadata o) { if (o == null) { return -1; // shunt nulls to the end of any lists } int result = svc.toString().compareTo(o.toString()); return result; } }
8,973
0
Create_ds/aries/versioning/versioning-plugin/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-plugin/src/main/java/org/apache/aries/versioning/mojo/VersionCheckerMojo.java
/* * Copyright 20012 The Apache Software Foundation. * * Licensed 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.versioning.mojo; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.List; import java.util.Map; import org.apache.aries.util.manifest.BundleManifest; import org.apache.aries.versioning.check.BundleCompatibility; import org.apache.aries.versioning.check.BundleInfo; import org.apache.aries.versioning.check.VersionChange; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.repository.RepositorySystem; import org.osgi.framework.Version; /** * Check semantic version changes between an explicitly named old artifact and * the project output artifact. Optionally write packageinfo files for wrong * package versions. */ @Mojo(name = "version-check", defaultPhase = LifecyclePhase.VERIFY) public class VersionCheckerMojo extends AbstractMojo { /** * name of old artifact in * groupId:artifactId[:extension[:classifier]]:version notation */ @Parameter(property="aries.oldArtifact") private String oldArtifact; @Parameter(property="aries.skip.version.check", defaultValue = "false") private boolean skip; /** * Location of the file (defaults to main project artifact). */ @Parameter private File newFile; /** * whether to write packageinfo files into source tree */ @Parameter(property="writePackageInfos", defaultValue="false") private boolean writePackageinfos = false; /** * source tree location */ @Parameter(defaultValue="${project.basedir}/src/main/java") private File source; @Parameter private List<String> excludes; @Component private RepositorySystem repository; @Component protected MavenProject project; @Component private MavenSession session; public void execute() throws MojoExecutionException { if (skip) { return; } if ("pom".equals(project.getPackaging())) { return; } if (newFile == null) { newFile = project.getArtifact().getFile(); } if (oldArtifact != null) { try { BundleInfo newBundle = getBundleInfo(newFile); if (newBundle == null || newBundle.getBundleManifest() == null) { //not a bundle type, just return getLog().info(newFile + " is not an OSGi bundle, skipping."); return; } if (null == newBundle.getBundleManifest().getManifestVersion() && null == newBundle.getBundleManifest().getSymbolicName() && Version.emptyVersion.equals(newBundle.getBundleManifest().getVersion())) { //not a bundle type, just return getLog().info(newFile + " is not an OSGi bundle, skipping."); return; } BundleInfo oldBundle = getBundleInfo(resolve(oldArtifact)); String bundleSymbolicName = newBundle.getBundleManifest().getSymbolicName(); URLClassLoader oldClassLoader = new URLClassLoader(new URL[] {oldBundle.getBundle().toURI() .toURL()}); URLClassLoader newClassLoader = new URLClassLoader(new URL[] {newBundle.getBundle().toURI() .toURL()}); BundleCompatibility bundleCompatibility = new BundleCompatibility(bundleSymbolicName, newBundle, oldBundle, oldClassLoader, newClassLoader, excludes); bundleCompatibility.invoke(); String bundleElement = bundleCompatibility.getBundleElement(); String pkgElement = bundleCompatibility.getPkgElements().toString(); boolean failed = false; if ((bundleElement != null) && (bundleElement.trim().length() > 0)) { getLog().error(bundleElement + "\r\n"); failed = true; } if ((pkgElement != null) && (pkgElement.trim().length() > 0)) { getLog().error(pkgElement); failed = true; } if (writePackageinfos) { writePackageInfos(bundleCompatibility); } if (failed) { throw new RuntimeException("Semantic Versioning incorrect"); } else { getLog().info("All package or bundle versions are semanticly versioned correctly."); } } catch (MalformedURLException e) { throw new MojoExecutionException("Problem analyzing sources"); } catch (IOException e) { throw new MojoExecutionException("Problem analyzing sources"); } } } private void writePackageInfos(BundleCompatibility bundleCompatibility) { Map<String, VersionChange> packages = bundleCompatibility.getPackageChanges(); for (Map.Entry<String, VersionChange> packageChange : packages.entrySet()) { VersionChange versionChange = packageChange.getValue(); if (!versionChange.isCorrect()) { String packageName = packageChange.getKey(); String[] bits = packageName.split("\\."); File packageInfo = source; for (String bit : bits) { packageInfo = new File(packageInfo, bit); } packageInfo.mkdirs(); packageInfo = new File(packageInfo, "packageinfo"); try { FileWriter w = new FileWriter(packageInfo); try { w.append("# generated by Apache Aries semantic versioning tool\n"); w.append("version " + versionChange.getRecommendedNewVersion().toString() + "\n"); w.flush(); } finally { w.close(); } } catch (IOException e) { getLog().error("Could not write packageinfo for package " + packageName, e); } } } } private File resolve(String artifactDescriptor) { String[] s = artifactDescriptor.split(":"); String type = (s.length >= 4 ? s[3] : "jar"); Artifact artifact = repository.createArtifact(s[0], s[1], s[2], type); ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(artifact); request.setResolveRoot(true).setResolveTransitively(false); request.setServers( session.getRequest().getServers() ); request.setMirrors( session.getRequest().getMirrors() ); request.setProxies( session.getRequest().getProxies() ); request.setLocalRepository(session.getLocalRepository()); request.setRemoteRepositories(session.getRequest().getRemoteRepositories()); repository.resolve(request); return artifact.getFile(); } private BundleInfo getBundleInfo(File f) { BundleManifest bundleManifest = BundleManifest.fromBundle(f); return new BundleInfo(bundleManifest, f); } }
8,974
0
Create_ds/aries/versioning/versioning-plugin/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-plugin/src/main/java/org/apache/aries/versioning/mojo/CLVersionCheckerMojo.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.versioning.mojo; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; /** * Check semantic version changes between an explicitly named old artifact and the project output artifact. * Optionally write packageinfo files for wrong package versions. */ @Mojo(name = "check", defaultPhase = LifecyclePhase.PACKAGE, requiresDirectInvocation = true) public class CLVersionCheckerMojo extends VersionCheckerMojo { }
8,975
0
Create_ds/aries/versioning/versioning-checker/src/test/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/test/java/org/apache/aries/versioning/tests/SemanticVersionUtilsTest.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.versioning.tests; import static org.junit.Assert.assertEquals; import org.apache.aries.versioning.utils.SemanticVersioningUtils; import org.junit.Test; public class SemanticVersionUtilsTest { @Test public void testMethodTransform() { String returnStr = SemanticVersioningUtils.getReadableMethodSignature("getAccountNum", "(Ljava/lang/String;)Ljava/lang/String;"); String expectedStr = "method java.lang.String getAccountNum(java.lang.String)"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("handleNotification", "(Ljavax/management/Notification;Ljava/lang/Object;)V"); expectedStr = "method void handleNotification(javax.management.Notification, java.lang.Object)"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("addItemDeepCopy", "(Lcom/xml/xci/Cursor$Area;Lcom/xml/xci/Cursor;Lcom/xml/xci/Cursor$Profile;Lcom/xml/xci/Cursor$Profile;ZZZ)Lcom/xml/xci/Cursor;"); expectedStr = "method com.xml.xci.Cursor addItemDeepCopy(com.xml.xci.Cursor$Area, com.xml.xci.Cursor, com.xml.xci.Cursor$Profile, com.xml.xci.Cursor$Profile, boolean, boolean, boolean)"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("createParserAndCompiler", "(Ljavax/xml/transform/Source;Lcom/xltxe/rnm1/xtq/exec/XTQStaticContext;Lcom/xltxe/rnm1/xtq/common/utils/ErrorHandler;)Lcom/xltxe/rnm1/xtq/xquery/drivers/XQueryCompiler;"); expectedStr = "method com.xltxe.rnm1.xtq.xquery.drivers.XQueryCompiler createParserAndCompiler(javax.xml.transform.Source, com.xltxe.rnm1.xtq.exec.XTQStaticContext, com.xltxe.rnm1.xtq.common.utils.ErrorHandler)"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("getAxis", "()Lcom/xml/xci/exec/Axis;"); expectedStr = "method com.xml.xci.exec.Axis getAxis()"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("createEmpty", "()Lcom/xml/xci/dp/cache/dom/InternalNodeData;"); expectedStr = "method com.xml.xci.dp.cache.dom.InternalNodeData createEmpty()"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("addElement", "(Lorg/w3c/dom/Node;)V"); expectedStr = "method void addElement(org.w3c.dom.Node)"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("isExternalFunctionCall", "(Lcom/xltxe/rnm1/xtq/ast/nodes/FunctionCall;Lcom/xltxe/rnm1/xtq/xpath/drivers/XPathCompiler;)Z"); expectedStr = "method boolean isExternalFunctionCall(com.xltxe.rnm1.xtq.ast.nodes.FunctionCall, com.xltxe.rnm1.xtq.xpath.drivers.XPathCompiler)"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("wrapForTracing", "(Lcom/xltxe/rnm1/xtq/xslt/runtime/output/ResultTreeSequenceWriterStream$TraceOutputEventGenerator;Lcom/xml/xci/SessionContext;Lcom/xml/xci/Cursor;Lcom/xml/xci/RequestInfo;Lcom/xltxe/rnm1/xtq/xslt/runtime/output/ResultTreeSequenceWriterStream$DeferredTraceResultTreeSequenceWriterStream;)Lcom/xml/xci/Cursor;"); expectedStr = "method com.xml.xci.Cursor wrapForTracing(com.xltxe.rnm1.xtq.xslt.runtime.output.ResultTreeSequenceWriterStream$TraceOutputEventGenerator, com.xml.xci.SessionContext, com.xml.xci.Cursor, com.xml.xci.RequestInfo, com.xltxe.rnm1.xtq.xslt.runtime.output.ResultTreeSequenceWriterStream$DeferredTraceResultTreeSequenceWriterStream)"; assertEquals("The return str is incorrect.", expectedStr, returnStr); returnStr = SemanticVersioningUtils.getReadableMethodSignature("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/security/Key;Ljava/security/Key;Ljava/security/cert/Certificate;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IJJLjava/lang/String;)V"); expectedStr = "constructor with parameter list (java.lang.String, java.lang.String, java.lang.String, java.security.Key, java.security.Key, java.security.cert.Certificate, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, long, long, java.lang.String)"; assertEquals("The return str is incorrect.", expectedStr, returnStr); } }
8,976
0
Create_ds/aries/versioning/versioning-checker/src/test/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/test/java/org/apache/aries/versioning/tests/BinaryCompatibilityTest.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.versioning.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.objectweb.asm.Opcodes.ACC_ABSTRACT; import static org.objectweb.asm.Opcodes.ACC_FINAL; import static org.objectweb.asm.Opcodes.ACC_INTERFACE; import static org.objectweb.asm.Opcodes.ACC_NATIVE; import static org.objectweb.asm.Opcodes.ACC_PRIVATE; import static org.objectweb.asm.Opcodes.ACC_PROTECTED; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACC_STATIC; import static org.objectweb.asm.Opcodes.ACC_SYNCHRONIZED; import static org.objectweb.asm.Opcodes.ACC_TRANSIENT; import static org.objectweb.asm.Opcodes.V1_5; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import org.apache.aries.versioning.utils.BinaryCompatibilityStatus; import org.apache.aries.versioning.utils.MethodDeclaration; import org.apache.aries.versioning.utils.SemanticVersioningClassVisitor; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; /** * Test the jdk chap 13 -binary compatibility implementation * * @author emily */ public class BinaryCompatibilityTest { private static final int ACC_ABASTRACT = 0; private static URLClassLoader loader = null; @BeforeClass public static void setup() throws Exception { Collection<URL> urls = new HashSet<URL>(); urls.add(new File("unitest/").toURI().toURL()); loader = new URLClassLoader(urls.toArray(new URL[0])); } /** * Test of binary incompatibility where a class was not abstract is changed to be declared abstract, */ @Test public void test_jdk_chap13_4_1_1() { // construct original class ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "When a class is changed from non abstract to abstract, this should break binary compatibility.", bcs.size() == 1); assertEquals(" The class pkg/Test was not abstract but is changed to be abstract.", bcs.get(0)); } /** * Test of binary compatibility where a class was abstract is changed to be declared non-abstract, */ @Test public void test_jdk_chap13_4_1_2() { // construct original class ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "When a class is changed from static to non-static, this should not break binary compatibility.", bcs.isCompatible()); } /** * Test a binary incompatibility where a class was not final is changed to be final. */ @Test public void test_jdk_chap13_4_2_1() { // construct original class ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_FINAL, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "When a class is changed from non final to final, this should break binary compatibility.", bcs.size() == 1); assertEquals(" The class pkg/Test was not final but is changed to be final.", bcs.get(0)); } /** * Test a binary compatibility where a class was final is changed to not final. */ @Test public void test_jdk_chap13_4_2_2() { // construct original class ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_FINAL, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "When a class is changed from final to not final, this should not break binary compatibility.", bcs.isCompatible()); } /** * Test a binary incompatibility where a class was public is changed to not public. */ @Test public void test_jdk_chap13_4_3_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_FINAL, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_FINAL, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertNull( "When a class is changed from public to non-public, this should break binary compatibility.", newCV.getClassDeclaration()); } /** * Test a binary incompatibility where a class was not public is changed to public. */ @Test public void test_jdk_chap13_4_3_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_FINAL, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_FINAL, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "When a class is changed from non-public to public, this should break binary compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Changing the direct superclass or the set of direct superinterfaces of a class type will not break compatibility * with pre-existing binaries, provided that the total set of superclasses or superinterfaces, respectively, of the class type loses no members. */ @Test public void test_jdk_chap13_4_4_1() throws IOException { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestBChild", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Changing the direct superclass or the set of direct superinterfaces of a class type will not breake binary compatibility if not losing any members.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Changing field type breaks binary compatibility * with pre-existing binaries, provided that the total set of superclasses or superinterfaces, respectively, of the class type loses no members but the one of the fields has changed type. */ @Test public void test_jdk_chap13_4_7_4() throws IOException { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "Changing the direct superclass or the set of direct superinterfaces of a class type results fields changes. This should breake binary compatibility if not losing any members.", bcs.size() == 2); assertEquals(new HashSet<String>(Arrays.asList(new String[] {"The public field bar was static but is changed to be non static or vice versa.", "The public field bar has changed its type."})), new HashSet<String>(bcs)); } /** * Change the signature of the field from Colllection<AA> to Collection<String> */ @Test public void test_jdk_chap13_4_7_5() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitField(ACC_PUBLIC, "more", "Ljava/util/Collection;", "Lcom/bim/AA;", null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitField(ACC_PROTECTED, "more", "Ljava/util/Collection;", "Ljava/lang/String;", null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals(new HashSet<String>(Arrays.asList(new String[] { "The public field more becomes less accessible."})), new HashSet<String>(bcs)); assertTrue( "Changing the declared access of a field to permit less access , this should break binary compatibility.", bcs.size() == 1); } /** * If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, it will break binary compatibility. */ @Test public void test_jdk_chap13_4_4_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertFalse( "If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, it will break binary compatibility.", bcs.isCompatible()); assertEquals(new HashSet<String>(Arrays.asList(new String[] {"The method int getFooLen(java.lang.String) has been deleted or its return type or parameter list has changed.", "The method java.lang.String getFoo() has changed from non abstract to abstract.", "The method int getBarLen(java.lang.String) has been deleted or its return type or parameter list has changed.", "The method int getBooLen(java.lang.String) has been deleted or its return type or parameter list has changed.", "The superclasses or superinterfaces have stopped being super: [versioning/java/files/TestC, versioning/java/files/TestA].", "The protected field c has been deleted.", "The public field bar was not final but has been changed to be final.", "The public field bar was static but is changed to be non static or vice versa.", "The public field bar has changed its type."})), new HashSet<String>(bcs)); } /** * Test deleting a class member or constructor that is not declared private/default breaks binary compatibility. */ @Test public void test_jdk_chap13_4_5_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitMethod(ACC_PROTECTED + ACC_ABSTRACT, "convert", "(Ljava/lang/Object;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int convert(java.lang.Object) has been deleted or its return type or parameter list has changed.", bcs.get(0)); assertTrue( "deleting a class member or constructor that is not declared private breaks binary compatibility.", bcs.size() == 1); } /** * Test deleting a class member or constructor that is declared private should not break binary compatibility. */ @Test public void test_jdk_chap13_4_5_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitMethod(ACC_PRIVATE, "convert", "(Ljava/lang/Object;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Deleting a class member or constructor that is declared private should not break binary compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Test adding a class member or constructor should not break binary compatibility. */ @Test public void test_jdk_chap13_4_5_3() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitMethod(ACC_PROTECTED, "convert", "(Ljava/lang/Object;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Adding a class member or constructor should not break binary compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Test changing the declared access of a method to permit less access, this should break compatibility. */ @Test public void test_jdk_chap13_4_6_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "convert", "(Ljava/lang/Object;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitMethod(ACC_STATIC, "convert", "(Ljava/lang/Object;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int convert(java.lang.Object) is less accessible.", bcs.get(0)); assertTrue( "Changing the declared access of a member or contructor to permit less access , this should break binary compatibility.", bcs.size() == 1); } @Test public void test_jdk_chap13_4_6_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitField(ACC_PUBLIC, "lESS", "I", null, new Integer(-1)).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitField(ACC_PROTECTED, "lESS", "I", null, new Integer(-1)).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The public field lESS becomes less accessible.", bcs.get(0)); assertTrue( "Changing the declared access of a field to permit less access , this should break binary compatibility.", bcs.size() == 1); } /** * Test deleting a private/default field, this should not break compatibility. */ @Test public void test_jdk_chap13_4_7_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitField(ACC_PRIVATE, "lESS", "I", null, new Integer(-1)).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", null); cw.visitMethod(ACC_PROTECTED, "convert", "(Ljava/lang/Object;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Deleting a private field should not break binary compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * If a field is added but is less accessible than the old one or change to static from non-static or from non-static to static. */ @Test public void test_jdk_chap13_4_7_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PROTECTED, "bar", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The public field bar becomes less accessible.", bcs.get(0)); assertTrue( "The new field conflicts with a field in the super class. Check chapter 13.4.7 java spec for more info.", bcs.size() == 1); } /** * If a field was not final is changed to be final, then it can break compatibility. */ @Test public void test_jdk_chap13_4_8_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_FINAL, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The public field aa was not final but has been changed to be final.", bcs.get(0)); assertTrue( "Change that a public or protected field was final but is changed to be not final will break binary compatibility.", bcs.size() == 1); } /** * If a field was final is changed to be non-final, then it does not break compatibility. */ @Test public void test_jdk_chap13_4_8_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_FINAL, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, it will break binary compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * If a field was static is changed to be non-static, then it will break compatibility. */ @Test public void test_jdk_chap13_4_9_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_STATIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The public field aa was static but is changed to be non static or vice versa.", bcs.get(0)); assertTrue( "If a field was static is changed to be non-static, then it will break compatibility.", bcs.size() == 1); } /** * If a field was non-static is changed to be static, then it will break compatibility. */ @Test public void test_jdk_chap13_4_9_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_STATIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The public field aa was static but is changed to be non static or vice versa.", bcs.get(0)); assertTrue( "If a field was non-static is changed to be static, then it will break compatibility.", bcs.size() == 1); } /** * If a field was transient is changed to non-transient, then it will not break compatibility. */ @Test public void test_jdk_chap13_4_10_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, it will break binary compatibility.", bcs.isCompatible()); } /** * If a field was non-transient is changed to transient, then it will not break compatibility. */ @Test public void test_jdk_chap13_4_10_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, it will break binary compatibility.", bcs.isCompatible()); } /** * Testing deleting a public/protected method when there is no such a method in the superclass breaks binary compatibility. */ @Test public void test_jdk_chap13_4_11_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getFooLen", "(Ljava/lang/STring;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getFooLen(java.lang.STring) has been deleted or its return type or parameter list has changed.", bcs.get(0)); assertTrue( "Deleting a public/protected method when there is no such a method in the superclass breaks binary compatibility.", bcs.size() == 1); } /** * Testing deleting a public/protected method when there is such a method in the superclass does not break binary compatibility. */ @Test public void test_jdk_chap13_4_11_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getBarLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, it will break binary compatibility.", bcs.isCompatible()); } /** * Testing deleting a public/protected method when there is less accessible method in the superclass does break binary compatibility. */ @Test public void test_jdk_chap13_4_11_3() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getFooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getFooLen(java.lang.String) is less accessible.", bcs.get(0)); assertTrue( "If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, it will break binary compatibility.", bcs.size() == 1); } /** * Adding a parameter is a binary compatibility change. */ @Test public void test_jdk_chap13_4_12_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;I)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getCooLen(java.lang.String) has been deleted or its return type or parameter list has changed.", bcs.get(0)); assertTrue( "Changing a parameter list will break binary compatibility.", bcs.size() == 1); } /** * Changing a method parameter type is a binary compatibility change. */ @Test public void test_jdk_chap13_4_12_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/Object;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getCooLen(java.lang.String) has been deleted or its return type or parameter list has changed.", bcs.get(0)); assertTrue( "Changing a method paramether type will break binary compatibility.", bcs.size() == 1); } /** * Changing a method formal type parameter is not a binary compatibility change. */ @Test public void test_jdk_chap13_4_12_3() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/util/List;)I", "Ljava/lang/String;", null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/util/List;)I", "Lcome/ibm/blah;", null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "Changing a method formal type parameter should not break binary compatibility.", bcs.isCompatible()); } /** * Changing a method return type is a binary compatibility change. */ @Test public void test_jdk_chap13_4_13_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)[I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getCooLen(java.lang.String) has been deleted or its return type or parameter list has changed.", bcs.get(0)); assertTrue( "Changing a method return type will break binary compatibility.", bcs.size() == 1); } /** * Changing a method to be abstract is a binary compatibility change. */ @Test public void test_jdk_chap13_4_14_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getCooLen(java.lang.String) has changed from non abstract to abstract.", bcs.get(0)); assertTrue( "Changing a method to be abstract will break binary compatibility.", bcs.size() == 1); } /** * Changing a method to not to be abstract is not a binary compatibility change. */ @Test public void test_jdk_chap13_4_14_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC + ACC_ABASTRACT, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Changing a method not to be abstract will not break binary compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Changing an instance method that is not final to be final is a binary compatibility change. */ @Test public void test_jdk_chap13_4_15_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getCooLen(java.lang.String) was not final but has been changed to be final.", bcs.get(0)); assertTrue( "Changing an instance method from non-final to final will break binary compatibility.", bcs.size() == 1); } /** * Changing an instance method that is final to be non-final is a binary compatibility change. */ @Test public void test_jdk_chap13_4_15_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Changing an instance method from final to non-final will not break binary compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Changing a static method that is not final to final is not a binary compatibility change. */ @Test public void test_jdk_chap13_4_15_3() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Changing a static method from non-final to final will not break binary compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Adding a native modifier of a method does not break compatibility. */ @Test public void test_jdk_chap13_4_16_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC + ACC_STATIC + ACC_NATIVE, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Adding a native modifier of a method does not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Deleting a native modifier of a method does not break compatibility. */ @Test public void test_jdk_chap13_4_16_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC + ACC_NATIVE, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Adding a native modifier of a method does not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * If a method is not private was not declared static and is changed to be declared static, this breaks compatibility. */ @Test public void test_jdk_chap13_4_17_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getCooLen(java.lang.String) has changed from static to non-static or vice versa.", bcs.get(0)); assertTrue( "If a method is not private was not declared static and is changed to be decalared static, this should break compatibility.", bcs.size() == 1); } /** * If a method is not private was declared static and is changed to not be declared static, this breaks compatibility. */ @Test public void test_jdk_chap13_4_17_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getCooLen(java.lang.String) has changed from static to non-static or vice versa.", bcs.get(0)); assertTrue( "If a method is not private was declared static and is changed to not be decalared static, this should break compatibility.", bcs.size() == 1); } /** * If a method is private was declared static and is changed to not be declared static, this does not break compatibility. */ @Test public void test_jdk_chap13_4_17_3() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PRIVATE + ACC_STATIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC + ACC_TRANSIENT, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PRIVATE, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertTrue( "If a method is private was declared static and is changed to not be decalared static, this should not break compatibility.", bcs.isCompatible()); } /** * Adding a synchronized modifier of a method does not break compatibility. */ @Test public void test_jdk_chap13_4_18_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC + ACC_SYNCHRONIZED, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Adding a synchronized modifier of a method does not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Deleting a synchronized modifier of a method does not break compatibility. */ @Test public void test_jdk_chap13_4_18_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitMethod(ACC_PUBLIC + ACC_SYNCHRONIZED, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "versioning/java/files/TestA", null); cw.visitField(ACC_PUBLIC, "aa", "Ljava/lang/String;", null, new String("newBar")).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getCooLen", "(Ljava/lang/String;)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Adding a synchronized modifier of a method does not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Changing an interface that is not declared public to be declared public does not break compatibility. */ @Test public void test_jdk_chap13_5_1_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Changing an interface that is not declared public to be declared public should not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())).isCompatible()); } /** * Changing an interface that is declared public to not be declared public should break compatibility. */ @Test public void test_jdk_chap13_5_1_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertNull( "Changing an interface that is declared public to not be declared public should break compatibility.", newCV.getClassDeclaration()); } /** * Changes to the interface hierarchy resulting an interface not being a super interface should break compatibility. */ @Test public void test_jdk_chap13_5_2_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", null); cw.visitMethod(ACC_PUBLIC, "getFoo", "I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals(new HashSet<String>(Arrays.asList(new String[] {"The public field bar has been deleted.", "The superclasses or superinterfaces have stopped being super: [versioning/java/files/TestB].", "The method java.lang.String getFoo() has been deleted or its return type or parameter list has changed."})), new HashSet<String>(bcs)); assertFalse( "Changes to the interface hierarchy resulting an interface not being a super interface should break compatibility.", bcs.isCompatible()); } /** * Deleting a method in an interface should break compatibility. */ @Test public void test_jdk_chap13_5_3_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC, "getFoo", "()I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getFoo() has been deleted or its return type or parameter list has changed.", bcs.get(0)); assertTrue( "Deleting a method in an interface should break compatibility.", bcs.size() == 1); } /** * Adding a method in an interface should not break compatibility. */ @Test public void test_jdk_chap13_5_3_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC, "getFoo", "()I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC, "getFoo", "()I", null, null).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getMoo", "()I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Adding a method in an interface should not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus(oldCV.getClassDeclaration()).isCompatible()); } /** * Changing a method return type in an interface should break compatibility. */ @Test public void test_jdk_chap13_5_5_1() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC, "getFoo", "()I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC, "getFoo", "(I)I", null, null).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getMoo", "()I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getFoo() has been deleted or its return type or parameter list has changed.", bcs.get(0)); assertTrue( "Changing a method return type in an interface should break compatibility.", bcs.size() == 1); } /** * Changing a method parameter in an interface should break compatibility. */ @Test public void test_jdk_chap13_5_5_2() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC, "getFoo", "(I)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC, "getFoo", "(IZ)I", null, null).visitEnd(); cw.visitMethod(ACC_PUBLIC, "getMoo", "I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); BinaryCompatibilityStatus bcs = newCV.getClassDeclaration().getBinaryCompatibleStatus((oldCV.getClassDeclaration())); assertEquals("The method int getFoo(int) has been deleted or its return type or parameter list has changed.", bcs.get(0)); assertTrue( "Changing a method parameter in an interface should break compatibility.", bcs.size() == 1); } /** * Check containing more abstract methods */ @Test public void test_containing_more_abstract_methods() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "getFoo", "(I)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "getFoo", "(I)I", null, null).visitEnd(); cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "getMoo", "()I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "Adding an abstract methods should not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus(oldCV.getClassDeclaration()).isCompatible()); Collection<MethodDeclaration> extraMethods = newCV.getClassDeclaration().getExtraMethods(oldCV.getClassDeclaration()); assertEquals(1, extraMethods.size()); for (MethodDeclaration md : extraMethods) { assertEquals( "getMoo", md.getName()); } } /** * Check not containing more abstract methods */ @Test public void test_not_cotaining_more_abstract_methods() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "getFoo", "(I)I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "getFoo", "(I)I", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "No change should not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus(oldCV.getClassDeclaration()).isCompatible()); assertEquals( "Containing more abstract methods should return false.", 0, newCV.getClassDeclaration().getExtraMethods(oldCV.getClassDeclaration()).size()); } @Test public void test_ignore_clinit() { ClassWriter cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitField(ACC_PUBLIC, "foo", "I", null, null).visitEnd(); cw.visitEnd(); byte[] oldBytes = cw.toByteArray(); cw = new ClassWriter(0); cw.visit(V1_5, ACC_PUBLIC, "pkg/Test", null, "java/lang/Object", new String[]{"versioning/java/files/TestB"}); cw.visitField(ACC_PUBLIC + ACC_STATIC, "bar", "I", null, null).visitEnd(); cw.visitField(ACC_PUBLIC, "foo", "I", null, null).visitEnd(); cw.visitMethod(ACC_PUBLIC, "<clinit>", "()V", null, null).visitEnd(); cw.visitEnd(); byte[] newBytes = cw.toByteArray(); SemanticVersioningClassVisitor oldCV = new SemanticVersioningClassVisitor(loader); SemanticVersioningClassVisitor newCV = new SemanticVersioningClassVisitor(loader); ClassReader newCR = new ClassReader(newBytes); ClassReader oldCR = new ClassReader(oldBytes); newCR.accept(newCV, 0); oldCR.accept(oldCV, 0); assertTrue( "No change should not break compatibility.", newCV.getClassDeclaration().getBinaryCompatibleStatus(oldCV.getClassDeclaration()).isCompatible()); assertEquals( "Containing more abstract methods should return false.", 0, newCV.getClassDeclaration().getExtraMethods(oldCV.getClassDeclaration()).size()); } }
8,977
0
Create_ds/aries/versioning/versioning-checker/src/test/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/test/java/org/apache/aries/versioning/tests/FilterResultsTest.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.versioning.tests; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import org.apache.aries.util.manifest.BundleManifest; import org.apache.aries.versioning.check.BundleCompatibility; import org.apache.aries.versioning.check.BundleInfo; import org.junit.Test; /** * Test that results can be excluded. */ public class FilterResultsTest { /** * Test an error is excluded when required. This test uses two bundles each containing the same * class, where the later versioned class has had a method removed. */ @Test public void testApiMethodErrorExcluded() { try { File oldBundleFile = new File("../src/test/resources/api_1.0.0.jar"); BundleInfo oldBundle = new BundleInfo(BundleManifest.fromBundle(oldBundleFile), oldBundleFile); File newBundleFile = new File("../src/test/resources/api_1.0.1.jar"); BundleInfo newBundle = new BundleInfo(BundleManifest.fromBundle(newBundleFile), newBundleFile); String bundleSymbolicName = newBundle.getBundleManifest().getSymbolicName(); URLClassLoader oldClassLoader = new URLClassLoader(new URL[] {oldBundle.getBundle().toURI() .toURL()}); URLClassLoader newClassLoader = new URLClassLoader(new URL[] {newBundle.getBundle().toURI() .toURL()}); List<String> excludes = new ArrayList<String>(); excludes.add("method void methodToBeExcludedFrom() has been deleted"); BundleCompatibility bundleCompatibility = new BundleCompatibility(bundleSymbolicName, newBundle, oldBundle, oldClassLoader, newClassLoader, excludes); bundleCompatibility.invoke(); String bundleElement = bundleCompatibility.getBundleElement(); String pkgElement = bundleCompatibility.getPkgElements().toString(); assertTrue("Unexpected bundle versioning issue", bundleElement==null); assertTrue("Unexpected package versioning issue", pkgElement.trim().length() == 0); } catch (IOException e) { fail("Unexpected IOException " + e); } } }
8,978
0
Create_ds/aries/versioning/versioning-checker/src/test/java/versioning/java
Create_ds/aries/versioning/versioning-checker/src/test/java/versioning/java/files/TestBChild.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 versioning.java.files; public interface TestBChild extends TestB { public String getBar(); }
8,979
0
Create_ds/aries/versioning/versioning-checker/src/test/java/versioning/java
Create_ds/aries/versioning/versioning-checker/src/test/java/versioning/java/files/TestB.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 versioning.java.files; public interface TestB { int bar = 2; public String getFoo(); }
8,980
0
Create_ds/aries/versioning/versioning-checker/src/test/java/versioning/java
Create_ds/aries/versioning/versioning-checker/src/test/java/versioning/java/files/TestC.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 versioning.java.files; public class TestC { protected int c = 1; protected int getFooLen(String foo) { return foo.length(); } public int getBooLen(String boo) { return boo.length(); } }
8,981
0
Create_ds/aries/versioning/versioning-checker/src/test/java/versioning/java
Create_ds/aries/versioning/versioning-checker/src/test/java/versioning/java/files/TestA.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 versioning.java.files; public class TestA extends TestC implements TestB { public String bar = "bar"; protected static int c = 2; public String getFoo() { return String.valueOf(bar); } public int getBarLen(String bar) { return bar.length(); } }
8,982
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/utils/MethodDeclaration.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.versioning.utils; import java.lang.reflect.Modifier; public class MethodDeclaration extends GenericDeclaration { private final String desc; MethodDeclaration(int access, String name, String desc, String signature, String[] exceptions) { super(access, name, signature); this.desc = desc; } public String getDesc() { return desc; } public boolean isAbstract() { return Modifier.isAbstract(getAccess()); } @Override public int hashCode() { final int prime = 31; //int result = super.hashCode(); int result = prime + ((desc == null) ? 0 : desc.hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; //if (getClass() != obj.getClass()) return false; MethodDeclaration other = (MethodDeclaration) obj; if (desc == null) { if (other.desc != null) return false; } else if (!desc.equals(other.desc)) return false; if (getName() == null) { if (other.getName() != null) return false; } else if (!getName().equals(other.getName())) return false; return true; } }
8,983
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/utils/FieldDeclaration.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.versioning.utils; public class FieldDeclaration extends GenericDeclaration { private final String desc; private final Object value; FieldDeclaration(int access, String name, String desc, String signature, Object value) { super(access, name, signature); this.desc = desc; this.value = value; } public String getDesc() { return desc; } public Object getValue() { return value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (getClass() != obj.getClass()) return false; FieldDeclaration other = (FieldDeclaration) obj; if (getName() == null) { if (other.getName() != null) return false; } else if (!getName().equals(other.getName())) return false; return true; } }
8,984
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/utils/SerialVersionClassVisitor.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.versioning.utils; import java.io.IOException; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.commons.SerialVersionUIDAdder; public class SerialVersionClassVisitor extends SerialVersionUIDAdder { public SerialVersionClassVisitor(ClassVisitor cv) { super(Opcodes.ASM5, cv); } public long getComputeSerialVersionUID() { try { return computeSVUID(); } catch (IOException ioe) { // not a issue } return 0; } }
8,985
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/utils/BinaryCompatibilityStatus.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.versioning.utils; import java.util.ArrayList; public class BinaryCompatibilityStatus extends ArrayList<String> { public BinaryCompatibilityStatus() { } public boolean isCompatible() { return isEmpty(); } }
8,986
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/utils/GenericDeclaration.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.versioning.utils; import java.lang.reflect.Modifier; import org.objectweb.asm.Opcodes; public abstract class GenericDeclaration { private final int access; private final String name; private final String signature; public GenericDeclaration(int access, String name, String signature) { int updatedAccess = access; // ignore the native or synchronized modifier as they do not affect binary compatibility if (Modifier.isNative(access)) { updatedAccess = updatedAccess - Opcodes.ACC_NATIVE; } if (Modifier.isSynchronized(access)) { updatedAccess = updatedAccess - Opcodes.ACC_SYNCHRONIZED; } this.access = access; this.name = name; this.signature = signature; } public int getAccess() { return access; } public String getName() { return name; } public String getSignature() { return signature; } public boolean isFinal() { return Modifier.isFinal(access); } public boolean isStatic() { return Modifier.isStatic(access); } public boolean isPublic() { return Modifier.isPublic(access); } public boolean isProtected() { return Modifier.isProtected(access); } public boolean isPrivate() { return Modifier.isPrivate(access); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + access; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GenericDeclaration other = (GenericDeclaration) obj; if (access != other.access) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
8,987
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/utils/ClassDeclaration.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.versioning.utils; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Type; public class ClassDeclaration extends GenericDeclaration { // Binary Compatibility - deletion of package-level access field/method/constructors of classes and interfaces in the package // will not break binary compatibility when an entire package is updated. // Assumptions: // 1. This tool assumes that the deletion of package-level fields/methods/constructors is not break binary compatibility // based on the assumption of the entire package is updated. // private final String superName; private final String[] interfaces; private final Map<String, FieldDeclaration> fields; private final Map<String, Set<MethodDeclaration>> methods; private final Map<String, Set<MethodDeclaration>> methodsInUpperChain = new HashMap<String, Set<MethodDeclaration>>(); private final Map<String, FieldDeclaration> fieldsInUpperChain = new HashMap<String, FieldDeclaration>(); private final Collection<String> supers = new ArrayList<String>(); private final URLClassLoader jarsLoader; private final SerialVersionClassVisitor serialVisitor; public Map<String, FieldDeclaration> getFields() { return fields; } public Map<String, FieldDeclaration> getAllFields() { Map<String, FieldDeclaration> allFields = new HashMap<String, FieldDeclaration>(getFields()); Map<String, FieldDeclaration> fieldsFromSupers = getFieldsInUpperChain(); putIfAbsent(allFields, fieldsFromSupers); return allFields; } private void putIfAbsent(Map<String, FieldDeclaration> allFields, Map<String, FieldDeclaration> fieldsFromSupers) { for (Map.Entry<String, FieldDeclaration> superFieldEntry : fieldsFromSupers.entrySet()) { String fieldName = superFieldEntry.getKey(); FieldDeclaration fd = superFieldEntry.getValue(); if (allFields.get(fieldName) == null) { allFields.put(fieldName, fd); } } } /** * Get the methods in the current class plus the methods in the upper chain * * @return map of method name to set of method declarations */ public Map<String, Set<MethodDeclaration>> getAllMethods() { Map<String, Set<MethodDeclaration>> methods = new HashMap<String, Set<MethodDeclaration>>(getMethods()); Map<String, Set<MethodDeclaration>> methodsFromSupers = getMethodsInUpperChain(); for (Map.Entry<String, Set<MethodDeclaration>> superMethodsEntry : methodsFromSupers.entrySet()) { Set<MethodDeclaration> overloadingMethods = methods.get(superMethodsEntry.getKey()); if (overloadingMethods != null) { overloadingMethods.addAll(superMethodsEntry.getValue()); } else { methods.put(superMethodsEntry.getKey(), superMethodsEntry.getValue()); } } return methods; } public Map<String, Set<MethodDeclaration>> getMethods() { return methods; } // public ClassDeclaration(int access, String name, String signature, String superName, // String[] interfaces, URLClassLoader loader) { // super(access, name, signature); // this.superName = superName; // this.interfaces = interfaces; // this.fields = new HashMap<String, FieldDeclaration>(); // this.methods = new HashMap<String, Set<MethodDeclaration>>(); // this.jarsLoader = loader; // this.serialVisitor = null; // } public ClassDeclaration(int access, String name, String signature, String superName, String[] interfaces, URLClassLoader loader, SerialVersionClassVisitor cv) { super(access, name, signature); this.superName = superName; this.interfaces = interfaces; this.fields = new HashMap<String, FieldDeclaration>(); this.methods = new HashMap<String, Set<MethodDeclaration>>(); this.jarsLoader = loader; this.serialVisitor = cv; } private void getFieldsRecursively(String superClass) { if ((superClass != null)) { // load the super class of the cd try { SerialVersionClassVisitor cv = new SerialVersionClassVisitor(null); SemanticVersioningClassVisitor svc = new SemanticVersioningClassVisitor(jarsLoader, cv); ClassReader cr = new ClassReader(jarsLoader.getResourceAsStream(superClass + SemanticVersioningUtils.classExt)); cr.accept(svc, 0); ClassDeclaration cd = svc.getClassDeclaration(); if (cd != null) { addFieldInUpperChain(cd.getFields()); getFieldsRecursively(cd.getSuperName()); for (String iface : cd.getInterfaces()) { getFieldsRecursively(iface); } } } catch (IOException ioe) { // not a problem } } } private void getMethodsRecursively(String superClass) { if ((superClass != null)) { // load the super class of the cd SerialVersionClassVisitor cv = new SerialVersionClassVisitor(null); SemanticVersioningClassVisitor svc = new SemanticVersioningClassVisitor(jarsLoader, cv); // use URLClassLoader to load the class try { ClassReader cr = new ClassReader(jarsLoader.getResourceAsStream(superClass + SemanticVersioningUtils.classExt)); cr.accept(svc, 0); ClassDeclaration cd = svc.getClassDeclaration(); if (cd != null) { addMethodsInUpperChain(cd.getMethods()); getMethodsRecursively(cd.getSuperName()); for (String iface : cd.getInterfaces()) { getMethodsRecursively(iface); } } } catch (IOException ioe) { // not a deal } } } public Map<String, FieldDeclaration> getFieldsInUpperChain() { if (fieldsInUpperChain.isEmpty()) { getFieldsRecursively(getSuperName()); for (String ifs : getInterfaces()) { getFieldsRecursively(ifs); } } return fieldsInUpperChain; } private void addFieldInUpperChain(Map<String, FieldDeclaration> fields) { putIfAbsent(fieldsInUpperChain, fields); } public Map<String, Set<MethodDeclaration>> getMethodsInUpperChain() { if (methodsInUpperChain.isEmpty()) { getMethodsRecursively(getSuperName()); for (String ifs : getInterfaces()) { getMethodsRecursively(ifs); } } return methodsInUpperChain; } private void addMethodsInUpperChain(Map<String, Set<MethodDeclaration>> methods) { for (Map.Entry<String, Set<MethodDeclaration>> method : methods.entrySet()) { String methodName = method.getKey(); Set<MethodDeclaration> mds = new HashSet<MethodDeclaration>(); if (methodsInUpperChain.get(methodName) != null) { mds.addAll(methodsInUpperChain.get(methodName)); } mds.addAll(method.getValue()); methodsInUpperChain.put(methodName, mds); } } public Collection<String> getUpperChainRecursively(String className) { Collection<String> clazz = new HashSet<String>(); if (className != null) { // load the super class of the cd SerialVersionClassVisitor cv = new SerialVersionClassVisitor(null); SemanticVersioningClassVisitor svc = new SemanticVersioningClassVisitor(jarsLoader, cv); try { ClassReader cr = new ClassReader(jarsLoader.getResourceAsStream(className + SemanticVersioningUtils.classExt)); cr.accept(svc, 0); clazz.add(className); if (svc.getClassDeclaration() != null) { String superName = svc.getClassDeclaration().getSuperName(); clazz.addAll(getUpperChainRecursively(superName)); if (svc.getClassDeclaration().getInterfaces() != null) { for (String iface : svc.getClassDeclaration().getInterfaces()) { clazz.addAll(getUpperChainRecursively(iface)); } } } } catch (IOException ioe) { // not to worry about this. terminate. } } return clazz; } public Collection<String> getAllSupers() { if (supers.isEmpty()) { supers.addAll(getUpperChainRecursively(getSuperName())); for (String iface : getInterfaces()) { supers.addAll(getUpperChainRecursively(iface)); } } return supers; } public String getSuperName() { return superName; } public String[] getInterfaces() { return interfaces; } public void addFields(FieldDeclaration fd) { fields.put(fd.getName(), fd); } public void addMethods(MethodDeclaration md) { String key = md.getName(); Set<MethodDeclaration> overloaddingMethods = methods.get(key); if (overloaddingMethods != null) { overloaddingMethods.add(md); methods.put(key, overloaddingMethods); } else { Set<MethodDeclaration> mds = new HashSet<MethodDeclaration>(); mds.add(md); methods.put(key, mds); } } public BinaryCompatibilityStatus getBinaryCompatibleStatus(ClassDeclaration old) { // check class signature, fields, methods BinaryCompatibilityStatus reasons = new BinaryCompatibilityStatus(); if (old == null) { return reasons; } getClassSignatureBinaryCompatibleStatus(old, reasons); getAllMethodsBinaryCompatibleStatus(old, reasons); getAllFieldsBinaryCompatibleStatus(old, reasons); getAllSuperPresentStatus(old, reasons); getSerializableBackCompatable(old, reasons); return reasons; } public boolean isAbstract() { return Modifier.isAbstract(getAccess()); } private void getClassSignatureBinaryCompatibleStatus(ClassDeclaration originalClass, List<String> reasons) { // if a class was not abstract but changed to abstract // not final changed to final // public changed to non-public String prefix = " The class " + getName(); if (!!!originalClass.isAbstract() && isAbstract()) { reasons.add(prefix + " was not abstract but is changed to be abstract."); } if (!!!originalClass.isFinal() && isFinal()) { reasons.add(prefix + " was not final but is changed to be final."); } if (originalClass.isPublic() && !!!isPublic()) { reasons.add(prefix + " was public but is changed to be non-public."); } } private void getAllFieldsBinaryCompatibleStatus(ClassDeclaration originalClass, List<String> reasons) { // for each field to see whether the same field has changed // not final -> final // static <-> nonstatic Map<String, FieldDeclaration> oldFields = originalClass.getAllFields(); Map<String, FieldDeclaration> newFields = getAllFields(); areFieldsBinaryCompatible(oldFields, newFields, reasons); } private void areFieldsBinaryCompatible(Map<String, FieldDeclaration> oldFields, Map<String, FieldDeclaration> currentFields, List<String> reasons) { for (Map.Entry<String, FieldDeclaration> entry : oldFields.entrySet()) { FieldDeclaration bef_fd = entry.getValue(); FieldDeclaration cur_fd = currentFields.get(entry.getKey()); isFieldBinaryCompatible(reasons, bef_fd, cur_fd); } } private boolean isFieldBinaryCompatible(List<String> reasons, FieldDeclaration bef_fd, FieldDeclaration cur_fd) { String fieldName = bef_fd.getName(); //only interested in the public or protected fields boolean compatible = true; if (bef_fd.isPublic() || bef_fd.isProtected()) { String prefix = "The " + (bef_fd.isPublic() ? "public" : "protected") + " field " + fieldName; if (cur_fd == null) { reasons.add(prefix + " has been deleted."); compatible = false; } else { if ((!!!bef_fd.isFinal()) && (cur_fd.isFinal())) { // make sure it has not been changed to final reasons.add(prefix + " was not final but has been changed to be final."); compatible = false; } if (bef_fd.isStatic() != cur_fd.isStatic()) { // make sure it the static signature has not been changed reasons.add(prefix + " was static but is changed to be non static or vice versa."); compatible = false; } // check to see the field type is the same if (!isFieldTypeSame(bef_fd, cur_fd)) { reasons.add(prefix + " has changed its type."); compatible = false; } if (SemanticVersioningUtils.isLessAccessible(bef_fd, cur_fd)) { // check whether the new field is less accessible than the old one reasons.add(prefix + " becomes less accessible."); compatible = false; } } } return compatible; } /** * Return whether the serializable class is binary compatible. The serial verison uid change breaks binary compatibility. * * * @param old Old class declaration * @param reasons list of binary compatibility problems */ private void getSerializableBackCompatable(ClassDeclaration old, List<String> reasons) { // It does not matter one of them is not serializable. if ((getAllSupers().contains(SemanticVersioningUtils.SERIALIZABLE_CLASS_IDENTIFIER)) && (old.getAllSupers().contains(SemanticVersioningUtils.SERIALIZABLE_CLASS_IDENTIFIER))) { // check to see whether the serializable id is the same //ignore if it is enum if ((!getAllSupers().contains(SemanticVersioningUtils.ENUM_CLASS) && (!old.getAllSupers().contains(SemanticVersioningUtils.ENUM_CLASS)))) { long oldValue = getSerialVersionUID(old); long curValue = getSerialVersionUID(this); if ((oldValue != curValue)) { reasons.add("The serializable class is no longer back compatible as the value of SerialVersionUID has changed from " + oldValue + " to " + curValue + "."); } } } } private long getSerialVersionUID(ClassDeclaration cd) { FieldDeclaration serialID = cd.getAllFields().get(SemanticVersioningUtils.SERIAL_VERSION_UTD); if (serialID != null) { if (serialID.isFinal() && serialID.isStatic() && Type.LONG_TYPE.equals(Type.getType(serialID.getDesc()))) { if (serialID.getValue() != null) { return (Long)serialID.getValue(); } else { return 0; } } } // get the generated value return cd.getSerialVisitor().getComputeSerialVersionUID(); } private boolean isFieldTypeSame(FieldDeclaration bef_fd, FieldDeclaration cur_fd) { boolean descSame = bef_fd.getDesc().equals(cur_fd.getDesc()); if (descSame) { return true; } return false; } private void getAllMethodsBinaryCompatibleStatus(ClassDeclaration originalClass, List<String> reasons) { // for all methods // no methods should have deleted // method return type has not changed // method changed from not abstract -> abstract Map<String, Set<MethodDeclaration>> oldMethods = originalClass.getAllMethods(); Map<String, Set<MethodDeclaration>> newMethods = getAllMethods(); areMethodsBinaryCompatible(oldMethods, newMethods, reasons); } private void areMethodsBinaryCompatible( Map<String, Set<MethodDeclaration>> oldMethods, Map<String, Set<MethodDeclaration>> newMethods, List<String> reasons) { boolean compatible = true; Map<String, Collection<MethodDeclaration>> extraMethods = new HashMap<String, Collection<MethodDeclaration>>(); for (Map.Entry<String, Set<MethodDeclaration>> me : newMethods.entrySet()) { Collection<MethodDeclaration> mds = new ArrayList<MethodDeclaration>(me.getValue()); extraMethods.put(me.getKey(), mds); } for (Map.Entry<String, Set<MethodDeclaration>> methods : oldMethods.entrySet()) { // all overloading methods, check against the current class String methodName = methods.getKey(); Collection<MethodDeclaration> oldMDSigs = methods.getValue(); // If the method cannot be found in the current class, it means that it has been deleted. Collection<MethodDeclaration> newMDSigs = newMethods.get(methodName); // for each overloading methods outer: for (MethodDeclaration md : oldMDSigs) { String mdName = md.getName(); String prefix = "The " + SemanticVersioningUtils.getReadableMethodSignature(mdName, md.getDesc()); if (md.isProtected() || md.isPublic()) { boolean found = false; if (newMDSigs != null) { // try to find it in the current class for (MethodDeclaration new_md : newMDSigs) { // find the method with the same return type, parameter list if ((md.equals(new_md))) { found = true; // If the old method is final but the new one is not or vice versa // If the old method is static but the new one is non static // If the old method is not abstract but the new is if (!!!Modifier.isFinal(md.getAccess()) && !!!Modifier.isStatic(md.getAccess()) && Modifier.isFinal(new_md.getAccess())) { compatible = false; reasons.add(prefix + " was not final but has been changed to be final."); } if (Modifier.isStatic(md.getAccess()) != Modifier.isStatic(new_md.getAccess())) { compatible = false; reasons.add(prefix + " has changed from static to non-static or vice versa."); } if ((Modifier.isAbstract(new_md.getAccess())) && (!Modifier.isAbstract(md.getAccess()))) { compatible = false; reasons.add(prefix + " has changed from non abstract to abstract."); } if (SemanticVersioningUtils.isLessAccessible(md, new_md)) { compatible = false; reasons.add(prefix + " is less accessible."); } if (compatible) { // remove from the extra map Collection<MethodDeclaration> mds = extraMethods.get(methodName); mds.remove(new_md); extraMethods.put(methodName, mds); continue outer; } } } } // // if we are here, it means that we have not found the method with the same description and signature // which means that the method has been deleted. Let's make sure it is not moved to its upper chain. if (!found) { if (!isMethodInSuperClass(md)) { compatible = false; reasons.add(prefix + " has been deleted or its return type or parameter list has changed."); } else { if (newMDSigs != null) { for (MethodDeclaration new_md : newMDSigs) { // find the method with the same return type, parameter list if ((md.equals(new_md))) { Collection<MethodDeclaration> mds = extraMethods.get(methodName); mds.remove(new_md); extraMethods.put(methodName, mds); } } } } } } } } // Check the newly added method has not caused binary incompatibility for (Map.Entry<String, Collection<MethodDeclaration>> extraMethodSet : extraMethods.entrySet()) { for (MethodDeclaration md : extraMethodSet.getValue()) { String head = "The " + SemanticVersioningUtils.getReadableMethodSignature(md.getName(), md.getDesc()); isNewMethodSpecialCase(md, head, reasons); } } } /** * Return the newly added fields * * @param old old class declaration * @return FieldDeclarations for fields added to new class */ public Collection<FieldDeclaration> getExtraFields(ClassDeclaration old) { Map<String, FieldDeclaration> oldFields = old.getAllFields(); Map<String, FieldDeclaration> newFields = getAllFields(); Map<String, FieldDeclaration> extraFields = new HashMap<String, FieldDeclaration>(newFields); for (String key : oldFields.keySet()) { extraFields.remove(key); } return extraFields.values(); } /** * Return the extra non-private methods * * @param old old class declaration * @return method declarations for methods added to new class */ public Collection<MethodDeclaration> getExtraMethods(ClassDeclaration old) { // Need to find whether there are new methods added. Collection<MethodDeclaration> extraMethods = new HashSet<MethodDeclaration>(); Map<String, Set<MethodDeclaration>> currMethodsMap = getAllMethods(); Map<String, Set<MethodDeclaration>> oldMethodsMap = old.getAllMethods(); for (Map.Entry<String, Set<MethodDeclaration>> currMethod : currMethodsMap.entrySet()) { String methodName = currMethod.getKey(); Collection<MethodDeclaration> newMethods = currMethod.getValue(); // for each method, we look for whether it exists in the old class Collection<MethodDeclaration> oldMethods = oldMethodsMap.get(methodName); for (MethodDeclaration new_md : newMethods) { if (!new_md.isPrivate()) { if (oldMethods == null) { extraMethods.add(new_md); } else { if (!oldMethods.contains(new_md)) { extraMethods.add(new_md); } } } } } return extraMethods; } public boolean isMethodInSuperClass(MethodDeclaration md) { // scan the super class and interfaces String methodName = md.getName(); Collection<MethodDeclaration> overloaddingMethods = getMethodsInUpperChain().get(methodName); if (overloaddingMethods != null) { for (MethodDeclaration value : overloaddingMethods) { // method signature and name same and also the method should not be less accessible if (md.equals(value) && (!!!SemanticVersioningUtils.isLessAccessible(md, value)) && (value.isStatic() == md.isStatic())) { return true; } } } return false; } /** * The newly added method is less accessible than the old one in the super or is a static (respectively instance) method. * * * @param md method declaration * @param prefix beginning of incompatibility message * @param reasons list of binary incompatibility reasons * @return whether new method is less accessible or changed static-ness compared to old class */ private boolean isNewMethodSpecialCase(MethodDeclaration md, String prefix, List<String> reasons) { // scan the super class and interfaces String methodName = md.getName(); boolean special = false; Collection<MethodDeclaration> overloaddingMethods = getMethodsInUpperChain().get(methodName); if (overloaddingMethods != null) { for (MethodDeclaration value : overloaddingMethods) { // method signature and name same and also the method should not be less accessible if (!SemanticVersioningUtils.CONSTRUTOR.equals(md.getName())) { if (md.equals(value)) { if (SemanticVersioningUtils.isLessAccessible(value, md)) { special = true; reasons.add(prefix + " is less accessible than the same method in its parent."); } if (value.isStatic()) { if (!md.isStatic()) { special = true; reasons.add(prefix + " is non-static but the same method in its parent is static."); } } else { if (md.isStatic()) { special = true; reasons.add(prefix + " is static but the same method is its parent is not static."); } } } } } } return special; } private void getAllSuperPresentStatus(ClassDeclaration old, List<String> reasons) { Collection<String> oldSupers = old.getAllSupers(); boolean containsAll = getAllSupers().containsAll(oldSupers); if (!!!containsAll) { oldSupers.removeAll(getAllSupers()); reasons.add("The superclasses or superinterfaces have stopped being super: " + oldSupers.toString() + "."); } } public SerialVersionClassVisitor getSerialVisitor() { return serialVisitor; } }
8,988
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/utils/SemanticVersioningUtils.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.versioning.utils; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.objectweb.asm.Opcodes; public class SemanticVersioningUtils { public static final String classExt = ".class"; public static final String javaExt = ".java"; public static final String schemaExt = ".xsd"; public static final String jarExt = ".jar"; public static final String CONSTRUTOR = "<init>"; public static final String MAJOR_CHANGE = "major"; public static final String MINOR_CHANGE = "minor"; public static final String NO_CHANGE = "no"; public static final String oneLineBreak = "\r\n"; public static final String twoLineBreaks = oneLineBreak + oneLineBreak; public static final String PROPERTY_FILE_IDENTIFIER = "java/util/ListResourceBundle"; public static final String CLINIT = "<clinit>"; public static final String SERIALIZABLE_CLASS_IDENTIFIER = "java/io/Serializable"; public static final String SERIAL_VERSION_UTD = "serialVersionUID"; public static final String ENUM_CLASS = "java/lang/Enum"; public static final int ASM4 = Opcodes.ASM4; public static boolean isLessAccessible(GenericDeclaration before, GenericDeclaration after) { if (before.getAccess() == after.getAccess()) { return false; } //When it reaches here, the two access are different. Let's make sure the whether the after field has less access than the before field. if (before.isPublic()) { if (!!!after.isPublic()) { return true; } } else if (before.isProtected()) { if (!!!(after.isPublic() || after.isProtected())) { return true; } } else { if (!!!before.isPrivate()) { // the field is package level. if (after.isPrivate()) { return true; } } } return false; } /** * ASM Type descriptor look up table * * @author emily */ private enum TypeDescriptor{ I("int"), Z("boolean"), C("char"), B("byte"), S("short"), F("float"), J("long"), D("double"), V("void"); String desc; TypeDescriptor(String desc) { this.desc = desc; } String getDesc() { return desc; } private static final Map<String, TypeDescriptor> stringToEnum = new HashMap<String, TypeDescriptor>(); static { for (TypeDescriptor td : values()) { stringToEnum.put(td.toString(), td); } } public static TypeDescriptor fromString(String symbol) { return stringToEnum.get(symbol); } } /** * Transform ASM method desc to a human readable form * Method declaration in source file Method descriptor * <pre> * void m(int i, float f) &lt;= (IF)V * int m(Object o) &lt;= (Ljava/lang/Object;)I * int[] m(int i, String s) &lt;= (ILjava/lang/String;)[I * Object m(int[] i) &lt;= ([I)Ljava/lang/Object; * </pre> */ public static String getReadableMethodSignature(String methodName, String methodDesc) { // need to find the return type first, which is outside the () int lastBrace = methodDesc.lastIndexOf(")"); // parameter StringBuilder methodSignature = new StringBuilder(); if (lastBrace == -1) { // this is odd, don't attempt to transform. Just return back. Won't happen unless byte code weaving is not behaving. return "method " + methodName + methodDesc; } String param = methodDesc.substring(1, lastBrace); if (CONSTRUTOR.equals(methodName)) { //This means the method is a constructor. In the binary form, the constructor carries a name 'init'. Let's use the source // code proper name methodSignature.append("constructor with parameter list "); } else { String returnType = methodDesc.substring(lastBrace + 1); methodSignature.append("method "); methodSignature.append(transform(returnType)); methodSignature.append(" "); methodSignature.append(methodName); } // add the paramether list methodSignature.append("("); methodSignature.append(transform(param)); methodSignature.append(")"); return methodSignature.toString(); } public static String transform(String asmDesc) { String separator = ", "; int brkCount = 0; StringBuilder returnStr = new StringBuilder(); //remove the '['s while (asmDesc.length() > 0) { while (asmDesc.startsWith("[")) { asmDesc = asmDesc.substring(1); brkCount++; } while (asmDesc.startsWith("L")) { //remove the L and ; int semiColonIndex = asmDesc.indexOf(";"); if (semiColonIndex == -1) { //This is odd. The asm binary code is invalid. Do not attempt to transform. return asmDesc; } returnStr.append(asmDesc.substring(1, semiColonIndex)); asmDesc = asmDesc.substring(semiColonIndex + 1); for (int index = 0; index < brkCount; index++) { returnStr.append("[]"); } brkCount = 0; returnStr.append(separator); } TypeDescriptor td = null; while ((asmDesc.length() > 0) && (td = TypeDescriptor.fromString(asmDesc.substring(0, 1))) != null) { returnStr.append(td.getDesc()); for (int index = 0; index < brkCount; index++) { returnStr.append("[]"); } brkCount = 0; returnStr.append(separator); asmDesc = asmDesc.substring(1); } } String finalStr = returnStr.toString(); if (finalStr.endsWith(separator)) { finalStr = finalStr.substring(0, finalStr.lastIndexOf(separator)); } //replace "/" with "." as bytecode uses / in the package names finalStr = finalStr.replaceAll("/", "."); return finalStr; } /** * Return whether the binary is property file. If the binary implements the interface of java.util.ListResourceBundle * * @param cd * @return */ public static boolean isPropertyFile(ClassDeclaration cd) { Collection<String> supers = cd.getAllSupers(); return (supers.contains(PROPERTY_FILE_IDENTIFIER)); } }
8,989
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/utils/SemanticVersioningClassVisitor.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.versioning.utils; import java.lang.reflect.Modifier; import java.net.URLClassLoader; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; public class SemanticVersioningClassVisitor extends ClassVisitor { private ClassDeclaration classDeclaration; private boolean needVisit = false; private URLClassLoader loader = null; private SerialVersionClassVisitor cv = null; public SemanticVersioningClassVisitor(URLClassLoader newJarLoader, SerialVersionClassVisitor cv) { super(SemanticVersioningUtils.ASM4); this.loader = newJarLoader; this.cv = cv; } public SemanticVersioningClassVisitor(URLClassLoader newJarLoader) { super(SemanticVersioningUtils.ASM4); this.loader = newJarLoader; } public ClassDeclaration getClassDeclaration() { return classDeclaration; } /* * (non-Javadoc) * * @see org.objectweb.asm.ClassAdapter#visit(int, int, * java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ // visit the header of the class @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { // only interested in public class if (cv != null) { cv.visit(version, access, name, signature, superName, interfaces); } if (Modifier.isPublic(access) || (Modifier.isProtected(access))) { classDeclaration = new ClassDeclaration(access, name, signature, superName, interfaces, loader, cv); needVisit = true; } } /* * (non-Javadoc) * * @see org.objectweb.asm.ClassAdapter#visitField(int, java.lang.String, * java.lang.String, java.lang.String, java.lang.Object) * * Grab all protected or public fields */ @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (cv != null) { cv.visitField(access, name, desc, signature, value); } if (needVisit) { FieldDeclaration fd = new FieldDeclaration(access, name, desc, signature, value); classDeclaration.addFields(fd); } return null; } /* * (non-Javadoc) * * @see org.objectweb.asm.ClassAdapter#visitMethod(int, java.lang.String, * java.lang.String, java.lang.String, java.lang.String[]) * Get all non-private methods */ @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (cv != null) { cv.visitMethod(access, name, desc, signature, exceptions); } if (needVisit && (!SemanticVersioningUtils.CLINIT.equals(name))) { MethodDeclaration md = new MethodDeclaration(access, name, desc, signature, exceptions); classDeclaration.addMethods(md); } return null; } @Override public AnnotationVisitor visitAnnotation(String arg0, boolean arg1) { return null; } @Override public void visitAttribute(Attribute arg0) { // no-op } @Override public void visitEnd() { //no-op } @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { //no-op //The inner class will be scanned on its own. However, the method level class will be excluded, as they won't be public or protected. } @Override public void visitOuterClass(String owner, String name, String desc) { //no op } @Override public void visitSource(String arg0, String arg1) { //no-op } }
8,990
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/check/BundleCompatibility.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.versioning.check; import static org.apache.aries.versioning.utils.SemanticVersioningUtils.oneLineBreak; import static org.apache.aries.versioning.utils.SemanticVersioningUtils.twoLineBreaks; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.aries.util.filesystem.FileSystem; 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.ManifestHeaderProcessor; import org.apache.aries.versioning.utils.BinaryCompatibilityStatus; import org.apache.aries.versioning.utils.ClassDeclaration; import org.apache.aries.versioning.utils.FieldDeclaration; import org.apache.aries.versioning.utils.MethodDeclaration; import org.apache.aries.versioning.utils.SemanticVersioningClassVisitor; import org.apache.aries.versioning.utils.SemanticVersioningUtils; import org.apache.aries.versioning.utils.SerialVersionClassVisitor; import org.objectweb.asm.ClassReader; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @version $Rev:$ $Date:$ */ public class BundleCompatibility { private static final Logger _logger = LoggerFactory.getLogger(BundleCompatibility.class); private URLClassLoader oldJarsLoader; private URLClassLoader newJarsLoader; private String bundleSymbolicName; private String bundleElement; private boolean bundleVersionCorrect; private BundleInfo currentBundle; private BundleInfo baseBundle; private StringBuilder pkgElements = new StringBuilder(); private List<String> pkgElementsList = new ArrayList<String>(); private List<String> excludes; private VersionChange bundleChange; private final Map<String, VersionChange> packageChanges = new HashMap<String, VersionChange>(); public BundleCompatibility(String bundleSymbolicName, BundleInfo currentBundle, BundleInfo baseBundle, URLClassLoader oldJarsLoader, URLClassLoader newJarsLoader) { this(bundleSymbolicName, currentBundle, baseBundle, oldJarsLoader, newJarsLoader, null); } public BundleCompatibility(String bundleSymbolicName, BundleInfo currentBundle, BundleInfo baseBundle, URLClassLoader oldJarsLoader, URLClassLoader newJarsLoader, List<String> excludes) { this.bundleSymbolicName = bundleSymbolicName; this.currentBundle = currentBundle; this.baseBundle = baseBundle; this.oldJarsLoader = oldJarsLoader; this.newJarsLoader = newJarsLoader; this.excludes = excludes != null ? excludes : new ArrayList<String>(); } public VersionChange getBundleChange() { return bundleChange; } public Map<String, VersionChange> getPackageChanges() { return packageChanges; } public String getBundleElement() { return bundleElement; } public StringBuilder getPkgElements() { return pkgElements; } private boolean ignoreChange(String reason) { if ((reason == null) || (this.excludes.isEmpty())) return false; for (String exclude : this.excludes) { // Could have interpreted each exclude as a regex, but that makes it easy to write loose rules // that match more strings than intended. if ((reason != null) && reason.contains(exclude)) return true; } return false; } public boolean isBundleVersionCorrect() { return bundleVersionCorrect; } public BundleCompatibility invoke() throws IOException { String reason = null; // open the manifest and scan the export package and find the package name and exported version // The tool assume the one particular package just exports under one version Map<String, PackageContent> currBundleExpPkgContents = getAllExportedPkgContents(currentBundle); Map<String, PackageContent> baseBundleExpPkgContents; boolean pkg_major_change = false; boolean pkg_minor_change = false; String fatal_package = null; if (!!!currBundleExpPkgContents.isEmpty()) { baseBundleExpPkgContents = getAllExportedPkgContents(baseBundle); // compare each class right now for (Map.Entry<String, PackageContent> pkg : baseBundleExpPkgContents.entrySet()) { String pkgName = pkg.getKey(); Map<String, IFile> baseClazz = pkg.getValue().getClasses(); Map<String, IFile> baseXsds = pkg.getValue().getXsds(); PackageContent currPkgContents = currBundleExpPkgContents.get(pkgName); if (currPkgContents == null) { // The package is no longer exported any more. This should lead to bundle major version change. pkg_major_change = true; fatal_package = pkgName; _logger.debug("The package " + pkgName + " in the bundle of " + bundleSymbolicName + " is no longer to be exported. Major change."); } else { Map<String, IFile> curClazz = currPkgContents.getClasses(); Map<String, IFile> curXsds = currPkgContents.getXsds(); //check whether there should be major change/minor change/micro change in this package. //1. Use ASM to visit all classes in the package VersionChangeReason majorChange = new VersionChangeReason(); VersionChangeReason minorChange = new VersionChangeReason(); // check all classes to see whether there are minor or major changes visitPackage(pkgName, baseClazz, curClazz, majorChange, minorChange); // If there is no binary compatibility changes, check whether xsd files have been added, changed or deleted if (!!!majorChange.isChange()) { checkXsdChangesInPkg(pkgName, baseXsds, curXsds, majorChange); // If everything is ok with the existing classes. Need to find out whether there are more API (abstract classes) in the current bundle. // loop through curClazz and visit it and find out whether one of them is abstract. // check whether there are more xsd or abstract classes added if (!!!(majorChange.isChange() || minorChange.isChange())) { checkAdditionalClassOrXsds(pkgName, curClazz, curXsds, minorChange); } } // We have scanned the whole packages, report the result // if (majorChange.isChange() || minorChange.isChange()) { String oldVersion = pkg.getValue().getPackageVersion(); String newVersion = currPkgContents.getPackageVersion(); if (majorChange.isChange() && !!!ignoreChange(majorChange.getReason())) { packageChanges.put(pkgName, new VersionChange(VERSION_CHANGE_TYPE.MAJOR_CHANGE, oldVersion, newVersion)); pkg_major_change = true; fatal_package = pkgName; if (!!!isVersionCorrect(VERSION_CHANGE_TYPE.MAJOR_CHANGE, oldVersion, newVersion)) { pkgElementsList.add(getPkgStatusText(pkgName, VERSION_CHANGE_TYPE.MAJOR_CHANGE, oldVersion, newVersion, majorChange.getReason(), majorChange.getChangeClass())); } } else if (minorChange.isChange() && !!!ignoreChange(minorChange.getReason())) { packageChanges.put(pkgName, new VersionChange(VERSION_CHANGE_TYPE.MINOR_CHANGE, oldVersion, newVersion)); pkg_minor_change = true; if (fatal_package == null) fatal_package = pkgName; if (!!!isVersionCorrect(VERSION_CHANGE_TYPE.MINOR_CHANGE, oldVersion, newVersion)) { pkgElementsList.add(getPkgStatusText(pkgName, VERSION_CHANGE_TYPE.MINOR_CHANGE, pkg.getValue().getPackageVersion(), currPkgContents.getPackageVersion(), minorChange.getReason(), minorChange.getChangeClass())); } } else { packageChanges.put(pkgName, new VersionChange(VERSION_CHANGE_TYPE.NO_CHANGE, oldVersion, newVersion)); pkgElementsList.add(getPkgStatusText(pkgName, VERSION_CHANGE_TYPE.NO_CHANGE, pkg.getValue().getPackageVersion(), currPkgContents.getPackageVersion(), "", "")); } } } // If there is a package version change, the bundle version needs to be updated. // If there is a major change in one of the packages, the bundle major version needs to be increased. // If there is a minor change in one of the packages, the bundle minor version needs to be increased. String oldVersion = baseBundle.getBundleManifest().getVersion().toString(); String newVersion = currentBundle.getBundleManifest().getVersion().toString(); if (pkg_major_change || pkg_minor_change) { if (pkg_major_change) { // The bundle version's major value should be increased. bundleChange = new VersionChange(VERSION_CHANGE_TYPE.MAJOR_CHANGE, oldVersion, newVersion); reason = "Some packages have major changes. For an instance, the package " + fatal_package + " has major version changes."; bundleElement = getBundleStatusText(currentBundle.getBundle().getName(), bundleSymbolicName, VERSION_CHANGE_TYPE.MAJOR_CHANGE, oldVersion, newVersion, reason); bundleVersionCorrect = isVersionCorrect(VERSION_CHANGE_TYPE.MAJOR_CHANGE, oldVersion, newVersion); } else if (pkg_minor_change) { bundleChange = new VersionChange(VERSION_CHANGE_TYPE.MINOR_CHANGE, oldVersion, newVersion); reason = "Some packages have minor changes. For an instance, the package " + fatal_package + " has minor version changes."; bundleElement = getBundleStatusText(currentBundle.getBundle().getName(), bundleSymbolicName, VERSION_CHANGE_TYPE.MINOR_CHANGE, oldVersion, newVersion, reason); bundleVersionCorrect = isVersionCorrect(VERSION_CHANGE_TYPE.MINOR_CHANGE, oldVersion, newVersion); } } else { bundleChange = new VersionChange(VERSION_CHANGE_TYPE.NO_CHANGE, oldVersion, newVersion); bundleVersionCorrect = isVersionCorrect(VERSION_CHANGE_TYPE.NO_CHANGE, oldVersion, newVersion); if (!bundleVersionCorrect) { reason = "The bundle has no version changes."; bundleElement = getBundleStatusText(currentBundle.getBundle().getName(), bundleSymbolicName, VERSION_CHANGE_TYPE.NO_CHANGE, oldVersion, newVersion, reason); } } } return this; } private Map<String, PackageContent> getAllExportedPkgContents(BundleInfo currentBundle) { String packageExports = currentBundle.getBundleManifest().getRawAttributes().getValue(Constants.EXPORT_PACKAGE); List<ManifestHeaderProcessor.NameValuePair> exportPackageLists = ManifestHeaderProcessor.parseExportString(packageExports); // only perform validation if there are some packages exported. Otherwise, not interested. Map<String, PackageContent> exportedPackages = new HashMap<String, PackageContent>(); if (!!!exportPackageLists.isEmpty()) { File bundleFile = currentBundle.getBundle(); IDirectory bundleDir = FileSystem.getFSRoot(bundleFile); for (ManifestHeaderProcessor.NameValuePair exportedPackage : exportPackageLists) { String packageName = exportedPackage.getName(); String packageVersion = exportedPackage.getAttributes().get(Constants.VERSION_ATTRIBUTE); // need to go through each package and scan every class exportedPackages.put(packageName, new PackageContent(packageName, packageVersion)); } // scan the jar and list all the files under each package List<IFile> allFiles = bundleDir.listAllFiles(); for (IFile file : allFiles) { String directoryFullPath = file.getName(); String directoryName = null; String fileName = null; if (file.isFile() && ((file.getName().endsWith(SemanticVersioningUtils.classExt) || (file.getName().endsWith(SemanticVersioningUtils.schemaExt))))) { if (directoryFullPath.lastIndexOf("/") != -1) { directoryName = directoryFullPath.substring(0, directoryFullPath.lastIndexOf("/")); fileName = directoryFullPath.substring(directoryFullPath.lastIndexOf("/") + 1); } } if (directoryName != null) { String pkgName = directoryName.replaceAll("/", "."); PackageContent pkgContent = exportedPackages.get(pkgName); if (pkgContent != null) { if (file.getName().endsWith(SemanticVersioningUtils.classExt)) { pkgContent.addClass(fileName, file); } else { pkgContent.addXsd(fileName, file); } exportedPackages.put(pkgName, pkgContent); } } } } return exportedPackages; } private String getBundleStatusText(String bundleFileName, String bundleSymbolicName, VERSION_CHANGE_TYPE status, String oldVersionStr, String newVersionStr, String reason) { if (!isVersionCorrect(status, oldVersionStr, newVersionStr)) { return "The bundle " + bundleSymbolicName + " has the following changes:\r\n" + reason + "\r\nThe bundle version should be " + getRecommendedVersion(status, oldVersionStr) + "."; } else { return ""; } } /** * Visit the whole package to scan each class to see whether we need to log minor or major changes. * * @param pkgName * @param baseClazz * @param curClazz * @param majorChange * @param minorChange */ private void visitPackage(String pkgName, Map<String, IFile> baseClazz, Map<String, IFile> curClazz, VersionChangeReason majorChange, VersionChangeReason minorChange) { StringBuilder major_reason = new StringBuilder(); StringBuilder minor_reason = new StringBuilder(); boolean is_major_change = false; boolean is_minor_change = false; String fatal_class = null; boolean foundNewAbstract = false; for (Map.Entry<String, IFile> file : baseClazz.entrySet()) { // scan the latest version of the class IFile curFile = curClazz.get(file.getKey()); String changeClass = file.getValue().getName(); //Scan the base version SemanticVersioningClassVisitor oldcv = getVisitor(file.getValue(), oldJarsLoader); // skip the property files as they are compiled as class file as well ClassDeclaration cd = oldcv.getClassDeclaration(); if ((cd != null) && (!SemanticVersioningUtils.isPropertyFile(cd))) { if (curFile == null) { // the class we are scanning has been deleted from the current version of the bundle // This should be a major increase major_reason.append(twoLineBreaks + "The class/interface " + getClassName(changeClass) + " has been deleted from the package."); //majorChange.update(reason, changeClass); is_major_change = true; // only replace the fatal class if not set as the class won't be found in cmvc due to the fact it has been deleted. if (fatal_class == null) { fatal_class = changeClass; } } else { // check for binary compatibility // load the class from the current version of the bundle // remove it from the curClazz collection as we would like to know whether there are more classes added curClazz.remove(file.getKey()); SemanticVersioningClassVisitor newcv = getVisitor(curFile, newJarsLoader); // check for binary compatibility ClassDeclaration newcd = newcv.getClassDeclaration(); BinaryCompatibilityStatus bcs = newcd.getBinaryCompatibleStatus(oldcv.getClassDeclaration()); if (!bcs.isCompatible()) { major_reason.append(twoLineBreaks + "In the " + getClassName(changeClass) + " class or its supers, the following changes have been made since the last release."); // break binary compatibility for (String reason : bcs) { major_reason.append(oneLineBreak).append(reason); } is_major_change = true; fatal_class = changeClass; } else { //check to see whether more methods are added ClassDeclaration oldcd = oldcv.getClassDeclaration(); Collection<MethodDeclaration> extraMethods = newcd.getExtraMethods(oldcd); boolean containsConcrete = false; boolean containsAbstract = false; boolean abstractClass = newcd.isAbstract(); StringBuilder subRemarks = new StringBuilder(); String concreteSubRemarks = null; for (MethodDeclaration extraMethod : extraMethods) { //only interested in the visible methods not the system generated ones if (!extraMethod.getName().contains("$")) { if (abstractClass) { if (extraMethod.isAbstract()) { foundNewAbstract = true; containsAbstract = true; subRemarks.append(oneLineBreak + SemanticVersioningUtils.getReadableMethodSignature(extraMethod.getName(), extraMethod.getDesc())); } else { //only list one abstract method, no need to list all containsConcrete = true; concreteSubRemarks = oneLineBreak + SemanticVersioningUtils.getReadableMethodSignature(extraMethod.getName(), extraMethod.getDesc()); } } else { containsConcrete = true; concreteSubRemarks = oneLineBreak + SemanticVersioningUtils.getReadableMethodSignature(extraMethod.getName(), extraMethod.getDesc()); break; } } } if (containsConcrete || containsAbstract) { is_minor_change = true; if (!is_major_change) { fatal_class = changeClass; } if (containsAbstract) { minor_reason.append(twoLineBreaks + "In the " + getClassName(changeClass) + " class or its supers, the following abstract methods have been added since the last release of this bundle."); minor_reason.append(subRemarks); } else { minor_reason.append(twoLineBreaks + "In the " + getClassName(changeClass) + " class or its supers, the following method has been added since the last release of this bundle."); minor_reason.append(concreteSubRemarks); } } //check to see whether there are extra public/protected fields if there is no additional methods if (!is_minor_change) { for (FieldDeclaration field : newcd.getExtraFields(oldcd)) { if (field.isPublic() || field.isProtected()) { is_minor_change = true; String extraFieldRemarks = oneLineBreak + " " + SemanticVersioningUtils.transform(field.getDesc()) + " " + field.getName(); if (!is_major_change) { fatal_class = changeClass; } minor_reason.append(twoLineBreaks + "In the " + getClassName(changeClass) + " class or its supers, the following fields have been added since the last release of this bundle."); minor_reason.append(extraFieldRemarks); break; } } } } } } } if (is_major_change) { majorChange.update(major_reason.toString(), fatal_class, false); } if (is_minor_change) { minorChange.update(minor_reason.toString(), fatal_class, (foundNewAbstract ? true : false)); } } /** * Check whether the package has xsd file changes or deleted. If yes, log a minor change. * * @param pkgName * @param baseXsds * @param curXsds * @param majorChange * @throws java.io.IOException */ private void checkXsdChangesInPkg(String pkgName, Map<String, IFile> baseXsds, Map<String, IFile> curXsds, VersionChangeReason majorChange) throws IOException { String reason; for (Map.Entry<String, IFile> file : baseXsds.entrySet()) { // scan the latest version of the class IFile curXsd = curXsds.get(file.getKey()); String changeClass = file.getValue().getName(); // check whether the xsd have been deleted or changed or added if (curXsd == null) { reason = "In the package " + pkgName + ", The schema file has been deleted: " + file.getKey() + "."; majorChange.update(reason, changeClass, false); break; } else { // check whether it is the same //read the current xsd file curXsds.remove(file.getKey()); String curFileContent = readXsdFile(curXsd.open()); String oldFileContent = readXsdFile(file.getValue().open()); if (!!!(curFileContent.equals(oldFileContent))) { reason = "In the package " + pkgName + ", The schema file has been updated: " + file.getKey() + "."; majorChange.update(reason, changeClass, false); break; } } } } /** * Check whether the package has gained additional class or xsd files. If yes, log a minor change. * * @param pkgName * @param curClazz * @param curXsds * @param minorChange */ private void checkAdditionalClassOrXsds(String pkgName, Map<String, IFile> curClazz, Map<String, IFile> curXsds, VersionChangeReason minorChange) { String reason; Collection<IFile> ifiles = curClazz.values(); Iterator<IFile> iterator = ifiles.iterator(); while (iterator.hasNext()) { IFile ifile = iterator.next(); String changeClass = ifile.getName(); SemanticVersioningClassVisitor cv = getVisitor(ifile, newJarsLoader); if (cv.getClassDeclaration() != null) { // If this is a public/protected class, it will need to increase the minor version of the package. minorChange.setChange(true); if (minorChange.isChange()) { reason = "The package " + pkgName + " has gained at least one class : " + getClassName(changeClass) + "."; minorChange.update(reason, changeClass, false); break; } } } if (!!!(minorChange.isChange() || curXsds.isEmpty())) { /// a new xsd file was added, it is a minor change IFile firstXsd = null; Iterator<IFile> xsdIterator = curXsds.values().iterator(); firstXsd = xsdIterator.next(); reason = "In the package " + pkgName + ", The schema file(s) are added: " + curXsds.keySet() + "."; minorChange.update(reason, firstXsd.getName(), false); } } static boolean isVersionCorrect(VERSION_CHANGE_TYPE status, String oldVersionStr, String newVersionStr) { boolean versionCorrect = false; Version oldVersion = Version.parseVersion(oldVersionStr); Version newVersion = Version.parseVersion(newVersionStr); if (status == VERSION_CHANGE_TYPE.MAJOR_CHANGE) { if (newVersion.getMajor() > oldVersion.getMajor()) { versionCorrect = true; } } else if (status == VERSION_CHANGE_TYPE.MINOR_CHANGE) { if ((newVersion.getMajor() > oldVersion.getMajor()) || (newVersion.getMinor() > oldVersion.getMinor())) { versionCorrect = true; } } else { if ((newVersion.getMajor() >= oldVersion.getMajor()) && (newVersion.getMinor() >= oldVersion.getMinor())) { versionCorrect = true; } } return versionCorrect; } private String getRecommendedVersion( VERSION_CHANGE_TYPE status, String oldVersionStr) { Version oldVersion = Version.parseVersion(oldVersionStr); Version recommendedNewVersion; if (status == BundleCompatibility.VERSION_CHANGE_TYPE.MAJOR_CHANGE) { recommendedNewVersion = new Version(oldVersion.getMajor() + 1, 0, 0); } else if (status == BundleCompatibility.VERSION_CHANGE_TYPE.MINOR_CHANGE) { recommendedNewVersion = new Version(oldVersion.getMajor(), oldVersion.getMinor() + 1, 0); } else { recommendedNewVersion = oldVersion; } return recommendedNewVersion.toString(); } private String getPkgStatusText(String pkgName, VERSION_CHANGE_TYPE status, String oldVersionStr, String newVersionStr, String reason, String key_class) { if (!isVersionCorrect(status, oldVersionStr, newVersionStr)) { return "The package " + pkgName + " has the following changes:" + reason + "\r\nThe package version should be " + getRecommendedVersion(status, oldVersionStr) + "."; } else { return ""; } } private String getClassName(String fullClassPath) { String[] chunks = fullClassPath.split("/"); String className = chunks[chunks.length - 1]; className = className.replace(SemanticVersioningUtils.classExt, SemanticVersioningUtils.javaExt); return className; } private String readXsdFile(InputStream is) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException ioe) { IOUtils.close(br); } return sb.toString(); } private SemanticVersioningClassVisitor getVisitor(IFile file, URLClassLoader loader) { SerialVersionClassVisitor sv = new SerialVersionClassVisitor(null); SemanticVersioningClassVisitor oldcv = new SemanticVersioningClassVisitor(loader, sv); try { ClassReader cr = new ClassReader(file.open()); cr.accept(oldcv, 0); } catch (IOException ioe) { _logger.debug("The file " + file + "cannot be opened."); } return oldcv; } enum VERSION_CHANGE_TYPE { MAJOR_CHANGE("major"), MINOR_CHANGE("minor"), NO_CHANGE("no"); private final String text; VERSION_CHANGE_TYPE(String text) { this.text = text; } public String text() { return this.text; } } private static class PackageContent { private final String packageName; private final String packageVersion; private final Map<String, IFile> classes = new HashMap<String, IFile>(); private final Map<String, IFile> xsds = new HashMap<String, IFile>(); PackageContent(String pkgName, String pkgVersion) { packageName = pkgName; packageVersion = pkgVersion; } public void addClass(String className, IFile file) { classes.put(className, file); } public void addXsd(String className, IFile file) { xsds.put(className, file); } public Map<String, IFile> getClasses() { return classes; } public Map<String, IFile> getXsds() { return xsds; } public String getPackageVersion() { return packageVersion; } public String getPackageName() { return packageName; } } private static class VersionChangeReason { boolean change = false; String reason = null; String changeClass = null; boolean moreAbstractMethod = false; public boolean isMoreAbstractMethod() { return moreAbstractMethod; } public boolean isChange() { return change; } public void setChange(boolean change) { this.change = change; } public String getReason() { return reason; } public String getChangeClass() { return changeClass; } public void update(String reason, String changeClass, boolean moreAbstractMethod) { this.change = true; this.reason = reason; this.changeClass = changeClass; this.moreAbstractMethod = moreAbstractMethod; } } }
8,991
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/check/SemanticVersioningChecker.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.versioning.check; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.String; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.apache.aries.util.filesystem.FileSystem; 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.apache.aries.versioning.utils.SemanticVersioningUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SemanticVersioningChecker { private static final Logger _logger = LoggerFactory.getLogger(SemanticVersioningChecker.class); private URLClassLoader newJarsLoader; private URLClassLoader oldJarsLoader; private static final String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; /** * This method is to scan the current location against base and process each individual jars * in the current location against the jar with the same symbolic names in the base and produce a xml report specified by versioningReport. * * @param base baseline jars * @param current current version of jars * @param versioningReport the validation reports */ public static void checkSemanticVersioning(URL base, URL current, File versioningReport) { //For each jar under the current location, open the jar and then use ASM to //work out whether there are binary incompatible changes against the base location. try { File baseDir = new File(base.toURI()); File currentDir = new File(current.toExternalForm()); if (baseDir.exists() && currentDir.exists()) { new SemanticVersioningChecker().performVersioningCheck(FileSystem.getFSRoot(baseDir), FileSystem.getFSRoot(currentDir), versioningReport); } else { _logger.debug("No bundles found to process."); } } catch (URISyntaxException use) { _logger.error(use.getMessage()); } } // for each jar, open its manifest and found the packages private void performVersioningCheck(IDirectory baseDir, IDirectory currentDir, File versionStatusFile) { FileWriter versionStatusFileWriter = null; try { versionStatusFileWriter = new FileWriter(versionStatusFile, false); Map<String, BundleInfo> baseBundles; Map<String, BundleInfo> currentBundles; //scan each individual bundle and find the corresponding bundle in the baseline and verify the version changes currentBundles = getBundles(currentDir); baseBundles = getBundles(baseDir); URL[] newJarURLs = getListURLs(currentBundles.values()).toArray(new URL[0]); newJarsLoader = new URLClassLoader(newJarURLs); URL[] oldJarURLs = getListURLs(baseBundles.values()).toArray(new URL[0]); oldJarsLoader = new URLClassLoader(oldJarURLs); //Write the xml header writeRecordToWriter(versionStatusFileWriter, xmlHeader + "\r\n"); // write the comparison base and current level into the file writeRecordToWriter(versionStatusFileWriter, "<semanticVersioning currentDir= \"" + currentDir + "\" baseDir = \"" + baseDir + "\">"); for (Map.Entry<String, BundleInfo> entry : currentBundles.entrySet()) { String bundleSymbolicName = entry.getKey(); String bundleElement = null; boolean bundleVersionCorrect = true; // find the same bundle in the base and check whether all the versions are correct BundleInfo currentBundle = entry.getValue(); BundleInfo baseBundle = baseBundles.get(bundleSymbolicName); StringBuilder pkgElements = new StringBuilder(); if (baseBundle == null) { _logger.debug("The bundle " + bundleSymbolicName + " has no counterpart in the base. The semantic version validation does not apply to this bundle."); } else { BundleCompatibility bundleCompatibility = new BundleCompatibility(bundleSymbolicName, currentBundle, baseBundle, oldJarsLoader, newJarsLoader).invoke(); bundleVersionCorrect = bundleCompatibility.isBundleVersionCorrect(); bundleElement = bundleCompatibility.getBundleElement(); pkgElements = bundleCompatibility.getPkgElements(); } // Need to write bundle element and then package elements if ((!!!bundleVersionCorrect) || ((pkgElements.length() > 0))) { writeRecordToWriter(versionStatusFileWriter, bundleElement); writeRecordToWriter(versionStatusFileWriter, pkgElements.toString()); writeRecordToWriter(versionStatusFileWriter, "</bundle>"); } } writeRecordToWriter(versionStatusFileWriter, "</semanticVersioning>"); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.close(versionStatusFileWriter); } return; } private void writeRecordToWriter(FileWriter fileWriter, String stringToWrite) throws IOException { if (fileWriter != null) { fileWriter.append(stringToWrite); fileWriter.append("\r\n"); } } private Map<String, BundleInfo> getBundles(IDirectory ds) { Map<String, BundleInfo> bundles = new HashMap<String, BundleInfo>(); List<IFile> includedFiles = ds.listAllFiles(); for (IFile ifile : includedFiles) { if (ifile.getName().endsWith(SemanticVersioningUtils.jarExt)) { // scan its manifest try { BundleManifest manifest = BundleManifest.fromBundle(ifile.open()); // find the bundle symbolic name, store them in a map with bundle symbolic name as key, bundleInfo as value if (manifest.getSymbolicName() != null) { bundles.put(manifest.getSymbolicName(), new BundleInfo(manifest, new File(ifile.toURL().getPath()))); } } catch (MalformedURLException mue) { _logger.debug("Exception thrown when processing" + ifile.getName(), mue); } catch (IOException ioe) { _logger.debug("Exception thrown when processing" + ifile.getName(), ioe); } } } return bundles; } private Collection<URL> getListURLs(Collection<BundleInfo> bundles) { Collection<URL> urls = new HashSet<URL>(); try { for (BundleInfo bundle : bundles) { URL url = bundle.getBundle().toURI().toURL(); urls.add(url); } } catch (MalformedURLException e) { _logger.debug(e.getMessage()); } return urls; } }
8,992
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/check/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 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.versioning.check; import java.io.File; import org.apache.aries.util.manifest.BundleManifest; /** * @version $Rev:$ $Date:$ */ public class BundleInfo { private final BundleManifest bundleManifest; private final File bundle; public BundleInfo(BundleManifest bm, File bundle) { this.bundleManifest = bm; this.bundle = bundle; } public BundleManifest getBundleManifest() { return bundleManifest; } public File getBundle() { return bundle; } }
8,993
0
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning
Create_ds/aries/versioning/versioning-checker/src/main/java/org/apache/aries/versioning/check/VersionChange.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.versioning.check; import org.osgi.framework.Version; /** * @version $Rev:$ $Date:$ */ public class VersionChange { private BundleCompatibility.VERSION_CHANGE_TYPE changeType; private Version oldVersion; private Version newVersion; private Version recommendedNewVersion; private boolean correct; VersionChange(BundleCompatibility.VERSION_CHANGE_TYPE status, String oldVersionStr, String newVersionStr) { oldVersion = Version.parseVersion(oldVersionStr); newVersion = Version.parseVersion(newVersionStr); if (status == BundleCompatibility.VERSION_CHANGE_TYPE.MAJOR_CHANGE) { recommendedNewVersion = new Version(oldVersion.getMajor() + 1, 0, 0); } else if (status == BundleCompatibility.VERSION_CHANGE_TYPE.MINOR_CHANGE) { recommendedNewVersion = new Version(oldVersion.getMajor(), oldVersion.getMinor() + 1, 0); } else { recommendedNewVersion = oldVersion; } correct = BundleCompatibility.isVersionCorrect(status, oldVersionStr, newVersionStr); } VersionChange(BundleCompatibility.VERSION_CHANGE_TYPE changeType, Version newVersion, Version oldVersion, Version recommendedNewVersion, boolean correct) { this.changeType = changeType; this.newVersion = newVersion; this.oldVersion = oldVersion; this.recommendedNewVersion = recommendedNewVersion; this.correct = correct; } public BundleCompatibility.VERSION_CHANGE_TYPE getChangeType() { return changeType; } public Version getNewVersion() { return newVersion; } public Version getOldVersion() { return oldVersion; } public Version getRecommendedNewVersion() { return recommendedNewVersion; } public boolean isCorrect() { return correct; } @Override public String toString() { return " oldVersion=\"" + getOldVersion() + "\" currentVersion=\"" + getNewVersion() + "\" recommendedVersion=\"" + getRecommendedNewVersion() + "\" correct=\"" + isCorrect(); } }
8,994
0
Create_ds/aries/ejb/openejb-extender-itest/src/test/java/org/apache/aries/ejb/openejb/extender
Create_ds/aries/ejb/openejb-extender-itest/src/test/java/org/apache/aries/ejb/openejb/extender/itest/AbstractOpenEJBTest.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.ejb.openejb.extender.itest; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.util.io.IOUtils; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; public abstract class AbstractOpenEJBTest extends AbstractIntegrationTest { @Configuration public static Option[] configuration() { return options( junitBundles(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api", "1.7.2"), mavenBundle("org.ops4j.pax.logging", "pax-logging-service", "1.7.2"), frameworkProperty("org.osgi.framework.system.packages") .value("javax.accessibility,javax.activation,javax.activity,javax.annotation,javax.annotation.processing,javax.crypto,javax.crypto.interfaces,javax.crypto.spec,javax.imageio,javax.imageio.event,javax.imageio.metadata,javax.imageio.plugins.bmp,javax.imageio.plugins.jpeg,javax.imageio.spi,javax.imageio.stream,javax.jws,javax.jws.soap,javax.lang.model,javax.lang.model.element,javax.lang.model.type,javax.lang.model.util,javax.management,javax.management.loading,javax.management.modelmbean,javax.management.monitor,javax.management.openmbean,javax.management.relation,javax.management.remote,javax.management.remote.rmi,javax.management.timer,javax.naming,javax.naming.directory,javax.naming.event,javax.naming.ldap,javax.naming.spi,javax.net,javax.net.ssl,javax.print,javax.print.attribute,javax.print.attribute.standard,javax.print.event,javax.rmi,javax.rmi.CORBA,javax.rmi.ssl,javax.script,javax.security.auth,javax.security.auth.callback,javax.security.auth.kerberos,javax.security.auth.login,javax.security.auth.spi,javax.security.auth.x500,javax.security.cert,javax.security.sasl,javax.sound.midi,javax.sound.midi.spi,javax.sound.sampled,javax.sound.sampled.spi,javax.sql,javax.sql.rowset,javax.sql.rowset.serial,javax.sql.rowset.spi,javax.swing,javax.swing.border,javax.swing.colorchooser,javax.swing.event,javax.swing.filechooser,javax.swing.plaf,javax.swing.plaf.basic,javax.swing.plaf.metal,javax.swing.plaf.multi,javax.swing.plaf.synth,javax.swing.table,javax.swing.text,javax.swing.text.html,javax.swing.text.html.parser,javax.swing.text.rtf,javax.swing.tree,javax.swing.undo,javax.tools,javax.xml,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.bind.util,javax.xml.crypto,javax.xml.crypto.dom,javax.xml.crypto.dsig,javax.xml.crypto.dsig.dom,javax.xml.crypto.dsig.keyinfo,javax.xml.crypto.dsig.spec,javax.xml.datatype,javax.xml.namespace,javax.xml.parsers,javax.xml.soap,javax.xml.stream,javax.xml.stream.events,javax.xml.stream.util,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stax,javax.xml.transform.stream,javax.xml.validation,javax.xml.ws,javax.xml.ws.handler,javax.xml.ws.handler.soap,javax.xml.ws.http,javax.xml.ws.soap,javax.xml.ws.spi,javax.xml.xpath,org.ietf.jgss,org.omg.CORBA,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA.TypeCodePackage,org.omg.CORBA.portable,org.omg.CORBA_2_3,org.omg.CORBA_2_3.portable,org.omg.CosNaming,org.omg.CosNaming.NamingContextExtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.Dynamic,org.omg.DynamicAny,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage,org.omg.IOP,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage,org.omg.Messaging,org.omg.PortableInterceptor,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.PortableServer,org.omg.PortableServer.CurrentPackage,org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.ServantLocatorPackage,org.omg.PortableServer.portable,org.omg.SendingContext,org.omg.stub.java.rmi,org.w3c.dom,org.w3c.dom.bootstrap,org.w3c.dom.css,org.w3c.dom.events,org.w3c.dom.html,org.w3c.dom.ls,org.w3c.dom.ranges,org.w3c.dom.stylesheets,org.w3c.dom.traversal,org.w3c.dom.views,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers"), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // Bundles mavenBundle("org.apache.aries", "org.apache.aries.util").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.transaction", "org.apache.aries.transaction.manager").versionAsInProject(), mavenBundle("org.osgi", "org.osgi.enterprise").versionAsInProject(), mavenBundle("org.apache.aries.ejb", "org.apache.aries.ejb.openejb.extender").versionAsInProject(), mavenBundle("org.apache.openejb", "openejb-core").versionAsInProject(), mavenBundle("org.apache.openejb", "openejb-api").versionAsInProject(), mavenBundle("org.apache.openejb", "openejb-javaagent").versionAsInProject(), mavenBundle("org.apache.openejb", "openejb-jee").versionAsInProject(), mavenBundle("org.apache.openejb", "openejb-loader").versionAsInProject(), mavenBundle("org.apache.openwebbeans", "openwebbeans-impl").versionAsInProject(), mavenBundle("org.apache.openwebbeans", "openwebbeans-spi").versionAsInProject(), mavenBundle("org.apache.openwebbeans", "openwebbeans-ee").versionAsInProject(), mavenBundle("org.apache.openwebbeans", "openwebbeans-ejb").versionAsInProject(), mavenBundle("org.apache.openwebbeans", "openwebbeans-web").versionAsInProject(), mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.javassist").versionAsInProject(), mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.wsdl4j-1.6.1").versionAsInProject(), mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jaxb-impl").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-annotation_1.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-ejb_3.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jcdi_1.0_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-el_2.2_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jaxrpc_1.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-atinject_1.0_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-servlet_3.0_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jsp_2.2_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-interceptor_1.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-saaj_1.3_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-activation_1.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-j2ee-management_1.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jpa_2.0_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.6_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jacc_1.4_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-validation_1.0_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jaxrs_1.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-ws-metadata_2.0_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jaspic_1.0_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jaxb_2.2_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-stax-api_1.2_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jaxws_2.2_spec").versionAsInProject(), // JMS is non optional if *any* EJBs are going to work, not just ones that use it :/ mavenBundle("org.apache.geronimo.specs", "geronimo-jms_1.1_spec").versionAsInProject(), mavenBundle("commons-cli", "commons-cli").versionAsInProject(), mavenBundle("commons-lang", "commons-lang").versionAsInProject(), mavenBundle("commons-beanutils", "commons-beanutils").versionAsInProject(), mavenBundle("commons-collections", "commons-collections").versionAsInProject(), mavenBundle("org.apache.geronimo.components", "geronimo-connector").versionAsInProject(), mavenBundle("org.apache.geronimo.components", "geronimo-transaction").versionAsInProject(), mavenBundle("org.apache.geronimo.bundles", "scannotation").versionAsInProject(), mavenBundle("org.apache.xbean", "xbean-asm-shaded").versionAsInProject(), mavenBundle("org.apache.xbean", "xbean-finder-shaded").versionAsInProject(), mavenBundle("org.apache.xbean", "xbean-naming").versionAsInProject(), mavenBundle("org.apache.xbean", "xbean-reflect").versionAsInProject(), mavenBundle("org.hsqldb", "hsqldb").versionAsInProject(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject() ); } protected void addToZip(ZipOutputStream zos, String src) throws IOException { addToZip(zos, src, src); } protected void addToZip(ZipOutputStream zos, String src, String outLocation) throws IOException { zos.putNextEntry(new ZipEntry(outLocation)); IOUtils.copy(getClass().getClassLoader(). getResourceAsStream(src), zos); zos.closeEntry(); } }
8,995
0
Create_ds/aries/ejb/openejb-extender-itest/src/test/java/org/apache/aries/ejb/openejb/extender
Create_ds/aries/ejb/openejb-extender-itest/src/test/java/org/apache/aries/ejb/openejb/extender/itest/AdvancedEJBBundleTest.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.ejb.openejb.extender.itest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.ops4j.pax.exam.CoreOptions.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.zip.ZipOutputStream; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceContextType; import javax.transaction.TransactionSynchronizationRegistry; import javax.transaction.UserTransaction; import org.apache.aries.jpa.container.PersistenceUnitConstants; import org.apache.aries.jpa.container.context.PersistenceContextProvider; import org.junit.Ignore; 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; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import beans.integration.Tx; import beans.integration.impl.JPASingleton; import beans.jpa.Laptop; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class AdvancedEJBBundleTest extends AbstractOpenEJBTest { @Configuration public static Option[] jpaConfig() { return options( mavenBundle("org.apache.derby", "derby").versionAsInProject(), mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.api").versionAsInProject(), mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container").versionAsInProject(), mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container.context").versionAsInProject(), mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.serp").versionAsInProject(), mavenBundle("org.apache.openjpa", "openjpa").versionAsInProject(), mavenBundle("commons-pool", "commons-pool").versionAsInProject() ); } @Test @Ignore public void testTransactionalEJB() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "TX_MANIFEST.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "beans/integration/impl/TxSingleton.class"); addToZip(zos, "beans/integration/Tx.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); Object bean = context().getService(context().getServiceReference(Tx.class.getName())); UserTransaction ut = context().getService(UserTransaction.class); Method no = bean.getClass().getMethod("getNoTransactionId"); Method maybe = bean.getClass().getMethod("getMaybeTransactionId"); Method tx = bean.getClass().getMethod("getTransactionId"); Method newTx = bean.getClass().getMethod("getNewTransactionId"); assertNull(no.invoke(bean)); assertNull(maybe.invoke(bean)); assertNotNull(tx.invoke(bean)); assertNotNull(newTx.invoke(bean)); ut.begin(); try { Object key = context().getService(TransactionSynchronizationRegistry.class). getTransactionKey(); assertNotNull(key); assertNull(no.invoke(bean)); assertSame(key, maybe.invoke(bean)); assertSame(key, tx.invoke(bean)); Object o = newTx.invoke(bean); assertNotNull(o); assertNotSame(key, o); } finally { ut.commit(); } test.stop(); } finally { test.uninstall(); } } @Test @Ignore public void testJPAContextSharing() throws Exception { System.setProperty("openejb.validation.output.level", "VERBOSE"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "JPA_MANIFEST.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "persistence.xml", "META-INF/persistence.xml"); addToZip(zos, "beans/integration/impl/JPASingleton.class"); addToZip(zos, "beans/jpa/Laptop.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); PersistenceContextProvider provider = context().getService(PersistenceContextProvider.class); HashMap<String, Object> props = new HashMap<String, Object>(); props.put(PersistenceContextProvider.PERSISTENCE_CONTEXT_TYPE, PersistenceContextType.TRANSACTION); provider.registerContext("ejb-test", context().getBundle(), props); Object bean = context().getService(context().getServiceReference(JPASingleton.class.getName())); UserTransaction ut = context().getService(UserTransaction.class); Method m = bean.getClass().getMethod("editEntity", String.class); EntityManager em = context().getService(EntityManagerFactory.class, "(&(osgi.unit.name=ejb-test)(" + PersistenceUnitConstants.CONTAINER_MANAGED_PERSISTENCE_UNIT + "=true)" + "(" + PersistenceContextProvider.PROXY_FACTORY_EMF_ATTRIBUTE + "=*))").createEntityManager(); ut.begin(); try { Object e = test.loadClass(Laptop.class.getName()).newInstance(); e.getClass().getMethod("setSerialNumber", String.class).invoke(e, "ABC123"); e.getClass().getMethod("setNumberOfCores", int.class).invoke(e, 1); em.persist(e); m.invoke(bean, "ABC123"); assertEquals(4, e.getClass().getMethod("getNumberOfCores").invoke(e)); assertEquals(Integer.MAX_VALUE, e.getClass().getMethod("getHardDiskSize").invoke(e)); } finally { ut.commit(); } test.stop(); } finally { test.uninstall(); } } }
8,996
0
Create_ds/aries/ejb/openejb-extender-itest/src/test/java/org/apache/aries/ejb/openejb/extender
Create_ds/aries/ejb/openejb-extender-itest/src/test/java/org/apache/aries/ejb/openejb/extender/itest/EJBBundleTest.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.ejb.openejb.extender.itest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.zip.ZipOutputStream; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; import beans.StatelessSessionBean; import beans.xml.LocalIface; import beans.xml.RemoteIface; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class EJBBundleTest extends AbstractOpenEJBTest { private void assertXML(Bundle test, boolean exists) throws Exception { ServiceReference[] local = context().getAllServiceReferences(LocalIface.class.getName(), "(&(ejb.name=XML)(ejb.type=Singleton))"); if (exists) { assertNotNull(local); assertEquals(1, local.length); Object svc = context().getService(local[0]); assertNotNull(svc); assertEquals("A Local Call", svc.getClass().getMethod("getLocalString").invoke(svc)); } else { assertNull(local); } ServiceReference[] remote = context().getAllServiceReferences(RemoteIface.class.getName(), "(&(ejb.name=XML)(ejb.type=Singleton))"); if (exists) { assertNotNull(remote); assertEquals(1, remote.length); Object svc = context().getService(remote[0]); assertNotNull(svc); assertEquals("A Remote Call", svc.getClass().getMethod("getRemoteString").invoke(svc)); } else { assertNull(remote); } } private void assertAnnotations(Bundle test, boolean exists) throws Exception { ServiceReference[] stateless = context().getAllServiceReferences(StatelessSessionBean.class.getName(), "(&(ejb.name=Annotated)(ejb.type=Stateless))"); if (exists) { assertNotNull(stateless); assertEquals(1, stateless.length); Object svc = context().getService(stateless[0]); assertNotNull(svc); assertEquals("A Stateless Call", svc.getClass().getMethod("getStatelessString").invoke(svc)); } else { assertNull(stateless); } } @Test public void testEJBJARInZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_1.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "META-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, true); test.stop(); assertXML(test, false); } finally { test.uninstall(); } } @Test public void testEJBJARAndAnnotatedInZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_1.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "META-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class"); addToZip(zos, "beans/StatelessSessionBean.class"); addToZip(zos, "beans/StatefulSessionBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, true); assertAnnotations(test, true); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testAnnotatedOnlyInZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_1.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class"); addToZip(zos, "beans/StatelessSessionBean.class"); addToZip(zos, "beans/StatefulSessionBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, false); assertAnnotations(test, true); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testEJBJARAndAnnotatedNotOnClasspathInZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_2.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "META-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class", "yes/beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class", "yes/beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class", "yes/beans/xml/XMLBean.class"); addToZip(zos, "beans/StatelessSessionBean.class", "no/beans/StatelessSessionBean.class"); addToZip(zos, "beans/StatefulSessionBean.class", "no/beans/StatefulSessionBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, true); assertAnnotations(test, false); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testEJBJARAndAnnotatedOnClasspathInZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_2.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "META-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class", "yes/beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class", "yes/beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class", "yes/beans/xml/XMLBean.class"); addToZip(zos, "beans/StatelessSessionBean.class", "yes/beans/StatelessSessionBean.class"); addToZip(zos, "beans/StatefulSessionBean.class", "yes/beans/StatefulSessionBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, true); assertAnnotations(test, true); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testEJBJARInWebZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_3.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "WEB-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, true); assertAnnotations(test, false); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testEJBJARInWrongPlaceWebZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_3.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "META-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, false); assertAnnotations(test, false); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testEJBJARAndAnnotatedInWebZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_3.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "WEB-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class"); addToZip(zos, "beans/StatelessSessionBean.class"); addToZip(zos, "beans/StatefulSessionBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, true); assertAnnotations(test, true); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testAnnotatedOnlyInWebZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_3.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class"); addToZip(zos, "beans/StatelessSessionBean.class"); addToZip(zos, "beans/StatefulSessionBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, false); assertAnnotations(test, true); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testEJBJARAndAnnotatedNotOnClasspathInWebZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_4.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "WEB-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class", "yes/beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class", "yes/beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class", "yes/beans/xml/XMLBean.class"); addToZip(zos, "beans/StatelessSessionBean.class", "no/beans/StatelessSessionBean.class"); addToZip(zos, "beans/StatefulSessionBean.class", "no/beans/StatefulSessionBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, true); assertAnnotations(test, false); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } @Test public void testEJBJARAndAnnotatedOnClasspathInWebZip() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); addToZip(zos, "MANIFEST_4.MF", "META-INF/MANIFEST.MF"); addToZip(zos, "ejb-jar.xml", "WEB-INF/ejb-jar.xml"); addToZip(zos, "beans/xml/LocalIface.class", "yes/beans/xml/LocalIface.class"); addToZip(zos, "beans/xml/RemoteIface.class", "yes/beans/xml/RemoteIface.class"); addToZip(zos, "beans/xml/XMLBean.class", "yes/beans/xml/XMLBean.class"); addToZip(zos, "beans/StatelessSessionBean.class", "yes/beans/StatelessSessionBean.class"); addToZip(zos, "beans/StatefulSessionBean.class", "yes/beans/StatefulSessionBean.class"); zos.close(); Bundle test = context().installBundle("", new ByteArrayInputStream(baos.toByteArray())); try { test.start(); assertXML(test, true); assertAnnotations(test, true); test.stop(); assertXML(test, false); assertAnnotations(test, false); } finally { test.uninstall(); } } }
8,997
0
Create_ds/aries/ejb/openejb-extender-itest/src/test/java
Create_ds/aries/ejb/openejb-extender-itest/src/test/java/beans/StatefulSessionBean.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 beans; import javax.ejb.Stateful; @Stateful(name="Stateful") public class StatefulSessionBean { }
8,998
0
Create_ds/aries/ejb/openejb-extender-itest/src/test/java
Create_ds/aries/ejb/openejb-extender-itest/src/test/java/beans/StatelessSessionBean.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 beans; import javax.ejb.Stateless; @Stateless(name="Annotated") public class StatelessSessionBean { public String getStatelessString() { return "A Stateless Call"; } }
8,999