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/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AriesProvisionDependenciesDirective.java | /*
* 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.subsystem.core.archive;
/**
* Aries specific implementation directive that can be added to the
* SubsystemSymbolicName header to defer provision of dependencies to start time
* (refer to jira aries-1383 for fuller description of this behavior).
* <p>
* The legal values for the directives are "start" and "install". The default is
* install.
* <p>
* There are exactly two instances of this type constructed. Statically
* references are
* {@code AriesProvisionDependenciesDirective.PROVISION_DEPENDENCIES_AT_INSTALL}
* or
* {@code AriesProvisionDependenciesDirective.PROVISION_DEPENDENCIES_AT_START}.
*/
public class AriesProvisionDependenciesDirective extends AbstractDirective {
public static final String NAME = "apache-aries-provision-dependencies";
public static final String VALUE_INSTALL = "install";
public static final String VALUE_RESOLVE = "resolve";
public static final AriesProvisionDependenciesDirective INSTALL = new AriesProvisionDependenciesDirective(VALUE_INSTALL);
public static final AriesProvisionDependenciesDirective RESOLVE = new AriesProvisionDependenciesDirective(VALUE_RESOLVE);
public static final AriesProvisionDependenciesDirective DEFAULT = INSTALL;
public static AriesProvisionDependenciesDirective getInstance(String value) {
if (VALUE_INSTALL.equals(value))
return INSTALL;
if (VALUE_RESOLVE.equals(value))
return RESOLVE;
throw new IllegalArgumentException(value);
}
private AriesProvisionDependenciesDirective(String value) {
super(NAME, value);
}
public String getProvisionDependencies() {
return getValue();
}
public boolean isInstall() {
return this == INSTALL;
}
public boolean isResolve() {
return this == RESOLVE;
}
}
| 8,600 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/GenericAttribute.java | /*
* 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.subsystem.core.archive;
public class GenericAttribute extends AbstractAttribute {
public GenericAttribute(String name, String value) {
super(name, value);
}
}
| 8,601 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AbstractParameter.java | /*
* 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.subsystem.core.archive;
public abstract class AbstractParameter implements Parameter {
protected final String name;
protected final Object value;
public AbstractParameter(String name, Object value) {
if (name == null || value == null) {
throw new NullPointerException();
}
this.name = name;
this.value = value;
}
@Override
public String getName() {
return name;
}
@Override
public Object getValue() {
return value;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + value.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof AbstractParameter)) {
return false;
}
AbstractParameter that = (AbstractParameter)o;
return that.name.equals(this.name)
&& that.value.equals(this.value);
}
}
| 8,602 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/DynamicImportPackageHeader.java | /*
* 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.subsystem.core.archive;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.resource.Resource;
public class DynamicImportPackageHeader extends AbstractClauseBasedHeader<DynamicImportPackageHeader.Clause> implements RequirementHeader<DynamicImportPackageHeader.Clause> {
public static class Clause extends AbstractClause {
public Clause(String clause) {
super(
parsePath(clause, Patterns.WILDCARD_NAMES, true),
parseParameters(clause, true),
generateDefaultParameters(
VersionRangeAttribute.DEFAULT_VERSION));
}
public Collection<String> getPackageNames() {
return Arrays.asList(path.split(";"));
}
public VersionRangeAttribute getVersionRangeAttribute() {
return (VersionRangeAttribute)parameters.get(Constants.VERSION_ATTRIBUTE);
}
public List<DynamicImportPackageRequirement> toRequirements(Resource resource) {
Collection<String> pkgs = getPackageNames();
List<DynamicImportPackageRequirement> result = new ArrayList<DynamicImportPackageRequirement>(pkgs.size());
for (String pkg : pkgs) {
result.add(new DynamicImportPackageRequirement(pkg, this, resource));
}
return result;
}
}
public static final String ATTRIBUTE_BUNDLE_SYMBOLICNAME = PackageNamespace.CAPABILITY_BUNDLE_SYMBOLICNAME_ATTRIBUTE;
public static final String ATTRIBUTE_BUNDLE_VERSION = PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE;
public static final String ATTRIBUTE_VERSION = PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE;
public static final String NAME = Constants.DYNAMICIMPORT_PACKAGE;
public DynamicImportPackageHeader(Collection<Clause> clauses) {
super(clauses);
}
public DynamicImportPackageHeader(String value) {
super(
value,
new ClauseFactory<Clause>() {
@Override
public Clause newInstance(String clause) {
return new Clause(clause);
}
});
}
@Override
public String getName() {
return Constants.IMPORT_PACKAGE;
}
@Override
public String getValue() {
return toString();
}
@Override
public List<DynamicImportPackageRequirement> toRequirements(Resource resource) {
Collection<Clause> clauses = getClauses();
List<DynamicImportPackageRequirement> result = new ArrayList<DynamicImportPackageRequirement>(clauses.size());
for (Clause clause : clauses) {
result.addAll(clause.toRequirements(resource));
}
return result;
}
}
| 8,603 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/Attribute.java | /*
* 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.subsystem.core.archive;
public interface Attribute extends Parameter {
public StringBuilder appendToFilter(StringBuilder builder);
}
| 8,604 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemVersionHeader.java | /*
* 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.subsystem.core.archive;
import org.osgi.framework.Version;
public class SubsystemVersionHeader extends VersionHeader {
public static final String DEFAULT_VALUE = Version.emptyVersion.toString();
// TODO Add to constants.
public static final String NAME = "Subsystem-Version";
public static final SubsystemVersionHeader DEFAULT = new SubsystemVersionHeader();
public SubsystemVersionHeader() {
this(DEFAULT_VALUE);
}
public SubsystemVersionHeader(String value) {
super(NAME, value);
}
public SubsystemVersionHeader(Version value) {
super(NAME, value);
}
}
| 8,605 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemTypeHeader.java | /*
* 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.subsystem.core.archive;
import java.util.Collection;
import java.util.Collections;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemTypeHeader extends AbstractClauseBasedHeader<SubsystemTypeHeader.Clause> {
public static class Clause extends AbstractClause {
private static final Collection<Parameter> defaultParameters = generateDefaultParameters(
ProvisionPolicyDirective.REJECT_DEPENDENCIES);
public Clause(String clause) {
super(
parsePath(clause, Patterns.SUBSYSTEM_TYPE, false),
parseParameters(clause, false),
defaultParameters);
}
public AriesProvisionDependenciesDirective getProvisionDependenciesDirective() {
return (AriesProvisionDependenciesDirective)getDirective(DIRECTIVE_PROVISION_DEPENDENCIES);
}
public ProvisionPolicyDirective getProvisionPolicyDirective() {
return (ProvisionPolicyDirective)getDirective(DIRECTIVE_PROVISION_POLICY);
}
public String getType() {
return path;
}
}
public static final String DIRECTIVE_PROVISION_DEPENDENCIES = AriesProvisionDependenciesDirective.NAME;
public static final String DIRECTIVE_PROVISION_POLICY = ProvisionPolicyDirective.NAME;
public static final String NAME = SubsystemConstants.SUBSYSTEM_TYPE;
public static final String ARIES_PROVISION_DEPENDENCIES_INSTALL = AriesProvisionDependenciesDirective.VALUE_INSTALL;
public static final String ARIES_PROVISION_DEPENDENCIES_RESOLVE = AriesProvisionDependenciesDirective.VALUE_RESOLVE;
public static final String PROVISION_POLICY_ACCEPT_DEPENDENCIES = ProvisionPolicyDirective.VALUE_ACCEPT_DEPENDENCIES;
public static final String PROVISION_POLICY_REJECT_DEPENDENCIES = ProvisionPolicyDirective.VALUE_REJECT_DEPENDENCIES;
public static final String TYPE_APPLICATION = SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION;
public static final String TYPE_COMPOSITE = SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE;
public static final String TYPE_FEATURE = SubsystemConstants.SUBSYSTEM_TYPE_FEATURE;
public static final SubsystemTypeHeader DEFAULT = new SubsystemTypeHeader(TYPE_APPLICATION);
public SubsystemTypeHeader(Clause clause) {
super(Collections.singleton(clause));
}
public SubsystemTypeHeader(String value) {
super(
value,
new ClauseFactory<Clause>() {
@Override
public Clause newInstance(String clause) {
return new Clause(clause);
}
});
}
public Clause getClause() {
return clauses.iterator().next();
}
@Override
public String getName() {
return NAME;
}
public AriesProvisionDependenciesDirective getAriesProvisionDependenciesDirective() {
return clauses.iterator().next().getProvisionDependenciesDirective();
}
public ProvisionPolicyDirective getProvisionPolicyDirective() {
return clauses.iterator().next().getProvisionPolicyDirective();
}
public String getType() {
return clauses.iterator().next().getType();
}
@Override
public String getValue() {
return toString();
}
public boolean isApplication() {
return this == DEFAULT || TYPE_APPLICATION.equals(getType());
}
public boolean isComposite() {
return TYPE_COMPOSITE.equals(getType());
}
public boolean isFeature() {
return TYPE_FEATURE.equals(getType());
}
}
| 8,606 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemSymbolicNameHeader.java | /*
* 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.subsystem.core.archive;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemSymbolicNameHeader extends SymbolicNameHeader {
public static final String NAME = SubsystemConstants.SUBSYSTEM_SYMBOLICNAME;
public SubsystemSymbolicNameHeader(String value) {
super(NAME, value);
}
}
| 8,607 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/RequireBundleHeader.java | /*
* 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.subsystem.core.archive;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.aries.subsystem.core.capabilityset.SimpleFilter;
import org.osgi.framework.Constants;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
public class RequireBundleHeader extends AbstractClauseBasedHeader<RequireBundleHeader.Clause>implements RequirementHeader<RequireBundleHeader.Clause> {
public static class Clause extends AbstractClause {
public static final String ATTRIBUTE_BUNDLEVERSION = Constants.BUNDLE_VERSION_ATTRIBUTE;
public static final String DIRECTIVE_RESOLUTION = Constants.RESOLUTION_DIRECTIVE;
public static final String DIRECTIVE_VISIBILITY = Constants.VISIBILITY_DIRECTIVE;
private static final Collection<Parameter> defaultParameters = generateDefaultParameters(
VersionRangeAttribute.DEFAULT_BUNDLEVERSION,
VisibilityDirective.PRIVATE,
ResolutionDirective.MANDATORY);
public Clause(String clause) {
super(
parsePath(clause, Patterns.SYMBOLIC_NAME, false),
parseParameters(clause, true),
defaultParameters);
}
public Clause(String path, Map<String, Parameter> parameters, Collection<Parameter> defaultParameters) {
super(path, parameters, defaultParameters);
}
public static Clause valueOf(Requirement requirement) {
String namespace = requirement.getNamespace();
if (!RequireBundleRequirement.NAMESPACE.equals(namespace)) {
throw new IllegalArgumentException("Invalid namespace:" + namespace);
}
Map<String, Parameter> parameters = new HashMap<String, Parameter>();
String filter = null;
Map<String, String> directives = requirement.getDirectives();
for (Map.Entry<String, String> entry : directives.entrySet()) {
String key = entry.getKey();
if (RequireBundleRequirement.DIRECTIVE_FILTER.equals(key)) {
filter = entry.getValue();
}
else {
parameters.put(key, DirectiveFactory.createDirective(key, entry.getValue()));
}
}
Map<String, List<SimpleFilter>> attributes = SimpleFilter.attributes(filter);
String path = null;
for (Map.Entry<String, List<SimpleFilter>> entry : attributes.entrySet()) {
String key = entry.getKey();
List<SimpleFilter> value = entry.getValue();
if (RequireBundleRequirement.NAMESPACE.equals(key)) {
path = String.valueOf(value.get(0).getValue());
}
else if (ATTRIBUTE_BUNDLEVERSION.equals(key)) {
parameters.put(key, new VersionRangeAttribute(key, parseVersionRange(value)));
}
else {
parameters.put(key, AttributeFactory.createAttribute(key,
String.valueOf(value.get(0).getValue())));
}
}
return new Clause(path, parameters, defaultParameters);
}
@Override
public Attribute getAttribute(String name) {
Parameter result = parameters.get(name);
if (result instanceof Attribute) {
return (Attribute)result;
}
return null;
}
@Override
public Collection<Attribute> getAttributes() {
ArrayList<Attribute> attributes = new ArrayList<Attribute>(parameters.size());
for (Parameter parameter : parameters.values()) {
if (parameter instanceof Attribute) {
attributes.add((Attribute)parameter);
}
}
attributes.trimToSize();
return attributes;
}
@Override
public Directive getDirective(String name) {
Parameter result = parameters.get(name);
if (result instanceof Directive) {
return (Directive)result;
}
return null;
}
@Override
public Collection<Directive> getDirectives() {
ArrayList<Directive> directives = new ArrayList<Directive>(parameters.size());
for (Parameter parameter : parameters.values()) {
if (parameter instanceof Directive) {
directives.add((Directive)parameter);
}
}
directives.trimToSize();
return directives;
}
public String getSymbolicName() {
return path;
}
public RequireBundleRequirement toRequirement(Resource resource) {
return new RequireBundleRequirement(this, resource);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder()
.append(getPath());
for (Parameter parameter : getParameters()) {
builder.append(';').append(parameter);
}
return builder.toString();
}
}
public static final String NAME = Constants.REQUIRE_BUNDLE;
public RequireBundleHeader(Collection<Clause> clauses) {
super(clauses);
}
public RequireBundleHeader(String value) {
super(
value,
new ClauseFactory<Clause>() {
@Override
public Clause newInstance(String clause) {
return new Clause(clause);
}
});
}
@Override
public String getName() {
return NAME;
}
@Override
public String getValue() {
return toString();
}
@Override
public List<RequireBundleRequirement> toRequirements(Resource resource) {
List<RequireBundleRequirement> requirements = new ArrayList<RequireBundleRequirement>(clauses.size());
for (Clause clause : clauses)
requirements.add(clause.toRequirement(resource));
return requirements;
}
}
| 8,608 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/FilterDirective.java | /*
* 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.subsystem.core.archive;
import org.apache.aries.subsystem.core.capabilityset.SimpleFilter;
import org.osgi.framework.Constants;
public class FilterDirective extends AbstractDirective {
public static final String NAME = Constants.FILTER_DIRECTIVE;
private final SimpleFilter filter;
public FilterDirective(String value) {
super(NAME, value);
filter = SimpleFilter.parse(value);
}
@Override
public String toString() {
return new StringBuilder()
.append(getName())
.append(":=\"")
.append(getValue())
.append('\"')
.toString();
}
@Override
public int hashCode() {
return 31 * 17 + filter.hashCode();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof FilterDirective)) {
return false;
}
FilterDirective that = (FilterDirective)o;
return that.filter.equals(this.filter);
}
}
| 8,609 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ExportPackageCapability.java | /*
* 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.subsystem.core.archive;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.internal.AbstractCapability;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.resource.Resource;
public class ExportPackageCapability extends AbstractCapability {
public static final String NAMESPACE = PackageNamespace.PACKAGE_NAMESPACE;
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Map<String, String> directives = new HashMap<String, String>();
private final Resource resource;
public ExportPackageCapability(String packageName, Collection<Parameter> parameters, Resource resource) {
attributes.put(NAMESPACE, packageName);
for (Parameter parameter : parameters) {
if (parameter instanceof Attribute)
attributes.put(parameter.getName(), parameter.getValue());
else
directives.put(parameter.getName(), ((Directive)parameter).getValue());
}
this.resource = resource;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
@Override
public Map<String, String> getDirectives() {
return Collections.unmodifiableMap(directives);
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,610 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemImportServiceHeader.java | /*
* 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.subsystem.core.archive;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.aries.subsystem.core.capabilityset.SimpleFilter;
import org.osgi.framework.Constants;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemImportServiceHeader extends AbstractClauseBasedHeader<SubsystemImportServiceHeader.Clause> implements RequirementHeader<SubsystemImportServiceHeader.Clause> {
public static class Clause extends AbstractClause {
public static final String DIRECTIVE_CARDINALITY = CardinalityDirective.NAME;
public static final String DIRECTIVE_EFFECTIVE = EffectiveDirective.NAME;
public static final String DIRECTIVE_FILTER = FilterDirective.NAME;
public static final String DIRECTIVE_RESOLUTION = ResolutionDirective.NAME;
private static final Collection<Parameter> defaultParameters = generateDefaultParameters(
EffectiveDirective.ACTIVE,
ResolutionDirective.MANDATORY,
CardinalityDirective.SINGLE);
public Clause(String clause) {
super(
parsePath(clause, Patterns.OBJECTCLASS_OR_STAR, false),
parseParameters(clause, false),
defaultParameters);
}
public Clause(String path, Map<String, Parameter> parameters, Collection<Parameter> defaultParameters) {
super(path, parameters, defaultParameters);
}
public static Clause valueOf(Requirement requirement) {
String namespace = requirement.getNamespace();
if (!SubsystemImportServiceRequirement.NAMESPACE.equals(namespace)) {
throw new IllegalArgumentException("Invalid namespace:" + namespace);
}
Map<String, Parameter> parameters = new HashMap<String, Parameter>();
String filter = null;
Map<String, String> directives = requirement.getDirectives();
for (Map.Entry<String, String> entry : directives.entrySet()) {
String key = entry.getKey();
if (SubsystemImportServiceRequirement.DIRECTIVE_FILTER.equals(key)) {
filter = entry.getValue();
}
else {
parameters.put(key, DirectiveFactory.createDirective(key, entry.getValue()));
}
}
Map<String, List<SimpleFilter>> attributes = SimpleFilter.attributes(filter);
String path = String.valueOf(attributes.remove(Constants.OBJECTCLASS).get(0).getValue());
Map<String, Object> map = new HashMap<String, Object>(attributes.size());
for (Map.Entry<String, List<SimpleFilter>> entry : attributes.entrySet()) {
map.put(entry.getKey(), entry.getValue().get(0).getValue());
}
if (!map.isEmpty()) {
parameters.put(
SubsystemImportServiceRequirement.DIRECTIVE_FILTER,
DirectiveFactory.createDirective(
SubsystemImportServiceRequirement.DIRECTIVE_FILTER,
SimpleFilter.convert(map).toString()));
}
return new Clause(path, parameters, defaultParameters);
}
public SubsystemImportServiceRequirement toRequirement(Resource resource) {
return new SubsystemImportServiceRequirement(this, resource);
}
}
public static final String NAME = SubsystemConstants.SUBSYSTEM_IMPORTSERVICE;
public SubsystemImportServiceHeader(String value) {
super(
value,
new ClauseFactory<Clause>() {
@Override
public Clause newInstance(String clause) {
return new Clause(clause);
}
});
}
public SubsystemImportServiceHeader(Collection<Clause> clauses) {
super(clauses);
}
@Override
public String getName() {
return NAME;
}
@Override
public String getValue() {
return toString();
}
@Override
public List<SubsystemImportServiceRequirement> toRequirements(Resource resource) {
List<SubsystemImportServiceRequirement> requirements = new ArrayList<SubsystemImportServiceRequirement>(clauses.size());
for (Clause clause : clauses)
requirements.add(clause.toRequirement(resource));
return requirements;
}
}
| 8,611 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/PreferredProviderRequirement.java | /*
* 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.subsystem.core.archive;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.internal.AbstractRequirement;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
public class PreferredProviderRequirement extends AbstractRequirement {
public static final String DIRECTIVE_FILTER = IdentityNamespace.REQUIREMENT_FILTER_DIRECTIVE;
public static final String NAMESPACE = IdentityNamespace.IDENTITY_NAMESPACE;
private final Map<String, String> directives = new HashMap<String, String>();
private final Resource resource;
public PreferredProviderRequirement(
PreferredProviderHeader.Clause clause, Resource resource) {
StringBuilder builder = new StringBuilder("(&(")
.append(NAMESPACE).append('=')
.append(clause.getSymbolicName()).append(')');
for (Attribute attribute : clause.getAttributes())
attribute.appendToFilter(builder);
directives.put(DIRECTIVE_FILTER, builder.append(')').toString());
this.resource = resource;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.emptyMap();
}
@Override
public Map<String, String> getDirectives() {
return Collections.unmodifiableMap(directives);
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,612 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AbstractClauseBasedHeader.java | /*
* 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.subsystem.core.archive;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.subsystem.core.capabilityset.SimpleFilter;
import org.osgi.framework.VersionRange;
public abstract class AbstractClauseBasedHeader<C extends Clause> implements Header<C> {
protected static VersionRange parseVersionRange(List<SimpleFilter> filters) {
SimpleFilter floor = null;
SimpleFilter ceiling = null;
for (SimpleFilter filter : filters) {
switch (filter.getOperation()) {
case SimpleFilter.EQ:
case SimpleFilter.GTE:
floor = filter;
break;
case SimpleFilter.LTE:
ceiling = filter;
break;
case SimpleFilter.NOT:
SimpleFilter negated = ((List<SimpleFilter>)filter.getValue()).get(0);
switch (negated.getOperation()) {
case SimpleFilter.EQ:
case SimpleFilter.GTE:
ceiling = filter;
break;
case SimpleFilter.LTE:
floor = filter;
break;
default:
throw new IllegalArgumentException("Invalid filter: " + filter);
}
break;
case SimpleFilter.PRESENT:
/* This can happen with version ranges of the form
* (1.5.0,2.0.0). The filter form will be
* (&(version=*)(!(version<=1.5.0))(!(version>=2.0.0)). The
* presence operator is required because an absent version
* attribute would otherwise match. These should simply be
* ignored for the purposes of converting back into a
* version range.
*/
break;
default:
throw new IllegalArgumentException("Invalid filter: " + filter);
}
}
if (ceiling == null) {
return new VersionRange(String.valueOf(floor.getValue()));
}
String range = new StringBuilder()
.append(floor.getOperation() == SimpleFilter.NOT ? '(' : '[')
.append(floor.getOperation() == SimpleFilter.NOT ?
((List<SimpleFilter>)floor.getValue()).get(0).getValue() : floor.getValue())
.append(',')
.append(ceiling.getOperation() == SimpleFilter.NOT ?
((List<SimpleFilter>)ceiling.getValue()).get(0).getValue() : ceiling.getValue())
.append(ceiling.getOperation() == SimpleFilter.NOT ? ')' : ']')
.toString();
return new VersionRange(range);
}
private static <C> Collection<C> computeClauses(String header, ClauseFactory<C> factory) {
Collection<String> clauseStrs = new ClauseTokenizer(header).getClauses();
Set<C> clauses = new HashSet<C>(clauseStrs.size());
for (String clause : clauseStrs) {
clauses.add(factory.newInstance(clause));
}
return clauses;
}
public interface ClauseFactory<C> {
public C newInstance(String clause);
}
protected final Set<C> clauses;
public AbstractClauseBasedHeader(Collection<C> clauses) {
if (clauses.isEmpty()) {
throw new IllegalArgumentException("No clauses");
}
this.clauses = Collections.synchronizedSet(new HashSet<C>(clauses));
}
public AbstractClauseBasedHeader(String header, ClauseFactory<C> factory) {
this(computeClauses(header, factory));
}
@Override
public final Collection<C> getClauses() {
return Collections.unmodifiableCollection(clauses);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getName().hashCode();
result = 31 * result + clauses.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof AbstractClauseBasedHeader)) {
return false;
}
AbstractClauseBasedHeader<?> that = (AbstractClauseBasedHeader<?>)o;
return that.getName().equals(this.getName())
&& that.clauses.equals(this.clauses);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (C clause : getClauses()) {
builder.append(clause).append(',');
}
// Remove the trailing comma. Note at least one clause is guaranteed to
// exist.
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
}
| 8,613 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ParameterFactory.java | /*
* 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.subsystem.core.archive;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ParameterFactory {
public static final String QUOTED_STRING = "\"((?:[^\"\r\n\u0000]|\\\\\"|\\\\\\\\)*)\"";
public static final String ARGUMENT = '(' + Grammar.EXTENDED + ")|" + QUOTED_STRING;
private static final String REGEX = '(' + Grammar.EXTENDED + ")(\\:?=)(?:" + ARGUMENT + ')';
private static final Pattern PATTERN = Pattern.compile(REGEX);
public static Parameter create(String parameter) {
Matcher matcher = PATTERN.matcher(parameter);
if (!matcher.matches()) {
throw new IllegalArgumentException("Invalid parameter: " + parameter);
}
String name = matcher.group(1);
String symbol = matcher.group(2);
String value = matcher.group(3);
if (value == null)
value = matcher.group(4);
if (symbol.equals("=")) {
return AttributeFactory.createAttribute(name, value);
}
return DirectiveFactory.createDirective(name, value);
}
}
| 8,614 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemManifestVersionHeader.java | /*
* 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.subsystem.core.archive;
import org.osgi.framework.Version;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemManifestVersionHeader extends VersionHeader {
public static final Version DEFAULT_VALUE = Version.parseVersion("1.0");
public static final String NAME = SubsystemConstants.SUBSYSTEM_MANIFESTVERSION;
public static final SubsystemManifestVersionHeader DEFAULT = new SubsystemManifestVersionHeader();
public SubsystemManifestVersionHeader() {
this(DEFAULT_VALUE);
}
public SubsystemManifestVersionHeader(String value) {
this(Version.parseVersion(value));
}
public SubsystemManifestVersionHeader(Version version) {
super(NAME, version);
if (!version.equals(DEFAULT_VALUE))
throw new IllegalArgumentException(NAME + " must be " + DEFAULT_VALUE);
}
}
| 8,615 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ReferenceDirective.java | /*
* 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.subsystem.core.archive;
public class ReferenceDirective extends AbstractDirective {
public static final String NAME = "reference";
public static final String VALUE_FALSE = Boolean.FALSE.toString();
public static final String VALUE_TRUE = Boolean.TRUE.toString();
public static final ReferenceDirective FALSE = new ReferenceDirective(VALUE_FALSE);
public static final ReferenceDirective TRUE = new ReferenceDirective(VALUE_TRUE);
public ReferenceDirective() {
this(VALUE_TRUE);
}
public static ReferenceDirective getInstance(String value) {
if (VALUE_TRUE.equals(value))
return TRUE;
if (VALUE_FALSE.equals(value))
return FALSE;
throw new IllegalArgumentException("Invalid " + NAME + " directive: " + value);
}
private ReferenceDirective(String value) {
super(NAME, value);
}
public boolean isReferenced() {
return TRUE == this || VALUE_TRUE.equals(getValue());
}
}
| 8,616 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemContentHeader.java | /*
* 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.subsystem.core.archive;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.aries.subsystem.core.internal.ResourceHelper;
import org.osgi.framework.Version;
import org.osgi.framework.VersionRange;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemContentHeader extends AbstractClauseBasedHeader<SubsystemContentHeader.Clause> implements RequirementHeader<SubsystemContentHeader.Clause> {
public static class Clause extends AbstractClause {
public static final String ATTRIBUTE_VERSION = VersionRangeAttribute.NAME_VERSION;
public static final String ATTRIBUTE_TYPE = TypeAttribute.NAME;
public static final String DIRECTIVE_RESOLUTION = ResolutionDirective.NAME;
public static final String DIRECTIVE_STARTORDER = StartOrderDirective.NAME;
private static final Collection<Parameter> defaultParameters = generateDefaultParameters(
// A default value for the type attribute is not included here
// because we need to determine in the constructor whether or
// not it was specified as part of the original value.
// See ARIES-1425.
VersionRangeAttribute.DEFAULT_VERSION,
ResolutionDirective.MANDATORY,
// This is an implementation specific start-order directive
// value. The specification states there is no default value.
new StartOrderDirective("0"));
// Was the type attribute specified as part of the original value?
private final boolean isTypeSpecified;
private final String originalValue;
public Clause(String clause) {
super(
parsePath(clause, Patterns.SYMBOLIC_NAME, false),
parseParameters(clause, true),
defaultParameters);
if (parameters.get(TypeAttribute.NAME) == null) {
// The resource type was not specified.
isTypeSpecified = false;
// Add the default type.
parameters.put(TypeAttribute.NAME, TypeAttribute.DEFAULT);
}
else {
// The resource type was specified.
isTypeSpecified = true;
}
originalValue = clause;
}
public String getSymbolicName() {
return path;
}
public int getStartOrder() {
return ((StartOrderDirective)getDirective(DIRECTIVE_STARTORDER)).getStartOrder();
}
public String getType() {
return ((TypeAttribute)getAttribute(ATTRIBUTE_TYPE)).getType();
}
public VersionRange getVersionRange() {
return ((VersionRangeAttribute)getAttribute(ATTRIBUTE_VERSION)).getVersionRange();
}
public boolean isMandatory() {
return ((ResolutionDirective)getDirective(DIRECTIVE_RESOLUTION)).isMandatory();
}
public boolean isTypeSpecified() {
return isTypeSpecified;
}
public SubsystemContentRequirement toRequirement(Resource resource) {
return new SubsystemContentRequirement(this, resource);
}
@Override
public String toString() {
return originalValue;
}
}
public static final String NAME = SubsystemConstants.SUBSYSTEM_CONTENT;
public static SubsystemContentHeader newInstance(Collection<Resource> resources) {
StringBuilder builder = new StringBuilder();
for (Resource resource : resources) {
appendResource(resource, builder);
builder.append(',');
}
// Remove the trailing comma.
// TODO Intentionally letting the exception propagate since there must be at least one resource.
builder.deleteCharAt(builder.length() - 1);
return new SubsystemContentHeader(builder.toString());
}
private static StringBuilder appendResource(Resource resource, StringBuilder builder) {
String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource);
Version version = ResourceHelper.getVersionAttribute(resource);
String type = ResourceHelper.getTypeAttribute(resource);
builder.append(symbolicName)
.append(';')
.append(Clause.ATTRIBUTE_VERSION)
.append("=\"[")
.append(version.toString())
.append(',')
.append(version.toString())
.append("]\";")
.append(Clause.ATTRIBUTE_TYPE)
.append('=')
.append(type);
return builder;
}
private final String originalValue;
public SubsystemContentHeader(String value) {
super(
value,
new ClauseFactory<Clause>() {
@Override
public Clause newInstance(String clause) {
return new Clause(clause);
}
});
originalValue = value;
}
public boolean contains(Resource resource) {
return getClause(resource) != null;
}
public Clause getClause(Resource resource) {
Capability capability = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE).get(0);
for (Clause clause : clauses) {
Requirement requirement = clause.toRequirement(resource);
if (ResourceHelper.matches(requirement, capability)) {
return clause;
}
}
return null;
}
public boolean isMandatory(Resource resource) {
Clause clause = getClause(resource);
if (clause == null)
return false;
return clause.isMandatory();
}
@Override
public String getName() {
return NAME;
}
@Override
public String getValue() {
return originalValue;
}
@Override
public List<Requirement> toRequirements(Resource resource) {
List<Requirement> requirements = new ArrayList<Requirement>(clauses.size());
for (Clause clause : clauses)
requirements.add(clause.toRequirement(resource));
return requirements;
}
@Override
public String toString() {
return originalValue;
}
}
| 8,617 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/OsgiExecutionEnvironmentRequirement.java | /*
* 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.subsystem.core.archive;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.BundleRequiredExecutionEnvironmentHeader.Clause.ExecutionEnvironment;
import org.apache.aries.subsystem.core.internal.AbstractRequirement;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.ExecutionEnvironmentNamespace;
import org.osgi.resource.Resource;
public class OsgiExecutionEnvironmentRequirement extends AbstractRequirement {
public static final String ATTRIBUTE_VERSION = ExecutionEnvironmentNamespace.CAPABILITY_VERSION_ATTRIBUTE;
public static final String DIRECTIVE_FILTER = ExecutionEnvironmentNamespace.REQUIREMENT_FILTER_DIRECTIVE;
public static final String NAMESPACE = ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE;
private final Map<String, String> directives;
private final Resource resource;
public OsgiExecutionEnvironmentRequirement(BundleRequiredExecutionEnvironmentHeader.Clause clause, Resource resource) {
this(Collections.singleton(clause), resource);
}
public OsgiExecutionEnvironmentRequirement(Collection<BundleRequiredExecutionEnvironmentHeader.Clause> clauses, Resource resource) {
if (clauses.isEmpty()) {
throw new IllegalArgumentException();
}
if (resource == null) {
throw new NullPointerException();
}
StringBuilder filter = new StringBuilder();
if (clauses.size() > 1) {
filter.append("(|");
}
for (BundleRequiredExecutionEnvironmentHeader.Clause clause : clauses) {
ExecutionEnvironment ee = clause.getExecutionEnvironment();
Version version = ee.getVersion();
if (version != null) {
filter.append("(&");
}
filter.append("(").append(NAMESPACE).append('=').append(ee.getName()).append(')');
if (version != null) {
filter.append('(').append(ATTRIBUTE_VERSION).append('=').append(version).append("))");
}
}
if (clauses.size() > 1) {
filter.append(')');
}
directives = new HashMap<String, String>(1);
directives.put(DIRECTIVE_FILTER, filter.toString());
this.resource = resource;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.emptyMap();
}
@Override
public Map<String, String> getDirectives() {
return Collections.unmodifiableMap(directives);
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,618 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemExportServiceHeader.java | /*
* 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.subsystem.core.archive;
import java.util.ArrayList;
import java.util.List;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemExportServiceHeader extends AbstractClauseBasedHeader<SubsystemExportServiceHeader.Clause> {
public static class Clause extends AbstractClause {
public static final String DIRECTIVE_FILTER = Constants.FILTER_DIRECTIVE;
public Clause(String clause) {
super(
parsePath(clause, Patterns.OBJECTCLASS_OR_STAR, false),
parseParameters(clause, false),
generateDefaultParameters());
}
public String getObjectClass() {
return path;
}
public List<Capability> toCapabilities(Resource resource) throws InvalidSyntaxException {
List<Capability> capabilities = resource.getCapabilities(ServiceNamespace.SERVICE_NAMESPACE);
if (capabilities.isEmpty())
return capabilities;
Filter filter = computeFilter();
ArrayList<Capability> result = new ArrayList<Capability>(capabilities.size());
for (Capability capability : capabilities)
if (filter.matches(capability.getAttributes()))
result.add(capability);
result.trimToSize();
return result;
}
private Filter computeFilter() throws InvalidSyntaxException {
return FrameworkUtil.createFilter(computeFilterString());
}
private String computeFilterString() {
Directive directive = getDirective(DIRECTIVE_FILTER);
return new StringBuilder()
.append("(&(")
.append(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE)
.append('=')
.append(path)
.append(')')
.append(directive == null ? "" : directive.getValue())
.append(')')
.toString();
}
}
public static final String NAME = SubsystemConstants.SUBSYSTEM_EXPORTSERVICE;
public SubsystemExportServiceHeader(String value) {
super(
value,
new ClauseFactory<Clause>() {
@Override
public Clause newInstance(String clause) {
return new Clause(clause);
}
});
}
@Override
public String getName() {
return NAME;
}
@Override
public String getValue() {
return toString();
}
public List<Capability> toCapabilities(Resource resource) throws InvalidSyntaxException {
List<Capability> result = new ArrayList<Capability>();
for (Clause clause : clauses)
result.addAll(clause.toCapabilities(resource));
return result;
}
}
| 8,619 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/Header.java | /*
* 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.subsystem.core.archive;
import java.util.Collection;
public interface Header<C extends Clause> {
Collection<C> getClauses();
String getName();
String getValue();
}
| 8,620 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/FragmentHostCapability.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.subsystem.core.archive;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.internal.AbstractCapability;
import org.osgi.framework.namespace.HostNamespace;
import org.osgi.resource.Resource;
public class FragmentHostCapability extends AbstractCapability {
public static final String ATTRIBUTE_BUNDLE_VERSION = HostNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE;
public static final String NAMESPACE = HostNamespace.HOST_NAMESPACE;
private static Map<String, Object> initializeAttributes(BundleSymbolicNameHeader bsn, BundleVersionHeader version) {
if (version == null) {
version = new BundleVersionHeader();
}
Clause clause = bsn.getClauses().get(0);
Collection<Attribute> attributes = clause.getAttributes();
Map<String, Object> result = new HashMap<String, Object>(attributes.size() + 2);
result.put(NAMESPACE, clause.getPath());
result.put(ATTRIBUTE_BUNDLE_VERSION, version.getVersion());
for (Attribute attribute : attributes) {
result.put(attribute.getName(), attribute.getValue());
}
return Collections.unmodifiableMap(result);
}
private static Map<String, String> initializeDirectives(Collection<Directive> directives) {
if (directives.isEmpty())
return Collections.emptyMap();
Map<String, String> result = new HashMap<String, String>(directives.size());
for (Directive directive : directives) {
result.put(directive.getName(), directive.getValue());
}
return Collections.unmodifiableMap(result);
}
private final Map<String, Object> attributes;
private final Map<String, String> directives;
private final Resource resource;
public FragmentHostCapability(BundleSymbolicNameHeader bsn, BundleVersionHeader version, Resource resource) {
if (resource == null)
throw new NullPointerException("Missing required parameter: resource");
this.resource = resource;
attributes = initializeAttributes(bsn, version);
directives = initializeDirectives(bsn.getClauses().get(0).getDirectives());
}
@Override
public Map<String, Object> getAttributes() {
return attributes;
}
@Override
public Map<String, String> getDirectives() {
return directives;
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,621 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/BundleVersionAttribute.java | /*
* 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.subsystem.core.archive;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.VersionRange;
public class BundleVersionAttribute extends AbstractAttribute {
public static final String NAME = Constants.BUNDLE_VERSION_ATTRIBUTE;
private final VersionRange range;
public BundleVersionAttribute() {
this(Version.emptyVersion.toString());
}
public BundleVersionAttribute(String value) {
this(new VersionRange(value));
}
public BundleVersionAttribute(VersionRange range) {
super(NAME, range.toString());
this.range = range;
}
public StringBuilder appendToFilter(StringBuilder builder) {
return builder.append(range.toFilterString(NAME));
}
public VersionRange getVersionRange() {
return range;
}
@Override
public Object getValue() {
return new StringBuilder().append('"').append(range.toString()).append('"').toString();
}
}
| 8,622 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/TypedAttribute.java | /*
* 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.subsystem.core.archive;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import org.osgi.framework.Version;
public class TypedAttribute extends AbstractAttribute {
private static final String DOUBLE = "Double";
private static final String LIST = "List";
private static final String LIST_DOUBLE = "List<Double>";
private static final String LIST_LONG = "List<Long>";
private static final String LIST_STRING = "List<String>";
private static final String LIST_VERSION = "List<Version>";
private static final String LONG = "Long";
private static final String STRING = "String";
private static final String VERSION = "Version";
private static Object parseScalar(String value, String type) {
if (STRING.equals(type)) {
return value;
}
if (VERSION.equals(type)) {
return Version.parseVersion(value);
}
if (LONG.equals(type)) {
return Long.valueOf(value);
}
if (DOUBLE.equals(type)) {
return Double.valueOf(value);
}
return null;
}
private static Object parseList(String value, String type) {
if (!type.startsWith(LIST)) {
return null;
}
String scalar;
if (type.length() == LIST.length()) {
scalar = STRING;
}
else {
Matcher matcher = Patterns.SCALAR_LIST.matcher(type);
if (!matcher.matches()) {
return null;
}
scalar = matcher.group(1);
}
String[] values = value.split(",");
List<Object> result = new ArrayList<Object>(values.length);
for (String s : values) {
result.add(parseScalar(s, scalar));
}
return result;
}
private static Object parseValue(String value, String type) {
if (type == null) {
return value;
}
Object result = parseScalar(value, type);
if (result == null) {
result = parseList(value, type);
}
return result;
}
private final String type;
public TypedAttribute(String name, String value, String type) {
super(name, parseValue(value, type));
this.type = type;
}
public TypedAttribute(String name, Object value) {
super(name, value);
if (value instanceof String) {
type = STRING;
}
else if (value instanceof List) {
@SuppressWarnings("rawtypes")
List list = (List)value;
if (list.isEmpty()) {
type = LIST;
}
else {
Object o = list.get(0);
if (o instanceof String) {
type = LIST_STRING;
}
else if (o instanceof Version) {
type = LIST_VERSION;
}
else if (o instanceof Long) {
type = LIST_LONG;
}
else if (o instanceof Double) {
type = LIST_DOUBLE;
}
else {
throw new IllegalArgumentException(name + '=' + value);
}
}
}
else if (value instanceof Version) {
type = VERSION;
}
else if (value instanceof Long) {
type = LONG;
}
else if (value instanceof Double) {
type = DOUBLE;
}
else {
throw new IllegalArgumentException(name + '=' + value);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder()
.append(getName())
.append(':')
.append(type)
.append("=\"");
if (type.startsWith(LIST)) {
@SuppressWarnings("rawtypes")
List list = (List)getValue();
if (!list.isEmpty()) {
builder.append(list.get(0));
}
for (int i = 1; i < list.size(); i++) {
builder.append(',').append(list.get(i));
}
}
else {
builder.append(getValue());
}
return builder.append('"').toString();
}
}
| 8,623 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/Clause.java | /*
* 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.subsystem.core.archive;
import java.util.Collection;
public interface Clause {
Attribute getAttribute(String name);
Collection<Attribute> getAttributes();
Directive getDirective(String name);
Collection<Directive> getDirectives();
Parameter getParameter(String name);
Collection<Parameter> getParameters();
String getPath();
}
| 8,624 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/BundleSymbolicNameHeader.java | /*
* 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.subsystem.core.archive;
import org.osgi.framework.Constants;
public class BundleSymbolicNameHeader extends SymbolicNameHeader {
public static final String NAME = Constants.BUNDLE_SYMBOLICNAME;
public BundleSymbolicNameHeader(String value) {
super(NAME, value);
}
}
| 8,625 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AttributeFactory.java | /*
* 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.subsystem.core.archive;
import org.osgi.framework.Constants;
public class AttributeFactory {
public static Attribute createAttribute(String name, String value) {
if (Constants.VERSION_ATTRIBUTE.equals(name)) {
if (Character.isDigit(value.charAt(0)))
return new VersionAttribute(value);
return new VersionRangeAttribute(value);
}
if (TypeAttribute.NAME.equals(name))
return new TypeAttribute(value);
if (DeployedVersionAttribute.NAME.equals(name))
return new DeployedVersionAttribute(value);
if (BundleVersionAttribute.NAME.equals(name))
return new BundleVersionAttribute(value);
return new GenericAttribute(name, value);
}
}
| 8,626 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemContentRequirement.java | /*
* 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.subsystem.core.archive;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.internal.AbstractRequirement;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
public class SubsystemContentRequirement extends AbstractRequirement {
public static final String DIRECTIVE_FILTER = IdentityNamespace.REQUIREMENT_FILTER_DIRECTIVE;
public static final String NAMESPACE = IdentityNamespace.IDENTITY_NAMESPACE;
private final Map<String, String> directives = new HashMap<String, String>();
private final Resource resource;
public SubsystemContentRequirement(
SubsystemContentHeader.Clause clause, Resource resource) {
StringBuilder builder = new StringBuilder("(&(")
.append(NAMESPACE).append('=')
.append(clause.getSymbolicName()).append(')');
for (Attribute attribute : clause.getAttributes()) {
if (!clause.isTypeSpecified()
&& TypeAttribute.NAME.equals(attribute.getName())) {
// If the type attribute was not specified as part of the
// original clause, match against both bundles and fragments.
// See ARIES-1425.
builder.append("(|(").append(TypeAttribute.NAME).append('=')
.append(IdentityNamespace.TYPE_BUNDLE).append(")(")
.append(TypeAttribute.NAME).append('=').append(IdentityNamespace.TYPE_FRAGMENT)
.append("))");
}
else {
attribute.appendToFilter(builder);
}
}
directives.put(DIRECTIVE_FILTER, builder.append(')').toString());
this.resource = resource;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.emptyMap();
}
@Override
public Map<String, String> getDirectives() {
return Collections.unmodifiableMap(directives);
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,627 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/GenericDirective.java | /*
* 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.subsystem.core.archive;
public class GenericDirective extends AbstractDirective {
public GenericDirective(String name, String value) {
super(name, value);
}
}
| 8,628 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BasicCapability.java | /*
* 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.subsystem.core.internal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.osgi.resource.Capability;
import org.osgi.resource.Resource;
public class BasicCapability extends AbstractCapability {
public static class Builder {
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Map<String, String> directives = new HashMap<String, String>();
private Resource resource;
private String namespace;
public Builder attribute(String key, Object value) {
attributes.put(key, value);
return this;
}
public Builder attributes(Map<String, Object> values) {
attributes.putAll(values);
return this;
}
public BasicCapability build() {
return new BasicCapability(namespace, attributes, directives, resource);
}
public Builder directive(String key, String value) {
directives.put(key, value);
return this;
}
public Builder directives(Map<String, String> values) {
directives.putAll(values);
return this;
}
public Builder namespace(String value) {
namespace = value;
return this;
}
public Builder resource(Resource value) {
resource = value;
return this;
}
}
private final Map<String, Object> attributes;
private final Map<String, String> directives;
private final Resource resource;
private final String namespace;
public BasicCapability(Capability capability, Resource resource) {
if (resource == null) {
throw new NullPointerException();
}
attributes = capability.getAttributes();
directives = capability.getDirectives();
this.resource = resource;
namespace = capability.getNamespace();
}
public BasicCapability(String namespace, Map<String, Object> attributes, Map<String, String> directives, Resource resource) {
if (namespace == null)
throw new NullPointerException();
this.namespace = namespace;
if (attributes == null)
this.attributes = Collections.emptyMap();
else
this.attributes = Collections.unmodifiableMap(new HashMap<String, Object>(attributes));
if (directives == null)
this.directives = Collections.emptyMap();
else
this.directives = Collections.unmodifiableMap(new HashMap<String, String>(directives));
if (resource == null)
throw new NullPointerException();
this.resource = resource;
}
@Override
public Map<String, Object> getAttributes() {
return attributes;
}
@Override
public Map<String, String> getDirectives() {
return directives;
}
@Override
public String getNamespace() {
return namespace;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,629 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/RepositoryServiceRepository.java | /*
* 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.subsystem.core.internal;
import java.lang.reflect.Method;
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.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.SubsystemException;
public class RepositoryServiceRepository implements org.apache.aries.subsystem.core.repository.Repository {
final BundleContext context;
public RepositoryServiceRepository() {
this(Activator.getInstance().getBundleContext());
}
RepositoryServiceRepository(BundleContext ctx) {
context = ctx;
}
@SuppressWarnings("unchecked")
public Collection<Capability> findProviders(Requirement requirement) {
Set<Capability> result = new HashSet<Capability>();
ServiceReference<?>[] references;
try {
references = context.getAllServiceReferences("org.osgi.service.repository.Repository", null);
if (references == null)
return result;
}
catch (InvalidSyntaxException e) {
throw new IllegalStateException(e);
}
for (ServiceReference<?> reference : references) {
Object repository = context.getService(reference);
if (repository == null)
continue;
try {
// Reflection is used here to allow the service to work with a mixture of
// Repository services implementing different versions of the API.
Class<?> clazz = repository.getClass();
Class<?> repoInterface = null;
while (clazz != null && repoInterface == null) {
for (Class<?> intf : clazz.getInterfaces()) {
if (Repository.class.getName().equals(intf.getName())) {
// Compare interfaces by name so that we can work with different versions of the
// interface.
repoInterface = intf;
break;
}
}
clazz = clazz.getSuperclass();
}
if (repoInterface == null) {
continue;
}
Map<Requirement, Collection<Capability>> map;
try {
Method method = repoInterface.getMethod("findProviders", Collection.class);
map = (Map<Requirement, Collection<Capability>>)method.invoke(repository, Collections.singleton(requirement));
}
catch (Exception e) {
throw new SubsystemException(e);
}
Collection<Capability> capabilities = map.get(requirement);
if (capabilities == null)
continue;
result.addAll(capabilities);
}
finally {
context.ungetService(reference);
}
}
return result;
}
@Override
public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) {
Map<Requirement, Collection<Capability>> result = new HashMap<Requirement, Collection<Capability>>();
for (Requirement requirement : requirements)
result.put(requirement, findProviders(requirement));
return result;
}
}
| 8,630 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java | /*
* 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.subsystem.core.internal;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.AccessController;
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 org.apache.aries.subsystem.core.archive.ProvisionPolicyDirective;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.apache.aries.subsystem.core.archive.SubsystemTypeHeader;
import org.apache.aries.subsystem.core.internal.BundleResourceInstaller.BundleConstituent;
import org.apache.aries.subsystem.core.internal.DependencyCalculator.MissingCapability;
import org.apache.aries.subsystem.core.internal.StartAction.Restriction;
import org.apache.aries.subsystem.core.repository.Repository;
import org.eclipse.equinox.region.Region;
import org.osgi.framework.BundleException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.namespace.ExecutionEnvironmentNamespace;
import org.osgi.framework.namespace.HostNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.NativeNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.resource.Capability;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.resource.Wire;
import org.osgi.resource.Wiring;
import org.osgi.service.resolver.HostedCapability;
import org.osgi.service.subsystem.Subsystem.State;
public class ResolveContext extends org.osgi.service.resolver.ResolveContext {
private final Repository contentRepository;
private final Repository localRepository;
private final Repository preferredProviderRepository;
private final Repository repositoryServiceRepository;
private final SubsystemResource resource;
private final Repository systemRepository;
private final Map<Resource, Wiring> wirings = computeWirings();
public ResolveContext(SubsystemResource resource) {
this.resource = resource;
contentRepository = new ContentRepository(resource.getInstallableContent(), resource.getSharedContent());
localRepository = resource.getLocalRepository();
preferredProviderRepository = new PreferredProviderRepository(resource);
repositoryServiceRepository = new RepositoryServiceRepository();
systemRepository = Activator.getInstance().getSystemRepository();
}
private void installDependenciesOfRequirerIfNecessary(Requirement requirement) {
if (requirement == null) {
return;
}
Resource requirer = requirement.getResource();
if (resource.equals(requirer)) {
return;
}
Collection<BasicSubsystem> subsystems;
if (requirer instanceof BasicSubsystem) {
BasicSubsystem subsystem = (BasicSubsystem)requirer;
subsystems = Collections.singletonList(subsystem);
}
else if (requirer instanceof BundleRevision) {
BundleRevision revision = (BundleRevision)requirer;
BundleConstituent constituent = new BundleConstituent(null, revision);
subsystems = Activator.getInstance().getSubsystems().getSubsystemsByConstituent(constituent);
}
else {
return;
}
for (BasicSubsystem subsystem : subsystems) {
if (Utils.isProvisionDependenciesInstall(subsystem)
|| !State.INSTALLING.equals(subsystem.getState())) {
continue;
}
AccessController.doPrivileged(new StartAction(subsystem, subsystem, subsystem, Restriction.INSTALL_ONLY));
}
}
private boolean isResolved(Resource resource) {
return wirings.containsKey(resource);
}
private boolean isProcessableAsFragment(Requirement requirement) {
Resource resource = requirement.getResource();
String namespace = requirement.getNamespace();
return Utils.isFragment(resource)
&& !(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE.equals(namespace)
|| HostNamespace.HOST_NAMESPACE.equals(namespace));
}
private void processAsFragment(Requirement requirement, List<Capability> capabilities) {
String namespace = requirement.getNamespace();
Resource fragment = requirement.getResource();
Wiring fragmentWiring = wirings.get(fragment);
List<Wire> fragmentWires = fragmentWiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE);
for (Wire fragmentWire : fragmentWires) {
Resource host = fragmentWire.getProvider();
Wiring hostWiring = wirings.get(host);
List<Wire> hostWires = hostWiring.getRequiredResourceWires(namespace);
processWires(hostWires, requirement, capabilities);
}
}
private void processWires(Collection<Wire> wires, Requirement requirement, List<Capability> capabilities) {
for (Wire wire : wires) {
processWire(wire, requirement, capabilities);
}
}
private void processWire(Wire wire, Requirement requirement, List<Capability> capabilities) {
if (requirement.equals(wire.getRequirement())) {
capabilities.add(wire.getCapability());
}
}
private void processCapability(Capability capability, Requirement requirement, List<Capability> capabilities) {
if (ResourceHelper.matches(requirement, capability)) {
capabilities.add(capability);
}
}
private void processResourceCapabilities(Collection<Capability> resourceCapabilities, Requirement requirement, List<Capability> capabilities) {
for (Capability resourceCapability : resourceCapabilities) {
processCapability(resourceCapability, requirement, capabilities);
}
}
private void processAsBundle(Requirement requirement, List<Capability> capabilities) {
String namespace = requirement.getNamespace();
Resource bundle = requirement.getResource();
Wiring wiring = wirings.get(bundle);
List<Wire> wires = wiring.getRequiredResourceWires(namespace);
processWires(wires, requirement, capabilities);
}
private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List<Capability> capabilities) {
String namespace = requirement.getNamespace();
if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) {
return;
}
Resource resource = requirement.getResource();
Wiring wiring = wirings.get(resource);
if (isFragment) {
List<Wire> fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE);
for (Wire fragmentWire : fragmentWires) {
Resource host = fragmentWire.getProvider();
processResourceCapabilities(
wirings.get(host).getResourceCapabilities(namespace),
requirement,
capabilities);
}
}
else {
List<Capability> resourceCapabilities = wiring.getResourceCapabilities(namespace);
processResourceCapabilities(resourceCapabilities, requirement, capabilities);
}
}
private void processAlreadyResolvedResource(Resource resource, Requirement requirement, List<Capability> capabilities) {
boolean isFragment = isProcessableAsFragment(requirement);
if (isFragment) {
processAsFragment(requirement, capabilities);
}
else {
processAsBundle(requirement, capabilities);
}
if (capabilities.isEmpty() && Utils.isMandatory(requirement)) {
processAsSubstitutableExport(isFragment, requirement, capabilities);
if (capabilities.isEmpty()) {
// ARIES-1538. Do not fail subsystem resolution if an already
// resolved resource has a missing dependency.
capabilities.add(new MissingCapability(requirement));
}
}
}
private void processNewlyResolvedResource(Resource resource, Requirement requirement, List<Capability> capabilities) {
try {
// Only check the system repository for osgi.ee and osgi.native
if (ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE.equals(requirement.getNamespace())
|| NativeNamespace.NATIVE_NAMESPACE.equals(requirement.getNamespace())) {
addDependenciesFromSystemRepository(requirement, capabilities);
} else {
addDependenciesFromContentRepository(requirement, capabilities);
addDependenciesFromPreferredProviderRepository(requirement, capabilities);
addDependenciesFromSystemRepository(requirement, capabilities);
addDependenciesFromLocalRepository(requirement, capabilities);
if (capabilities.isEmpty()) {
addDependenciesFromRepositoryServiceRepositories(requirement, capabilities);
}
}
if (capabilities.isEmpty()) {
// Is the requirement optional?
String resolution = requirement.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE);
if (Namespace.RESOLUTION_OPTIONAL.equals(resolution)) {
// Yes, it's optional. Add a missing capability to ensure
// it gets added to the sharing policy per the specification.
capabilities.add(new MissingCapability(requirement));
}
// Is the requirement resource already resolved? See ARIES-1538.
else if (isResolved(requirement.getResource())) {
// Yes, the resource has already been resolved. Do not fail
// the subsystem resolution due to a missing dependency.
capabilities.add(new MissingCapability(requirement));
}
}
}
catch (Throwable t) {
Utils.handleTrowable(t);
}
}
@Override
public List<Capability> findProviders(Requirement requirement) {
ArrayList<Capability> capabilities = new ArrayList<Capability>();
Resource resource = requirement.getResource();
if (isResolved(resource)
&& Utils.isEffectiveResolve(requirement)) {
processAlreadyResolvedResource(resource, requirement, capabilities);
}
else {
installDependenciesOfRequirerIfNecessary(requirement);
processNewlyResolvedResource(resource, requirement, capabilities);
}
capabilities.trimToSize();
return capabilities;
}
@Override
public int insertHostedCapability(List<Capability> capabilities, HostedCapability hostedCapability) {
// Must specify the location where the capability is to be added. From the ResoveContext javadoc:
// "This method must insert the specified HostedCapability in a place that makes the list maintain
// the preference order."
// The Felix implementation provides a list that requires the index to be specified in the add() call,
// otherwise it will throw an exception.
int sz = capabilities.size();
capabilities.add(sz, hostedCapability);
return sz;
}
@Override
public boolean isEffective(Requirement requirement) {
return true;
}
@Override
public Collection<Resource> getMandatoryResources() {
return resource.getMandatoryResources();
}
@Override
public Collection<Resource> getOptionalResources() {
return resource.getOptionalResources();
}
@Override
public Map<Resource, Wiring> getWirings() {
return Collections.emptyMap();
}
private boolean addDependencies(Repository repository, Requirement requirement, List<Capability> capabilities, boolean validate) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
if (repository == null)
return false;
Map<Requirement, Collection<Capability>> m = repository.findProviders(Collections.singleton(requirement));
if (m.containsKey(requirement)) {
Collection<Capability> cc = m.get(requirement);
addValidCapabilities(cc, capabilities, requirement, validate);
}
return !capabilities.isEmpty();
}
private boolean addDependenciesFromContentRepository(Requirement requirement, List<Capability> capabilities) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
return addDependencies(contentRepository, requirement, capabilities, false);
}
private boolean addDependenciesFromLocalRepository(Requirement requirement, List<Capability> capabilities) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
return addDependencies(localRepository, requirement, capabilities, true);
}
private boolean addDependenciesFromPreferredProviderRepository(Requirement requirement, List<Capability> capabilities) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
return addDependencies(preferredProviderRepository, requirement, capabilities, true);
}
private boolean addDependenciesFromRepositoryServiceRepositories(Requirement requirement, List<Capability> capabilities) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
return addDependencies(repositoryServiceRepository, requirement, capabilities, true);
}
private boolean addDependenciesFromSystemRepository(Requirement requirement, List<Capability> capabilities) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
boolean result = addDependencies(systemRepository, requirement, capabilities, true);
return result;
}
private void addValidCapabilities(Collection<Capability> from, Collection<Capability> to, Requirement requirement, boolean validate) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
for (Capability c : from) {
if (!validate || isValid(c, requirement)) {
// either validation is not requested or the capability is valid.
to.add(c);
}
}
}
private void addWiring(Resource resource, Map<Resource, Wiring> wirings) {
if (resource instanceof BundleConstituent) {
BundleConstituent bc = (BundleConstituent)resource;
BundleWiring wiring = bc.getWiring();
if (wiring != null) {
wirings.put(bc.getBundle().adapt(BundleRevision.class), wiring);
}
}
else if (resource instanceof BundleRevision) {
BundleRevision br = (BundleRevision)resource;
BundleWiring wiring = br.getWiring();
if (wiring != null) {
wirings.put(br, wiring);
}
}
}
private Map<Resource, Wiring> computeWirings() {
Map<Resource, Wiring> wirings = new HashMap<Resource, Wiring>();
for (BasicSubsystem subsystem : Activator.getInstance().getSubsystems().getSubsystems()) { // NEED
for (Resource constituent : subsystem.getConstituents()) {
addWiring(constituent, wirings);
}
}
return Collections.unmodifiableMap(wirings);
}
private boolean isContent(Resource resource) {
return this.resource.isContent(resource);
}
private boolean isInstallable(Resource resource) {
return !isShared(resource);
}
private boolean isShared(Resource resource) {
return Utils.isSharedResource(resource);
}
private boolean isValid(Capability capability, Requirement requirement) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
if (IdentityNamespace.IDENTITY_NAMESPACE.equals(capability.getNamespace()))
return true;
Resource provider = capability.getResource();
Resource requirer = requirement.getResource();
SubsystemManifest manifest = resource.getSubsystemManifest();
SubsystemContentHeader header = manifest.getSubsystemContentHeader();
if (header.contains(provider) && header.contains(requirer)) {
// Shortcut. If both the provider and requirer are content then they
// are in the same region and the capability will be visible.
return true;
}
Region from = findRegionForCapabilityValidation(provider);
Region to = findRegionForCapabilityValidation(requirer);
return new SharingPolicyValidator(from, to).isValid(capability);
}
private boolean isAcceptDependencies() {
SubsystemManifest manifest = resource.getSubsystemManifest();
SubsystemTypeHeader header = manifest.getSubsystemTypeHeader();
ProvisionPolicyDirective directive = header.getProvisionPolicyDirective();
return directive.isAcceptDependencies();
}
private Region findRegionForCapabilityValidation(Resource resource) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
if (isInstallable(resource)) {
// This is an installable resource so we need to figure out where it
// will be installed.
if (isContent(resource) // If the resource is content of this subsystem, it will be installed here.
// Or if this subsystem accepts dependencies, the resource will be installed here.
|| isAcceptDependencies()) {
if (this.resource.isComposite()) {
// Composites define their own sharing policy with which
// their regions are already configured by the time we get
// here. We ensure capabilities are visible to this region.
return this.resource.getRegion();
}
// For applications and features, we must ensure capabilities
// are visible to their scoped parent. Features import
// everything. Applications have their sharing policies
// computed, so if capabilities are visible to the parent, we
// know we can make them visible to the application.
BasicSubsystem parent = this.resource.getParents().iterator().next();
// If the parent accepts dependencies, the resource will
// be installed there and all capabilities will be visible.
if (parent.getSubsystemManifest().getSubsystemTypeHeader().getProvisionPolicyDirective().isAcceptDependencies()) {
return parent.getRegion();
}
// Otherwise, the "parent" is defined as the first scoped
// ancestor whose sharing policy has already been set. This
// covers the case of multiple subsystems from the same archive
// being installed whose regions will form a tree of depth N.
parent = Utils.findFirstScopedAncestorWithSharingPolicy(this.resource);
return parent.getRegion();
}
return Utils.findFirstSubsystemAcceptingDependenciesStartingFrom(this.resource.getParents().iterator().next()).getRegion();
}
else {
// This is an already installed resource from the system repository.
if (Utils.isBundle(resource)) {
if (isContent(resource)
&& this.resource.getSubsystemManifest().getSubsystemTypeHeader().getAriesProvisionDependenciesDirective().isResolve()) {
// If we get here with a subsystem that is
// apache-aries-provision-dependencies:=resolve, it means
// that a restart has occurred with the subsystem in the
// INSTALLING state. Its content has already been installed.
// However, because the sharing policy has not yet been set,
// we must treat it similarly to the installable content case
// above.
return Utils.findFirstScopedAncestorWithSharingPolicy(this.resource).getRegion();
}
BundleRevision revision = resource instanceof BundleRevision ? (BundleRevision)resource : ((BundleRevisionResource)resource).getRevision();
// If it's a bundle, use region digraph to get the region in order
// to account for bundles in isolated regions outside of the
// subsystems API.
return Activator.getInstance().getRegionDigraph().getRegion(revision.getBundle());
}
else {
if (this.resource.getSubsystemManifest().getSubsystemTypeHeader().getAriesProvisionDependenciesDirective().isResolve()) {
return Utils.findFirstScopedAncestorWithSharingPolicy(this.resource).getRegion();
}
// If it's anything else, get the region from one of the
// subsystems referencing it.
return Activator.getInstance().getSubsystems().getSubsystemsReferencing(resource).iterator().next().getRegion();
}
}
}
}
| 8,631 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SystemRepositoryManager.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.subsystem.core.internal;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.aries.subsystem.AriesSubsystem;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.util.tracker.BundleTracker;
import org.osgi.util.tracker.ServiceTracker;
public class SystemRepositoryManager {
private static final Filter filter = createFilter();
private static Filter createFilter() {
try {
return FrameworkUtil.createFilter(new StringBuilder()
.append("(&(!(|(")
.append(SubsystemConstants.SUBSYSTEM_STATE_PROPERTY)
.append('=')
.append(Subsystem.State.INSTALL_FAILED)
.append(")(")
.append(SubsystemConstants.SUBSYSTEM_STATE_PROPERTY)
.append('=')
.append(Subsystem.State.UNINSTALLING)
.append(")(")
.append(SubsystemConstants.SUBSYSTEM_STATE_PROPERTY)
.append('=')
.append(Subsystem.State.UNINSTALLED)
.append(")))(")
.append(org.osgi.framework.Constants.OBJECTCLASS)
.append('=')
.append(AriesSubsystem.class.getName())
.append("))")
.toString());
}
catch (InvalidSyntaxException e) {
throw new IllegalStateException(e);
}
}
private final BundleTracker<AtomicReference<BundleRevisionResource>> bundleTracker;
private final ServiceTracker<AriesSubsystem, BasicSubsystem> serviceTracker;
private final SystemRepository systemRepository;
public SystemRepositoryManager(BundleContext bundleContext) {
systemRepository = new SystemRepository(bundleContext);
bundleTracker = new BundleTracker<AtomicReference<BundleRevisionResource>>(
bundleContext, ~Bundle.UNINSTALLED, systemRepository);
serviceTracker = new ServiceTracker<AriesSubsystem, BasicSubsystem>(
bundleContext, filter, systemRepository);
}
public SystemRepository getSystemRepository() {
return systemRepository;
}
public void open() {
bundleTracker.open();
serviceTracker.open();
}
public void close() {
serviceTracker.close();
bundleTracker.close();
}
}
| 8,632 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/UninstallAction.java | /*
* 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.subsystem.core.internal;
import java.util.EnumSet;
import org.osgi.service.subsystem.Subsystem.State;
public class UninstallAction extends AbstractAction {
public UninstallAction(BasicSubsystem requestor, BasicSubsystem target, boolean disableRootCheck) {
super(requestor, target, disableRootCheck);
}
@Override
public Object run() {
// Protect against re-entry now that cycles are supported.
if (!Activator.getInstance().getLockingStrategy().set(State.UNINSTALLING, target)) {
return null;
}
try {
// Acquire the global write lock to prevent all other operations
// until the uninstall is complete. There is no need to hold any
// other locks.
Activator.getInstance().getLockingStrategy().writeLock();
try {
checkRoot();
checkValid();
State state = target.getState();
if (EnumSet.of(State.UNINSTALLED).contains(state)) {
return null;
}
if (state.equals(State.ACTIVE)) {
new StopAction(requestor, target, disableRootCheck).run();
}
ResourceUninstaller.newInstance(requestor, target).uninstall();
}
finally {
// Release the global write lock.
Activator.getInstance().getLockingStrategy().writeUnlock();
}
}
finally {
// Protection against re-entry no longer required.
Activator.getInstance().getLockingStrategy().unset(State.UNINSTALLING, target);
}
return null;
}
}
| 8,633 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResourceInstaller.java | /*
* 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.subsystem.core.internal;
import org.apache.aries.subsystem.ContentHandler;
import org.apache.aries.subsystem.core.archive.DeployedContentHeader;
import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public abstract class ResourceInstaller {
public static ResourceInstaller newInstance(Coordination coordination, Resource resource, BasicSubsystem subsystem) {
String type = ResourceHelper.getTypeAttribute(resource);
if (SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION.equals(type)
|| SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type)
|| SubsystemConstants.SUBSYSTEM_TYPE_FEATURE.equals(type)) {
return new SubsystemResourceInstaller(coordination, resource, subsystem);
} else if (IdentityNamespace.TYPE_BUNDLE.equals(type) || IdentityNamespace.TYPE_FRAGMENT.equals(type)) {
return new BundleResourceInstaller(coordination, resource, subsystem);
} else if (Constants.ResourceTypeSynthesized.equals(type)) {
return new ResourceInstaller(coordination, resource, subsystem) {
@Override
public Resource install() throws Exception {
// do nothing;
return resource;
}
};
} else {
ServiceReference<ContentHandler> handlerRef = CustomResources.getCustomContentHandler(subsystem, type);
if (handlerRef != null)
return new CustomResourceInstaller(coordination, resource, type, subsystem, handlerRef);
}
throw new SubsystemException("No installer exists for resource type: " + type);
}
protected final Coordination coordination;
protected final BasicSubsystem provisionTo;
/* resource to install */
protected final Resource resource;
/* parent subsystem being installed into */
protected final BasicSubsystem subsystem;
public ResourceInstaller(Coordination coordination, Resource resource, BasicSubsystem subsystem) {
if (coordination == null || resource == null || subsystem == null) {
// We're assuming these are not null post construction, so enforce it here.
throw new NullPointerException();
}
this.coordination = coordination;
this.resource = resource;
this.subsystem = subsystem;
if (isDependency()) {
if (Utils.isInstallableResource(resource))
provisionTo = Utils.findFirstSubsystemAcceptingDependenciesStartingFrom(subsystem);
else
provisionTo = null;
}
else
provisionTo = subsystem;
}
public abstract Resource install() throws Exception;
protected void addConstituent(final Resource resource) {
// Don't let a resource become a constituent of itself.
if (provisionTo == null || resource.equals(provisionTo))
return;
Activator.getInstance().getSubsystems().addConstituent(provisionTo, resource, isReferencedProvisionTo());
}
protected void addReference(final Resource resource) {
// Don't let a resource reference itself.
if (resource.equals(subsystem))
return;
// The following check protects against resources posing as content
// during a restart since the Deployed-Content header is currently used
// to track all constituents for persistence purposes, which includes
// resources that were provisioned to the subsystem as dependencies of
// other resources.
if (isReferencedSubsystem()) {
Activator.getInstance().getSubsystems().addReference(subsystem, resource);
}
}
protected String getLocation() {
return provisionTo.getLocation() + "!/" + ResourceHelper.getLocation(resource);
}
protected boolean isContent() {
return Utils.isContent(subsystem, resource);
}
protected boolean isDependency() {
return Utils.isDependency(subsystem, resource);
}
protected boolean isReferencedProvisionTo() {
DeploymentManifest manifest = subsystem.getDeploymentManifest();
if (manifest != null) {
DeployedContentHeader header = manifest.getDeployedContentHeader();
if (header != null && header.contains(resource))
return subsystem.isReferenced(resource);
}
if (subsystem.equals(provisionTo))
return isReferencedSubsystem();
return false;
}
protected boolean isReferencedSubsystem() {
DeploymentManifest manifest = subsystem.getDeploymentManifest();
if (manifest != null) {
DeployedContentHeader header = manifest.getDeployedContentHeader();
if (header != null && header.contains(resource))
return subsystem.isReferenced(resource);
}
return true;
}
}
| 8,634 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResourceReferences.java | /*
* 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.subsystem.core.internal;
import java.util.ArrayList;
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.osgi.resource.Resource;
public class ResourceReferences {
private final Map<Resource, Set<BasicSubsystem>> resourceToSubsystems = new HashMap<Resource, Set<BasicSubsystem>>();
private final Map<BasicSubsystem, Set<Resource>> subsystemToResources = new HashMap<BasicSubsystem, Set<Resource>>();
public synchronized void addReference(BasicSubsystem subsystem, Resource resource) {
addSubsystemToResource(subsystem, resource);
addResourceToSubsystem(subsystem, resource);
}
public synchronized Collection<Resource> getResources(BasicSubsystem subsystem) {
Collection<Resource> result = subsystemToResources.get(subsystem);
if (result == null)
result = Collections.emptyList();
return Collections.unmodifiableCollection(new ArrayList<Resource>(result));
}
public synchronized Collection<BasicSubsystem> getSubsystems(Resource resource) {
Collection<BasicSubsystem> result = resourceToSubsystems.get(resource);
if (result == null)
result = Collections.emptyList();
return Collections.unmodifiableCollection(new ArrayList<BasicSubsystem>(result));
}
public synchronized void removeReference(BasicSubsystem subsystem, Resource resource) {
removeResourceToSubsystem(subsystem, resource);
removeSubsystemToResource(subsystem, resource);
}
private void addResourceToSubsystem(BasicSubsystem subsystem, Resource resource) {
Set<BasicSubsystem> subsystems = resourceToSubsystems.get(resource);
if (subsystems == null) {
subsystems = new HashSet<BasicSubsystem>();
resourceToSubsystems.put(resource, subsystems);
}
subsystems.add(subsystem);
}
private void addSubsystemToResource(BasicSubsystem subsystem, Resource resource) {
Set<Resource> resources = subsystemToResources.get(subsystem);
if (resources == null) {
resources = new HashSet<Resource>();
subsystemToResources.put(subsystem, resources);
}
resources.add(resource);
}
private void removeResourceToSubsystem(BasicSubsystem subsystem, Resource resource) {
Set<BasicSubsystem> subsystems = resourceToSubsystems.get(resource);
if (subsystems == null)
return;
subsystems.remove(subsystem);
if (subsystems.isEmpty())
resourceToSubsystems.remove(resource);
}
private void removeSubsystemToResource(BasicSubsystem subsystem, Resource resource) {
Set<Resource> resources = subsystemToResources.get(subsystem);
if (resources == null)
return;
resources.remove(resource);
if (resources.isEmpty())
subsystemToResources.remove(subsystem);
}
}
| 8,635 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/InstallDependencies.java | package org.apache.aries.subsystem.core.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
public class InstallDependencies {
public void install(BasicSubsystem subsystem, BasicSubsystem parent, Coordination coordination) throws Exception{
// Install dependencies first...
List<Resource> dependencies = new ArrayList<Resource>(subsystem.getResource().getInstallableDependencies());
Collections.sort(dependencies, new InstallResourceComparator());
for (Resource dependency : dependencies)
ResourceInstaller.newInstance(coordination, dependency, subsystem).install();
for (Resource dependency : subsystem.getResource().getSharedDependencies()) {
// TODO This needs some more thought. The following check
// protects against a child subsystem that has its parent as a
// dependency. Are there other places of concern as well? Is it
// only the current parent that is of concern or should all
// parents be checked?
if (parent==null || !dependency.equals(parent))
ResourceInstaller.newInstance(coordination, dependency, subsystem).install();
}
}
}
| 8,636 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/FileResource.java | /*
* 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.subsystem.core.internal;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.aries.util.filesystem.IFile;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.repository.RepositoryContent;
public class FileResource implements Resource, RepositoryContent {
private final IFile file;
private volatile Map<String, List<Capability>> capabilities ;
public FileResource(IFile file) {
this.file = file;
}
@Override
public List<Capability> getCapabilities(String namespace) {
Map<String, List<Capability>> namespace2capabilities = capabilities;
if (namespace2capabilities == null) {
return Collections.emptyList();
}
List<Capability> caps;
if (namespace == null) {
caps = new ArrayList<Capability>();
for (List<Capability> l : capabilities.values()) {
caps.addAll(l);
}
return Collections.unmodifiableList(caps);
}
caps = namespace2capabilities.get(namespace);
if (caps != null)
return Collections.unmodifiableList(caps);
else
return Collections.emptyList();
}
@Override
public List<Requirement> getRequirements(String namespace) {
return Collections.emptyList();
}
public void setCapabilities(List<Capability> capabilities) {
Map<String, List<Capability>> m = new HashMap<String, List<Capability>>();
for (Capability c : capabilities) {
List<Capability> l = m.get(c.getNamespace());
if (l == null) {
l = new ArrayList<Capability>();
m.put(c.getNamespace(), l);
}
l.add(c);
}
this.capabilities = m;
}
@Override
public InputStream getContent() {
try {
return file.open();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 8,637 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/RegionContextBundleHelper.java | /*
* 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.subsystem.core.internal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Version;
import org.osgi.framework.startlevel.BundleStartLevel;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.service.coordinator.Coordination;
public class RegionContextBundleHelper {
public static final String SYMBOLICNAME_PREFIX = Constants.RegionContextBundleSymbolicNamePrefix;
public static final Version VERSION = Version.parseVersion("1.0.0");
public static void installRegionContextBundle(final BasicSubsystem subsystem, Coordination coordination) throws Exception {
String symbolicName = SYMBOLICNAME_PREFIX + subsystem.getSubsystemId();
String location = subsystem.getLocation() + '/' + subsystem.getSubsystemId();
Bundle b = subsystem.getRegion().getBundle(symbolicName, VERSION);
if (b == null) {
b = subsystem.getRegion().installBundleAtLocation(location, createRegionContextBundle(symbolicName));
// The start level of all managed bundles, including the region
// context bundle, should be 1.
b.adapt(BundleStartLevel.class).setStartLevel(1);
}
ResourceInstaller.newInstance(coordination, b.adapt(BundleRevision.class), subsystem).install();
// The region context bundle must be started persistently.
b.start();
subsystem.setRegionContextBundle(b);
}
public static void uninstallRegionContextBundle(BasicSubsystem subsystem) {
String symbolicName = SYMBOLICNAME_PREFIX + subsystem.getSubsystemId();
Bundle bundle = subsystem.getRegion().getBundle(symbolicName, VERSION);
if (bundle == null)
return;
BundleRevision revision = bundle.adapt(BundleRevision.class);
try {
bundle.uninstall();
}
catch (BundleException e) {
// TODO Should we really eat this? At least log it?
}
ResourceUninstaller.newInstance(revision, subsystem).uninstall();
subsystem.setRegionContextBundle(null);
}
private static Manifest createManifest(String symbolicName) {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().putValue(org.osgi.framework.Constants.BUNDLE_MANIFESTVERSION, "2");
manifest.getMainAttributes().putValue(Constants.BundleSymbolicName, symbolicName);
manifest.getMainAttributes().putValue(Constants.BundleVersion, VERSION.toString());
return manifest;
}
private static InputStream createRegionContextBundle(String symbolicName) throws IOException {
Manifest manifest = createManifest(symbolicName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
jos.close();
return new ByteArrayInputStream(baos.toByteArray());
}
}
| 8,638 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemGraph.java | /*
* 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.subsystem.core.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemException;
public class SubsystemGraph {
private static class SubsystemWrapper {
private final Subsystem s;
public SubsystemWrapper(Subsystem subsystem) {
s = subsystem;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof SubsystemWrapper))
return false;
SubsystemWrapper that = (SubsystemWrapper)o;
return s.getLocation().equals(that.s.getLocation());
}
public Subsystem getSubsystem() {
return s;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + s.getLocation().hashCode();
return result;
}
@Override
public String toString() {
return new StringBuilder("location=").append(s.getLocation())
.append(", symbolicName=").append(s.getSymbolicName())
.append(", version=").append(s.getVersion())
.append(", type=").append(s.getType()).toString();
}
}
private final Map<SubsystemWrapper, Collection<SubsystemWrapper>> adjacencyList = new HashMap<SubsystemWrapper, Collection<SubsystemWrapper>>();
public SubsystemGraph(BasicSubsystem root) {
adjacencyList.put(new SubsystemWrapper(root), new HashSet<SubsystemWrapper>());
}
public synchronized void add(BasicSubsystem parent, BasicSubsystem child) {
SubsystemWrapper parentWrap = new SubsystemWrapper(parent);
SubsystemWrapper childWrap = new SubsystemWrapper(child);
if (containsAncestor(childWrap, parentWrap))
throw new SubsystemException("Cycle detected between '" + parentWrap + "' and '" + childWrap + "'");
Collection<SubsystemWrapper> subsystems = adjacencyList.get(childWrap);
if (subsystems == null) {
subsystems = new HashSet<SubsystemWrapper>();
adjacencyList.put(childWrap, subsystems);
}
subsystems = adjacencyList.get(parentWrap);
if (subsystems == null) {
subsystems = new HashSet<SubsystemWrapper>();
adjacencyList.put(parentWrap, subsystems);
}
subsystems.add(childWrap);
}
public synchronized Collection<Subsystem> getChildren(BasicSubsystem parent) {
Collection<SubsystemWrapper> children = adjacencyList.get(new SubsystemWrapper(parent));
if (children == null || children.isEmpty())
return Collections.emptySet();
Collection<Subsystem> result = new ArrayList<Subsystem>(children.size());
for (SubsystemWrapper child : children)
result.add(child.getSubsystem());
return Collections.unmodifiableCollection(result);
}
public synchronized Collection<Subsystem> getParents(BasicSubsystem child) {
Collection<SubsystemWrapper> parents = getParents(new SubsystemWrapper(child));
Collection<Subsystem> result = new ArrayList<Subsystem>(parents.size());
for (SubsystemWrapper parent : parents) {
result.add(parent.getSubsystem());
}
return Collections.unmodifiableCollection(result);
}
public synchronized void remove(BasicSubsystem child) {
SubsystemWrapper subsystemWrap = new SubsystemWrapper(child);
Collection<SubsystemWrapper> parents = getParents(subsystemWrap);
for (SubsystemWrapper parent : parents)
adjacencyList.get(parent).remove(subsystemWrap);
adjacencyList.remove(subsystemWrap);
}
public synchronized void remove(BasicSubsystem parent, BasicSubsystem child) {
SubsystemWrapper parentWrap = new SubsystemWrapper(parent);
SubsystemWrapper childWrap = new SubsystemWrapper(child);
adjacencyList.get(parentWrap).remove(childWrap);
}
private boolean containsAncestor(SubsystemWrapper subsystem, SubsystemWrapper ancestor) {
Collection<SubsystemWrapper> subsystems = adjacencyList.get(subsystem);
if (subsystems == null)
return false;
if (subsystems.contains(ancestor))
return true;
for (SubsystemWrapper s : subsystems) {
return containsAncestor(s, ancestor);
}
return false;
}
private Collection<SubsystemWrapper> getParents(SubsystemWrapper child) {
ArrayList<SubsystemWrapper> result = new ArrayList<SubsystemWrapper>();
for (Entry<SubsystemWrapper, Collection<SubsystemWrapper>> entry : adjacencyList.entrySet())
if (entry.getValue().contains(child))
result.add(entry.getKey());
result.trimToSize();
return result;
}
}
| 8,639 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/AbstractRequirement.java | /*
* 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.subsystem.core.internal;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.resource.Requirement;
public abstract class AbstractRequirement implements Requirement {
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Requirement))
return false;
Requirement c = (Requirement)o;
return c.getNamespace().equals(getNamespace())
&& c.getAttributes().equals(getAttributes())
&& c.getDirectives().equals(getDirectives())
&& c.getResource() != null ? c.getResource().equals(
getResource()) : getResource() == null;
}
private Filter filter;
public Filter getFilter() throws InvalidSyntaxException {
String filterStr = getDirectives().get(Constants.FILTER_DIRECTIVE);
if (filterStr == null) {
return null;
}
synchronized (this) {
if (filter == null) {
filter = FrameworkUtil.createFilter(filterStr);
}
return filter;
}
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getNamespace().hashCode();
result = 31 * result + getAttributes().hashCode();
result = 31 * result + getDirectives().hashCode();
result = 31 * result
+ (getResource() == null ? 0 : getResource().hashCode());
return result;
}
@Override
public String toString() {
return new StringBuffer().append(getClass().getName()).append(": ")
.append("namespace=").append(getNamespace())
.append(", attributes=").append(getAttributes())
.append(", directives=").append(getDirectives())
.append(", resource=").append(getResource()).toString();
}
}
| 8,640 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemResolverHook.java | /*
* 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.subsystem.core.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.aries.subsystem.core.archive.PreferredProviderHeader;
import org.osgi.framework.hooks.resolver.ResolverHook;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.Subsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SubsystemResolverHook implements ResolverHook {
private static final Logger LOGGER = LoggerFactory.getLogger(SubsystemResolverHook.class);
private final Subsystems subsystems;
public SubsystemResolverHook(Subsystems subsystems) {
if (subsystems == null)
throw new NullPointerException("Missing required parameter: subsystems");
this.subsystems = subsystems;
}
public void end() {
// noop
}
public void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates) {
// Filter out candidates that don't come from preferred providers when
// there is at least one preferred provider.
// (1) Find the subsystem(s) containing requirement.getResource() as a
// constituent.
Collection<BasicSubsystem> requirers = subsystems.getSubsystemsReferencing(requirement.getResource());
// (2) For each candidate, ask each subsystem if the candidate or any of
// the candidate's containing subsystems is a preferred provider. If at
// least one preferred provider exists, filter out all other candidates
// that are not also preferred providers.
Collection<BundleCapability> preferredProviders = new ArrayList<BundleCapability>(candidates.size());
for (BundleCapability candidate : candidates)
for (BasicSubsystem subsystem : requirers) {
PreferredProviderHeader header = subsystem.getSubsystemManifest().getPreferredProviderHeader();
if (header != null && (header.contains(candidate.getResource()) || isResourceConstituentOfPreferredSubsystem(candidate.getResource(), subsystem)))
preferredProviders.add(candidate);
}
if (!preferredProviders.isEmpty())
candidates.retainAll(preferredProviders);
}
public void filterResolvable(Collection<BundleRevision> candidates) {
try {
for (Iterator<BundleRevision> iterator = candidates.iterator(); iterator.hasNext();) {
BundleRevision revision = iterator.next();
if (revision.equals(ThreadLocalBundleRevision.get())) {
// The candidate is a bundle whose INSTALLED event is
// currently being processed on this thread.
iterator.remove();
continue;
}
if (revision.getSymbolicName().startsWith(Constants.RegionContextBundleSymbolicNamePrefix))
// Don't want to filter out the region context bundle.
continue;
Collection<BasicSubsystem> subsystems = this.subsystems.getSubsystemsReferencing(revision);
if (subsystems.isEmpty() && ThreadLocalSubsystem.get() != null) {
// This is the revision of a bundle being installed as part of a subsystem installation
// before it has been added as a reference or constituent.
iterator.remove();
continue;
}
for (BasicSubsystem subsystem : subsystems) {
if (subsystem.isFeature()) {
// Feature subsystems require no isolation.
continue;
}
// Otherwise, the candidate is part of an application or composite subsystem requiring isolation.
// But only when in the INSTALLING state.
if (Subsystem.State.INSTALLING.equals(subsystem.getState())) {
iterator.remove();
}
}
}
}
catch (RuntimeException e) {
// This try/catch block is in place because exceptions occurring here are not showing up in the console during testing.
LOGGER.debug("Unexpected exception while filtering resolution candidates: " + candidates, e);
}
}
public void filterSingletonCollisions(BundleCapability singleton, Collection<BundleCapability> collisionCandidates) {
// noop
}
private boolean isResourceConstituentOfPreferredSubsystem(Resource resource, BasicSubsystem preferer) {
Collection<BasicSubsystem> subsystems = this.subsystems.getSubsystemsReferencing(resource);
for (BasicSubsystem subsystem : subsystems)
if (preferer.getSubsystemManifest().getPreferredProviderHeader().contains(subsystem))
return true;
return false;
}
}
| 8,641 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/CustomResourceInstaller.java | /*
* 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.subsystem.core.internal;
import java.io.InputStream;
import org.apache.aries.subsystem.ContentHandler;
import org.osgi.framework.ServiceReference;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.repository.RepositoryContent;
public class CustomResourceInstaller extends ResourceInstaller {
private final ServiceReference<ContentHandler> handlerRef;
private final String type;
public CustomResourceInstaller(Coordination coordination, Resource resource, String type,
BasicSubsystem subsystem, ServiceReference<ContentHandler> handlerRef) {
super(coordination, resource, subsystem);
this.handlerRef = handlerRef;
this.type = type;
}
@Override
public Resource install() throws Exception {
try {
ContentHandler handler = subsystem.getBundleContext().getService(handlerRef);
if (handler != null) {
InputStream is = ((RepositoryContent) resource).getContent();
handler.install(is, ResourceHelper.getSymbolicNameAttribute(resource), type, subsystem, coordination);
addReference(resource);
return resource;
} else {
throw new Exception("Custom content handler not found: " + handlerRef);
}
} finally {
subsystem.getBundleContext().ungetService(handlerRef);
}
}
}
| 8,642 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemResourceUninstaller.java | /*
* 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.subsystem.core.internal;
import org.apache.aries.util.io.IOUtils;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SubsystemResourceUninstaller extends ResourceUninstaller {
private static final Logger logger = LoggerFactory.getLogger(BasicSubsystem.class);
private static void removeChild(BasicSubsystem parent, BasicSubsystem child) {
Activator.getInstance().getSubsystems().removeChild(parent, child);
}
public SubsystemResourceUninstaller(Resource resource, BasicSubsystem subsystem) {
super(resource, subsystem);
}
public void uninstall() {
removeReferences();
try {
if (isResourceUninstallable())
uninstallSubsystem();
}
finally {
removeConstituents();
removeChildren();
removeSubsystem();
}
}
private void removeChildren() {
if (!isExplicit()) {
removeChild((BasicSubsystem)subsystem, (BasicSubsystem)resource);
return;
}
for (Subsystem subsystem : ((BasicSubsystem)resource).getParents())
removeChild((BasicSubsystem)subsystem, (BasicSubsystem)resource);
}
private void removeConstituents() {
if (!isExplicit()) {
removeConstituent();
return;
}
for (Subsystem subsystem : ((BasicSubsystem)resource).getParents())
removeConstituent((BasicSubsystem)subsystem, (BasicSubsystem)resource);
}
private void removeReferences() {
if (!isExplicit()) {
removeReference();
}
else {
for (Subsystem subsystem : ((BasicSubsystem)resource).getParents())
removeReference((BasicSubsystem)subsystem, (BasicSubsystem)resource);
Subsystems subsystems = Activator.getInstance().getSubsystems();
// for explicit uninstall remove all references to subsystem.
for (BasicSubsystem s : subsystems.getSubsystemsReferencing(resource)) {
removeReference(s, resource);
}
}
}
private void removeSubsystem() {
Activator.getInstance().getSubsystems().removeSubsystem((BasicSubsystem)resource);
}
private void uninstallSubsystem() {
BasicSubsystem subsystem = (BasicSubsystem) resource;
try {
if (subsystem.getState().equals(Subsystem.State.RESOLVED))
subsystem.setState(State.INSTALLED);
subsystem.setState(State.UNINSTALLING);
Throwable firstError = null;
for (Resource resource : Activator.getInstance().getSubsystems()
.getResourcesReferencedBy(subsystem)) {
// Don't uninstall the region context bundle here.
if (Utils.isRegionContextBundle(resource))
continue;
try {
ResourceUninstaller.newInstance(resource, subsystem)
.uninstall();
} catch (Throwable t) {
logger.error("An error occurred while uninstalling resource "
+ resource + " of subsystem " + subsystem, t);
if (firstError == null)
firstError = t;
}
}
subsystem.setState(State.UNINSTALLED);
Activator activator = Activator.getInstance();
activator.getSubsystemServiceRegistrar().unregister(subsystem);
if (subsystem.isScoped()) {
RegionContextBundleHelper.uninstallRegionContextBundle(subsystem);
activator.getRegionDigraph().removeRegion(subsystem.getRegion());
}
if (firstError != null)
throw new SubsystemException(firstError);
}
finally {
// Let's be sure to always clean up the directory.
IOUtils.deleteRecursive(subsystem.getDirectory());
}
}
} | 8,643 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/InstallAction.java | /*
* 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.subsystem.core.internal;
import java.io.InputStream;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.aries.util.filesystem.IDirectory;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.coordinator.CoordinationException;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemException;
public class InstallAction implements PrivilegedAction<BasicSubsystem> {
private final IDirectory content;
private final AccessControlContext context;
private final InputStream deploymentManifest;
private final String location;
private final BasicSubsystem parent;
public InstallAction(String location, IDirectory content, BasicSubsystem parent, AccessControlContext context, InputStream deploymentManifest) {
this.location = location;
this.content = content;
this.parent = parent;
this.context = context;
this.deploymentManifest = deploymentManifest;
}
@Override
public BasicSubsystem run() {
// Doesn't appear to be any need of protecting against re-entry in the
// case of installation.
BasicSubsystem result = null;
// Acquire the global write lock to prevent all other operations until
// the installation is complete. There is no need to hold any other locks.
Activator.getInstance().getLockingStrategy().writeLock();
try {
State state = parent.getState();
if (State.INSTALLING.equals(state)) {
throw new SubsystemException("A child subsystem may not be installed while the parent is in the INSTALLING state");
}
// Initialization of a null coordination must be privileged and,
// therefore, occur in the run() method rather than in the constructor.
Coordination coordination = Utils.createCoordination(parent);
try {
TargetRegion region = new TargetRegion(parent);
SubsystemResource ssr = new SubsystemResource(location, content, parent, coordination);
result = Activator.getInstance().getSubsystems().getSubsystemByLocation(location);
if (result != null) {
if (!region.contains(result))
throw new SubsystemException("Location already exists but existing subsystem is not part of target region: " + location);
if (!(result.getSymbolicName().equals(ssr.getSubsystemManifest().getSubsystemSymbolicNameHeader().getSymbolicName())
&& result.getVersion().equals(ssr.getSubsystemManifest().getSubsystemVersionHeader().getVersion())
&& result.getType().equals(ssr.getSubsystemManifest().getSubsystemTypeHeader().getType())))
throw new SubsystemException("Location already exists but symbolic name, version, and type are not the same: " + location);
}
else {
result = (BasicSubsystem)region.find(
ssr.getSubsystemManifest().getSubsystemSymbolicNameHeader().getSymbolicName(),
ssr.getSubsystemManifest().getSubsystemVersionHeader().getVersion());
if (result != null) {
if (!result.getType().equals(ssr.getSubsystemManifest().getSubsystemTypeHeader().getType()))
throw new SubsystemException("Subsystem already exists in target region but has a different type: " + location);
}
else {
result = new BasicSubsystem(ssr, deploymentManifest);
}
}
checkLifecyclePermission(result);
return (BasicSubsystem)ResourceInstaller.newInstance(coordination, result, parent).install();
}
catch (Throwable t) {
coordination.fail(t);
}
finally {
try {
coordination.end();
}
catch (CoordinationException e) {
Throwable t = e.getCause();
if (t instanceof SubsystemException)
throw (SubsystemException)t;
if (t instanceof SecurityException)
throw (SecurityException)t;
throw new SubsystemException(t);
}
}
}
finally {
// Release the global write lock.
Activator.getInstance().getLockingStrategy().writeUnlock();
}
return result;
}
private void checkLifecyclePermission(final BasicSubsystem subsystem) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
SecurityManager.checkLifecyclePermission(subsystem);
return null;
}
},
context);
}
}
| 8,644 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/StartAction.java | /*
* 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.subsystem.core.internal;
import java.io.IOException;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.aries.subsystem.ContentHandler;
import org.apache.aries.subsystem.core.archive.ExportPackageCapability;
import org.apache.aries.subsystem.core.archive.ExportPackageHeader;
import org.apache.aries.subsystem.core.archive.ProvideCapabilityCapability;
import org.apache.aries.subsystem.core.archive.ProvideCapabilityHeader;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.apache.aries.subsystem.core.archive.SubsystemExportServiceCapability;
import org.apache.aries.subsystem.core.archive.SubsystemExportServiceHeader;
import org.apache.aries.subsystem.core.internal.BundleResourceInstaller.BundleConstituent;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionFilter;
import org.eclipse.equinox.region.RegionFilterBuilder;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.startlevel.BundleStartLevel;
import org.osgi.framework.startlevel.FrameworkStartLevel;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.coordinator.CoordinationException;
import org.osgi.service.coordinator.Participant;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StartAction extends AbstractAction {
public static enum Restriction {
NONE,
INSTALL_ONLY,
RESOLVE_ONLY
}
private static final Logger logger = LoggerFactory.getLogger(StartAction.class);
private final Coordination coordination;
private final BasicSubsystem instigator;
private final Restriction restriction;
public StartAction(BasicSubsystem instigator, BasicSubsystem requestor, BasicSubsystem target) {
this(instigator, requestor, target, Restriction.NONE);
}
public StartAction(BasicSubsystem instigator, BasicSubsystem requestor, BasicSubsystem target, Restriction restriction) {
this(instigator, requestor, target, null, restriction);
}
public StartAction(BasicSubsystem instigator, BasicSubsystem requestor, BasicSubsystem target, Coordination coordination) {
this(instigator, requestor, target, coordination, Restriction.NONE);
}
public StartAction(BasicSubsystem instigator, BasicSubsystem requestor, BasicSubsystem target, Coordination coordination, Restriction restriction) {
super(requestor, target, false);
this.instigator = instigator;
this.coordination = coordination;
this.restriction = restriction;
}
private static boolean isTargetStartable(BasicSubsystem instigator, BasicSubsystem requestor, BasicSubsystem target) {
State state = target.getState();
// The following states are illegal.
if (EnumSet.of(State.INSTALL_FAILED, State.UNINSTALLED).contains(state))
throw new SubsystemException("Cannot start from state " + state);
// The following states mean the requested state has already been attained.
if (State.ACTIVE.equals(state))
return false;
// Always start if target is content of requestor.
if (!Utils.isContent(requestor, target)) {
// Always start if target is a dependency of requestor.
if (!Utils.isDependency(requestor, target)) {
// Always start if instigator equals target (explicit start).
if (!instigator.equals(target)) {
// Don't start if instigator is root (restart) and target is not ready.
if (instigator.isRoot() && !target.isReadyToStart()) {
return false;
}
}
}
}
return true;
}
private void installDependencies(BasicSubsystem target, Coordination coordination) throws Exception {
for (Subsystem parent : target.getParents()) {
AccessController.doPrivileged(new StartAction(instigator, target, (BasicSubsystem)parent, coordination, Restriction.INSTALL_ONLY));
}
installDependencies(Collections.<Subsystem>singletonList(target), coordination);
for (Subsystem child : Activator.getInstance().getSubsystems().getChildren(target)) {
AccessController.doPrivileged(new StartAction(instigator, target, (BasicSubsystem)child, coordination, Restriction.INSTALL_ONLY));
}
}
private static void installDependencies(Collection<Subsystem> subsystems, Coordination coordination) throws Exception {
for (Subsystem subsystem : subsystems) {
if (State.INSTALLING.equals(subsystem.getState())) {
BasicSubsystem bs = (BasicSubsystem)subsystem;
bs.computeDependenciesPostInstallation(coordination);
new InstallDependencies().install(bs, null, coordination);
bs.setState(State.INSTALLED);
}
}
}
private Coordination createCoordination() {
Coordination coordination = this.coordination;
if (coordination == null) {
coordination = Utils.createCoordination(target);
}
return coordination;
}
private static class AffectedResources {
private final List<Resource> resources;
private final Collection<BasicSubsystem> subsystemResources;
AffectedResources(BasicSubsystem target) {
LinkedHashSet<Resource> resources = new LinkedHashSet<Resource>();
LinkedHashSet<BasicSubsystem> subsystemResources = new LinkedHashSet<BasicSubsystem>();
Subsystems subsystems = Activator.getInstance().getSubsystems();
for (Resource dep : subsystems.getResourcesReferencedBy(target)) {
if (dep instanceof BasicSubsystem
&& !subsystems.getChildren(target).contains(dep)) {
subsystemResources.add((BasicSubsystem)dep);
}
else if (dep instanceof BundleRevision) {
BundleConstituent constituent = new BundleConstituent(null, (BundleRevision)dep);
if (!target.getConstituents().contains(constituent)) {
for (BasicSubsystem constituentOf : subsystems.getSubsystemsByConstituent(
new BundleConstituent(null, (BundleRevision)dep))) {
subsystemResources.add(constituentOf);
}
}
}
resources.add(dep);
}
for (Subsystem child : subsystems.getChildren(target)) {
subsystemResources.add((BasicSubsystem)child);
resources.add((BasicSubsystem)child);
}
for (Resource resource : target.getResource().getSharedContent()) {
for (BasicSubsystem constituentOf : subsystems.getSubsystemsByConstituent(
resource instanceof BundleRevision ? new BundleConstituent(null, (BundleRevision)resource) : resource)) {
subsystemResources.add(constituentOf);
}
resources.add(resource);
}
subsystemResources.add(target);
this.resources = new ArrayList<Resource>(resources);
this.subsystemResources = subsystemResources;
}
List<Resource> resources() {
return resources;
}
Collection<BasicSubsystem> subsystems() {
return subsystemResources;
}
}
private static AffectedResources computeAffectedResources(BasicSubsystem target) {
return new AffectedResources(target);
}
@Override
public Object run() {
// Protect against re-entry now that cycles are supported.
if (!Activator.getInstance().getLockingStrategy().set(State.STARTING, target)) {
return null;
}
try {
AffectedResources affectedResources;
// We are now protected against re-entry.
// If necessary, install the dependencies.
if (State.INSTALLING.equals(target.getState()) && !Utils.isProvisionDependenciesInstall(target)) {
// Acquire the global write lock while installing dependencies.
Activator.getInstance().getLockingStrategy().writeLock();
try {
// We are now protected against installs, starts, stops, and uninstalls.
// We need a separate coordination when installing
// dependencies because cleaning up the temporary export
// sharing policies must be done while holding the write lock.
Coordination c = Utils.createCoordination(target);
try {
installDependencies(target, c);
// Associated subsystems must be computed after all dependencies
// are installed because some of the dependencies may be
// subsystems. This is safe to do while only holding the read
// lock since we know that nothing can be added or removed.
affectedResources = computeAffectedResources(target);
for (BasicSubsystem subsystem : affectedResources.subsystems()) {
if (State.INSTALLING.equals(subsystem.getState())
&& !Utils.isProvisionDependenciesInstall(subsystem)) {
installDependencies(subsystem, c);
}
}
// Downgrade to the read lock in order to prevent
// installs and uninstalls but allow starts and stops.
Activator.getInstance().getLockingStrategy().readLock();
}
catch (Throwable t) {
c.fail(t);
}
finally {
// This will clean up the temporary export sharing
// policies. Must be done while holding the write lock.
c.end();
}
}
finally {
// Release the global write lock as soon as possible.
Activator.getInstance().getLockingStrategy().writeUnlock();
}
}
else {
// Acquire the read lock in order to prevent installs and
// uninstalls but allow starts and stops.
Activator.getInstance().getLockingStrategy().readLock();
}
try {
// We now hold the read lock and are protected against installs
// and uninstalls.
if (Restriction.INSTALL_ONLY.equals(restriction)) {
return null;
}
// Compute associated subsystems here in case (1) they weren't
// computed previously while holding the write lock or (2) they
// were computed previously and more were subsequently added.
// This is safe to do while only holding the read lock since we
// know that nothing can be added or removed.
affectedResources = computeAffectedResources(target);
// Acquire the global mutual exclusion lock while acquiring the
// state change locks of affected subsystems.
Activator.getInstance().getLockingStrategy().lock();
try {
// We are now protected against cycles.
// Acquire the state change locks of affected subsystems.
Activator.getInstance().getLockingStrategy().lock(affectedResources.subsystems());
}
finally {
// Release the global mutual exclusion lock as soon as possible.
Activator.getInstance().getLockingStrategy().unlock();
}
Coordination coordination = this.coordination;
try {
coordination = createCoordination();
// We are now protected against other starts and stops of the affected subsystems.
if (!isTargetStartable(instigator, requestor, target)) {
return null;
}
// Resolve if necessary.
if (State.INSTALLED.equals(target.getState()))
resolve(instigator, target, target, coordination, affectedResources.subsystems());
if (Restriction.RESOLVE_ONLY.equals(restriction))
return null;
target.setState(State.STARTING);
// Be sure to set the state back to RESOLVED if starting fails.
coordination.addParticipant(new Participant() {
@Override
public void ended(Coordination coordination) throws Exception {
// Nothing.
}
@Override
public void failed(Coordination coordination) throws Exception {
target.setState(State.RESOLVED);
}
});
SubsystemContentHeader header = target.getSubsystemManifest().getSubsystemContentHeader();
if (header != null)
Collections.sort(affectedResources.resources(), new StartResourceComparator(header));
for (Resource resource : affectedResources.resources())
startResource(resource, coordination);
target.setState(State.ACTIVE);
}
catch (Throwable t) {
// We catch exceptions and fail the coordination here to
// ensure we are still holding the state change locks when
// the participant sets the state to RESOLVED.
coordination.fail(t);
}
finally {
try {
// Don't end a coordination that was not begun as part
// of this start action.
if (coordination.getName().equals(Utils.computeCoordinationName(target))) {
coordination.end();
}
}
finally {
// Release the state change locks of affected subsystems.
Activator.getInstance().getLockingStrategy().unlock(affectedResources.subsystems());
}
}
}
finally {
// Release the read lock.
Activator.getInstance().getLockingStrategy().readUnlock();
}
}
catch (CoordinationException e) {
Throwable t = e.getCause();
if (t == null) {
throw new SubsystemException(e);
}
if (t instanceof SecurityException) {
throw (SecurityException)t;
}
if (t instanceof SubsystemException) {
throw (SubsystemException)t;
}
throw new SubsystemException(t);
}
finally {
// Protection against re-entry no longer required.
Activator.getInstance().getLockingStrategy().unset(State.STARTING, target);
}
return null;
}
private static Collection<Bundle> getBundles(BasicSubsystem subsystem) {
Collection<Resource> constituents = Activator.getInstance().getSubsystems().getConstituents(subsystem);
ArrayList<Bundle> result = new ArrayList<Bundle>(constituents.size());
for (Resource resource : constituents) {
if (resource instanceof BundleRevision)
result.add(((BundleRevision)resource).getBundle());
}
result.trimToSize();
return result;
}
private static void emitResolvingEvent(BasicSubsystem subsystem) {
// Don't propagate a RESOLVING event if this is a persisted subsystem
// that is already RESOLVED.
if (State.INSTALLED.equals(subsystem.getState()))
subsystem.setState(State.RESOLVING);
}
private static void emitResolvedEvent(BasicSubsystem subsystem) {
// No need to propagate a RESOLVED event if this is a persisted
// subsystem already in the RESOLVED state.
if (State.RESOLVING.equals(subsystem.getState()))
subsystem.setState(State.RESOLVED);
}
private static void resolveSubsystems(BasicSubsystem instigator, BasicSubsystem target, Coordination coordination, Collection<BasicSubsystem> subsystems) throws Exception {
for (BasicSubsystem subsystem : subsystems) {
resolveSubsystem(instigator, target, subsystem, coordination);
}
}
private static void resolveSubsystem(BasicSubsystem instigator, BasicSubsystem target, BasicSubsystem subsystem, Coordination coordination) throws Exception {
State state = subsystem.getState();
if (State.INSTALLED.equals(state)) {
if (target.equals(subsystem)) {
resolve(instigator, target, subsystem, coordination, Collections.<BasicSubsystem>emptyList());
}
else {
AccessController.doPrivileged(new StartAction(instigator, target, subsystem, coordination, Restriction.RESOLVE_ONLY));
}
}
}
private static void resolveBundles(BasicSubsystem subsystem) {
FrameworkWiring frameworkWiring = Activator.getInstance().getBundleContext().getBundle(0)
.adapt(FrameworkWiring.class);
// TODO I think this is insufficient. Do we need both
// pre-install and post-install environments for the Resolver?
Collection<Bundle> bundles = getBundles(subsystem);
if (!frameworkWiring.resolveBundles(bundles)) {
handleFailedResolution(subsystem, bundles, frameworkWiring);
}
}
private static void resolve(BasicSubsystem instigator, BasicSubsystem target, BasicSubsystem subsystem, Coordination coordination, Collection<BasicSubsystem> subsystems) {
emitResolvingEvent(subsystem);
try {
// The root subsystem should follow the same event pattern for
// state transitions as other subsystems. However, an unresolvable
// root subsystem should have no effect, so there's no point in
// actually doing the resolution work.
if (!subsystem.isRoot()) {
setExportIsolationPolicy(subsystem, coordination);
resolveSubsystems(instigator, target, coordination, subsystems);
resolveBundles(subsystem);
}
emitResolvedEvent(subsystem);
}
catch (Throwable t) {
subsystem.setState(State.INSTALLED);
if (t instanceof SubsystemException)
throw (SubsystemException)t;
throw new SubsystemException(t);
}
}
private static void setExportIsolationPolicy(final BasicSubsystem subsystem, Coordination coordination) throws InvalidSyntaxException {
if (!subsystem.isComposite())
return;
final Region from = ((BasicSubsystem)subsystem.getParents().iterator().next()).getRegion();
final Region to = subsystem.getRegion();
RegionFilterBuilder builder = from.getRegionDigraph().createRegionFilterBuilder();
setExportIsolationPolicy(builder, subsystem.getDeploymentManifest().getExportPackageHeader(), subsystem);
setExportIsolationPolicy(builder, subsystem.getDeploymentManifest().getProvideCapabilityHeader(), subsystem);
setExportIsolationPolicy(builder, subsystem.getDeploymentManifest().getSubsystemExportServiceHeader(), subsystem);
RegionFilter regionFilter = builder.build();
if (regionFilter.getSharingPolicy().isEmpty())
return;
if (logger.isDebugEnabled())
logger.debug("Establishing region connection: from=" + from
+ ", to=" + to + ", filter=" + regionFilter);
try {
from.connectRegion(to, regionFilter);
}
catch (BundleException e) {
// TODO Assume this means that the export sharing policy has already
// been set. Bad assumption?
return;
}
coordination.addParticipant(new Participant() {
@Override
public void ended(Coordination coordination) throws Exception {
// It may be necessary to rollback the export sharing policy
// even when the coordination did not fail. For example, this
// might have been a subsystem whose export sharing policy was
// set just in case it offered dependencies for some other
// subsystem.
unsetExportIsolationPolicyIfNecessary();
}
@Override
public void failed(Coordination coordination) throws Exception {
// Nothing to do because a coordination is always ended.
}
private void unsetExportIsolationPolicyIfNecessary() throws BundleException, InvalidSyntaxException {
if (!EnumSet.of(State.INSTALLING, State.INSTALLED).contains(subsystem.getState())) {
// The subsystem is either RESOLVED or ACTIVE and therefore
// does not require a rollback.
return;
}
// The subsystem is either INSTALLING or INSTALLED and therefore
// requires a rollback since the export sharing policy must only
// be set upon entering the RESOLVED state.
RegionUpdater updater = new RegionUpdater(from, to);
updater.addRequirements(null);
}
});
}
private static void setExportIsolationPolicy(RegionFilterBuilder builder, ExportPackageHeader header, BasicSubsystem subsystem) throws InvalidSyntaxException {
if (header == null)
return;
String policy = RegionFilter.VISIBLE_PACKAGE_NAMESPACE;
for (ExportPackageCapability capability : header.toCapabilities(subsystem)) {
StringBuilder filter = new StringBuilder("(&");
for (Entry<String, Object> attribute : capability.getAttributes().entrySet())
filter.append('(').append(attribute.getKey()).append('=').append(attribute.getValue()).append(')');
filter.append(')');
if (logger.isDebugEnabled())
logger.debug("Allowing " + policy + " of " + filter);
builder.allow(policy, filter.toString());
}
}
private static void setExportIsolationPolicy(RegionFilterBuilder builder, ProvideCapabilityHeader header, BasicSubsystem subsystem) throws InvalidSyntaxException {
if (header == null)
return;
for (ProvideCapabilityHeader.Clause clause : header.getClauses()) {
ProvideCapabilityCapability capability = new ProvideCapabilityCapability(clause, subsystem);
String policy = capability.getNamespace();
Set<Entry<String, Object>> entrySet = capability.getAttributes().entrySet();
StringBuilder filter = new StringBuilder();
if (entrySet.size() > 1) {
filter.append("(&");
}
for (Entry<String, Object> attribute : capability.getAttributes().entrySet()) {
filter.append('(').append(attribute.getKey()).append('=').append(attribute.getValue()).append(')');
}
if (entrySet.size() > 1) {
filter.append(')');
}
if (logger.isDebugEnabled()) {
logger.debug("Allowing policy {} with filter {}", policy, filter);
}
if (filter.length() == 0) {
builder.allowAll(policy);
}
else {
builder.allow(policy, filter.toString());
}
}
}
private static void setExportIsolationPolicy(RegionFilterBuilder builder, SubsystemExportServiceHeader header, BasicSubsystem subsystem) throws InvalidSyntaxException {
if (header == null)
return;
String policy = RegionFilter.VISIBLE_SERVICE_NAMESPACE;
for (SubsystemExportServiceHeader.Clause clause : header.getClauses()) {
SubsystemExportServiceCapability capability = new SubsystemExportServiceCapability(clause, subsystem);
String filter = capability.getDirectives().get(SubsystemExportServiceCapability.DIRECTIVE_FILTER);
if (logger.isDebugEnabled())
logger.debug("Allowing " + policy + " of " + filter);
builder.allow(policy, filter);
}
}
private void startBundleResource(Resource resource, Coordination coordination) throws BundleException {
if (target.isRoot())
// Starting the root subsystem should not affect bundles within the
// root region.
return;
if (Utils.isRegionContextBundle(resource))
// The region context bundle was persistently started elsewhere.
return;
final Bundle bundle = ((BundleRevision)resource).getBundle();
if ((bundle.getState() & (Bundle.STARTING | Bundle.ACTIVE)) != 0)
return;
if (logger.isDebugEnabled()) {
int bundleStartLevel = bundle.adapt(BundleStartLevel.class).getStartLevel();
Bundle systemBundle=Activator.getInstance().getBundleContext().getBundle(0);
int fwStartLevel = systemBundle.adapt(FrameworkStartLevel.class).getStartLevel();
logger.debug("StartAction: starting bundle " + bundle.getSymbolicName()
+ " " + bundle.getVersion().toString()
+ " bundleStartLevel=" + bundleStartLevel
+ " frameworkStartLevel=" + fwStartLevel);
}
bundle.start(Bundle.START_TRANSIENT | Bundle.START_ACTIVATION_POLICY);
if (logger.isDebugEnabled()) {
logger.debug("StartAction: bundle " + bundle.getSymbolicName()
+ " " + bundle.getVersion().toString()
+ " started correctly");
}
if (coordination == null)
return;
coordination.addParticipant(new Participant() {
public void ended(Coordination coordination) throws Exception {
// noop
}
public void failed(Coordination coordination) throws Exception {
bundle.stop();
}
});
}
private void startResource(Resource resource, Coordination coordination) throws BundleException, IOException {
String type = ResourceHelper.getTypeAttribute(resource);
if (SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION.equals(type)
|| SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type)
|| SubsystemConstants.SUBSYSTEM_TYPE_FEATURE.equals(type)) {
startSubsystemResource(resource, coordination);
} else if (IdentityNamespace.TYPE_BUNDLE.equals(type)) {
startBundleResource(resource, coordination);
} else if (IdentityNamespace.TYPE_FRAGMENT.equals(type)) {
// Fragments are not started.
} else {
if (!startCustomHandler(resource, type, coordination))
throw new SubsystemException("Unsupported resource type: " + type);
}
}
private boolean startCustomHandler(Resource resource, String type, Coordination coordination) {
ServiceReference<ContentHandler> customHandlerRef = CustomResources.getCustomContentHandler(target, type);
if (customHandlerRef != null) {
ContentHandler customHandler = target.getBundleContext().getService(customHandlerRef);
if (customHandler != null) {
try {
customHandler.start(ResourceHelper.getSymbolicNameAttribute(resource), type, target, coordination);
return true;
} finally {
target.getBundleContext().ungetService(customHandlerRef);
}
}
}
return false;
}
private void startSubsystemResource(Resource resource, final Coordination coordination) throws IOException {
final BasicSubsystem subsystem = (BasicSubsystem)resource;
if (!isTargetStartable(instigator, target, subsystem)) {
return;
}
// Subsystems that are content resources of another subsystem must have
// their autostart setting set to started.
if (Utils.isContent(this.target, subsystem))
subsystem.setAutostart(true);
new StartAction(instigator, target, subsystem, coordination).run();
if (coordination == null)
return;
coordination.addParticipant(new Participant() {
public void ended(Coordination coordination) throws Exception {
// noop
}
public void failed(Coordination coordination) throws Exception {
new StopAction(target, subsystem, !subsystem.isRoot()).run();
}
});
}
private static void handleFailedResolution(BasicSubsystem subsystem, Collection<Bundle> bundles, FrameworkWiring wiring) {
logFailedResolution(subsystem, bundles);
throw new SubsystemException("Framework could not resolve the bundles: " + bundles);
}
private static void logFailedResolution(BasicSubsystem subsystem, Collection<Bundle> bundles) {
//work out which bundles could not be resolved
Collection<Bundle> unresolved = new ArrayList<Bundle>();
StringBuilder diagnostics = new StringBuilder();
diagnostics.append(String.format("Unable to resolve bundles for subsystem/version/id %s/%s/%s:\n",
subsystem.getSymbolicName(), subsystem.getVersion(), subsystem.getSubsystemId()));
String fmt = "%d : STATE %s : %s : %s : %s";
for(Bundle bundle:bundles){
if((bundle.getState() & Bundle.RESOLVED) != Bundle.RESOLVED) {
unresolved.add(bundle);
}
String state = null;
switch(bundle.getState()) {
case Bundle.ACTIVE :
state = "ACTIVE";
break;
case Bundle.INSTALLED :
state = "INSTALLED";
break;
case Bundle.RESOLVED :
state = "RESOLVED";
break;
case Bundle.STARTING :
state = "STARTING";
break;
case Bundle.STOPPING :
state = "STOPPING";
break;
case Bundle.UNINSTALLED :
state = "UNINSTALLED";
break;
default :
//convert common states to text otherwise default to just showing the ID
state = "[" + Integer.toString(bundle.getState()) + "]";
break;
}
diagnostics.append(String.format(fmt, bundle.getBundleId(), state,
bundle.getSymbolicName(), bundle.getVersion().toString(),
bundle.getLocation()));
diagnostics.append("\n");
}
logger.error(diagnostics.toString());
}
static void setExportPolicyOfAllInstallingSubsystemsWithProvisionDependenciesResolve(Coordination coordination) throws InvalidSyntaxException {
for (BasicSubsystem subsystem : Activator.getInstance().getSubsystems().getSubsystems()) {
if (!State.INSTALLING.equals(subsystem.getState())
|| Utils.isProvisionDependenciesInstall(subsystem)) {
continue;
}
setExportIsolationPolicy(subsystem, coordination);
}
}
}
| 8,645 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ThreadLocalSubsystem.java | /*
* 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.subsystem.core.internal;
public class ThreadLocalSubsystem {
private static ThreadLocal<BasicSubsystem> subsystem = new ThreadLocal<BasicSubsystem>();
public static BasicSubsystem get() {
return subsystem.get();
}
public static void remove() {
subsystem.remove();
}
public static void set(BasicSubsystem value) {
subsystem.set(value);
}
}
| 8,646 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BundleEventHook.java | /*
* 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.subsystem.core.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.aries.subsystem.core.internal.BundleResourceInstaller.BundleConstituent;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionDigraph;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.hooks.bundle.EventHook;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Resource;
public class BundleEventHook implements EventHook {
private final Activator activator;
private final ConcurrentHashMap<Bundle, BundleRevision> bundleToRevision;
private boolean active;
private List<BundleEvent> events;
public BundleEventHook() {
activator = Activator.getInstance();
bundleToRevision = new ConcurrentHashMap<Bundle, BundleRevision>();
}
@Override
public void event(BundleEvent event, Collection<BundleContext> contexts) {
if ((event.getType() & (BundleEvent.INSTALLED | BundleEvent.UNINSTALLED)) == 0)
return;
// Protect against deadlock when the bundle event hook receives an
// event before subsystems has fully initialized, in which case the
// events are queued and processed once initialization is complete.
synchronized (this) {
if (!active) {
if (events == null)
events = new ArrayList<BundleEvent>();
events.add(event);
return;
}
}
handleEvent(event);
}
// Events must be processed in order. Don't allow events to go through
// synchronously before all pending events have been processed.
synchronized void activate() {
active = true;
processPendingEvents();
}
synchronized void deactivate() {
active = false;
}
synchronized void processPendingEvents() {
if (events == null)
return;
for (BundleEvent event : events)
handleEvent(event);
events = null;
}
private Subsystems getSubsystems() {
return activator.getSubsystems();
}
/*
* Note that because some events may be processed asynchronously, we can no
* longer rely on the guarantees that a synchronous event brings. For
* example, bundle revisions adapted from bundles included in events may be
* null.
*/
private void handleEvent(BundleEvent event) {
switch (event.getType()) {
case BundleEvent.INSTALLED:
handleInstalledEvent(event);
break;
// TODO I think updates will play a role here as well. Need to keep
// track of the most current bundle revision?
case BundleEvent.UNINSTALLED:
handleUninstalledEvent(event);
break;
}
}
/*
* This method guards against an uninstalled origin bundle. Guards against a
* null bundle revision are done elsewhere. It is assumed the bundle
* revision is never null once we get here.
*/
private void handleExplicitlyInstalledBundleBundleContext(BundleRevision originRevision, BundleRevision bundleRevision) {
/*
* The newly installed bundle must become a constituent of all the Subsystems of which the bundle
* whose context was used to perform the install is a constituent (OSGI.enterprise spec. 134.10.1.1).
*/
Collection<BasicSubsystem> subsystems = getSubsystems().getSubsystemsReferencing(originRevision);
boolean bundleRevisionInstalled=false;
for (BasicSubsystem s : subsystems) {
for (Resource constituent : s.getConstituents()) {
if (constituent instanceof BundleConstituent) {
BundleRevision rev = ((BundleConstituent) constituent).getRevision();
if (originRevision.equals(rev)) {
Utils.installResource(bundleRevision, s);
bundleRevisionInstalled=true;
}
}
}
}
/* if the bundle is not made constituent of any subsystem then make it constituent of root */
if (!bundleRevisionInstalled) {
Utils.installResource(bundleRevision, getSubsystems().getRootSubsystem());
}
}
private void handleExplicitlyInstalledBundleRegionDigraph(Bundle origin, BundleRevision bundleRevision) {
// The bundle needs to be associated with the scoped subsystem of
// the region used to install the bundle.
RegionDigraph digraph = activator.getRegionDigraph();
Region region = digraph.getRegion(origin);
for (BasicSubsystem s : getSubsystems().getSubsystems()) {
if ((s.isApplication() || s.isComposite())
&& region.equals(s.getRegion())) {
Utils.installResource(bundleRevision, s);
return;
}
}
throw new IllegalStateException("No subsystem found for bundle " + bundleRevision + " in region " + region);
}
private void handleInstalledEvent(BundleEvent event) {
Bundle origin = event.getOrigin();
BundleRevision originRevision = origin.adapt(BundleRevision.class);
Bundle bundle = event.getBundle();
BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);
if (bundleRevision == null) {
// The event is being processed asynchronously and the installed
// bundle has been uninstalled. Nothing we can do.
return;
}
bundleToRevision.put(bundle, bundleRevision);
// Only handle explicitly installed bundles. An explicitly installed
// bundle is a bundle that was installed using some other bundle's
// BundleContext or using RegionDigraph.
if (ThreadLocalSubsystem.get() != null
// Region context bundles must be treated as explicit installations.
|| bundleRevision.getSymbolicName().startsWith(Constants.RegionContextBundleSymbolicNamePrefix)) {
return;
}
// Indicate that a bundle is being explicitly installed on this thread.
// This protects against attempts to resolve the bundle as part of
// processing the explicit installation.
ThreadLocalBundleRevision.set(bundleRevision);
try {
if ("org.eclipse.equinox.region".equals(origin.getSymbolicName())) {
// The bundle was installed using RegionDigraph.
handleExplicitlyInstalledBundleRegionDigraph(origin, bundleRevision);
}
else {
// The bundle was installed using some other bundle's BundleContext.
handleExplicitlyInstalledBundleBundleContext(originRevision, bundleRevision);
}
}
finally {
// Always remove the bundle so that it can be resolved no matter
// what happens here.
ThreadLocalBundleRevision.remove();
}
}
@SuppressWarnings("unchecked")
private void handleUninstalledEvent(BundleEvent event) {
Bundle bundle = event.getBundle();
BundleRevision revision = bundleToRevision.remove(bundle);
if (ThreadLocalSubsystem.get() != null
|| (revision == null ? false :
// Region context bundles must be treated as explicit installations.
revision.getSymbolicName().startsWith(Constants.RegionContextBundleSymbolicNamePrefix))) {
return;
}
Collection<BasicSubsystem> subsystems;
if (revision == null) {
// The bundle was installed while the bundle event hook was unregistered.
Object[] o = activator.getSubsystems().getSubsystemsByBundle(bundle);
if (o == null)
return;
revision = (BundleRevision)o[0];
subsystems = (Collection<BasicSubsystem>)o[1];
}
else {
subsystems = activator.getSubsystems().getSubsystemsByConstituent(new BundleConstituent(null, revision));
}
for (BasicSubsystem subsystem : subsystems) {
ResourceUninstaller.newInstance(revision, subsystem).uninstall();
}
}
}
| 8,647 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/AbstractCapability.java | /*
* 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.subsystem.core.internal;
import org.osgi.resource.Capability;
public abstract class AbstractCapability implements Capability {
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Capability))
return false;
Capability c = (Capability)o;
return c.getNamespace().equals(getNamespace())
&& c.getAttributes().equals(getAttributes())
&& c.getDirectives().equals(getDirectives())
&& c.getResource().equals(getResource());
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getNamespace().hashCode();
result = 31 * result + getAttributes().hashCode();
result = 31 * result + getDirectives().hashCode();
result = 31 * result + getResource().hashCode();
return result;
}
@Override
public String toString() {
return new StringBuilder().append("[Capability: ")
.append("namespace=").append(getNamespace())
.append(", attributes=").append(getAttributes())
.append(", directives=").append(getDirectives())
.append(", resource=").append(getResource()).append(']')
.toString();
}
}
| 8,648 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemResource.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.subsystem.core.internal;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.AriesSubsystemParentsHeader;
import org.apache.aries.subsystem.core.archive.Attribute;
import org.apache.aries.subsystem.core.archive.DeployedContentHeader;
import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.apache.aries.subsystem.core.archive.Header;
import org.apache.aries.subsystem.core.archive.ImportPackageHeader;
import org.apache.aries.subsystem.core.archive.ImportPackageRequirement;
import org.apache.aries.subsystem.core.archive.ProvisionResourceHeader;
import org.apache.aries.subsystem.core.archive.RequireBundleHeader;
import org.apache.aries.subsystem.core.archive.RequireBundleRequirement;
import org.apache.aries.subsystem.core.archive.RequireCapabilityHeader;
import org.apache.aries.subsystem.core.archive.RequireCapabilityRequirement;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.apache.aries.subsystem.core.archive.SubsystemExportServiceHeader;
import org.apache.aries.subsystem.core.archive.SubsystemImportServiceHeader;
import org.apache.aries.subsystem.core.archive.SubsystemImportServiceRequirement;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.aries.util.filesystem.IDirectory;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionDigraph;
import org.eclipse.equinox.region.RegionFilter;
import org.eclipse.equinox.region.RegionFilterBuilder;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.namespace.ExecutionEnvironmentNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.NativeNamespace;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.resource.Wire;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.coordinator.Participant;
import org.osgi.service.resolver.ResolutionException;
import org.osgi.service.resolver.ResolveContext;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class SubsystemResource implements Resource {
private Region region;
private final List<Capability> capabilities;
private final DeploymentManifest deploymentManifest;
private final Collection<Resource> installableContent = new HashSet<Resource>();
private final Collection<Resource> installableDependencies = new HashSet<Resource>();
private final Collection<Resource> mandatoryResources = new HashSet<Resource>();
private final Collection<DeployedContentHeader.Clause> missingResources = new HashSet<DeployedContentHeader.Clause>();
private final Collection<Resource> optionalResources = new HashSet<Resource>();
private final BasicSubsystem parent;
private final RawSubsystemResource resource;
private final Collection<Resource> sharedContent = new HashSet<Resource>();
private final Collection<Resource> sharedDependencies = new HashSet<Resource>();
public SubsystemResource(String location, IDirectory content, BasicSubsystem parent, Coordination coordination) throws URISyntaxException, IOException, ResolutionException, BundleException, InvalidSyntaxException {
this(new RawSubsystemResource(location, content, parent), parent, coordination);
}
public SubsystemResource(RawSubsystemResource resource, BasicSubsystem parent, Coordination coordination) throws IOException, BundleException, InvalidSyntaxException, URISyntaxException {
this.parent = parent;
this.resource = resource;
computeContentResources(resource.getDeploymentManifest());
capabilities = computeCapabilities();
if (this.getSubsystemManifest().getSubsystemTypeHeader().getAriesProvisionDependenciesDirective().isInstall()) {
/* compute dependencies now only if we intend to provision them during install */
computeDependencies(resource.getDeploymentManifest(), coordination);
}
deploymentManifest = computeDeploymentManifest();
}
public SubsystemResource(File file) throws IOException, URISyntaxException, ResolutionException, BundleException, InvalidSyntaxException {
this(null, FileSystem.getFSRoot(file));
}
public SubsystemResource(BasicSubsystem subsystem, IDirectory directory) throws IOException, URISyntaxException, ResolutionException, BundleException, InvalidSyntaxException {
if (subsystem == null) {
// This is intended to only support the case where the root subsystem
// is being initialized from a non-persistent state.
parent = null;
}
else {
parent = Utils.findScopedSubsystemInRegion(subsystem);
}
resource = new RawSubsystemResource(directory, parent);
deploymentManifest = resource.getDeploymentManifest();
computeContentResources(deploymentManifest);
capabilities = computeCapabilities();
if (getSubsystemManifest().getSubsystemTypeHeader().getAriesProvisionDependenciesDirective().isInstall()) {
/* compute dependencies if we intend to provision them during install */
computeDependencies(resource.getDeploymentManifest(), null);
}
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof SubsystemResource))
return false;
SubsystemResource that = (SubsystemResource)o;
return getLocation().equals(that.getLocation());
}
@Override
public List<Capability> getCapabilities(String namespace) {
return Collections.unmodifiableList(capabilities);
}
private List<Capability> computeCapabilities() throws InvalidSyntaxException {
List<Capability> capabilities = new ArrayList<Capability>();
if (isScoped())
computeScopedCapabilities(capabilities);
else
computeUnscopedCapabilities(capabilities);
return capabilities;
}
private void computeUnscopedCapabilities(List<Capability> capabilities) {
capabilities.addAll(resource.getCapabilities(null));
for (Resource r : getContentResources())
capabilities.addAll(r.getCapabilities(null));
}
private void computeScopedCapabilities(List<Capability> capabilities) throws InvalidSyntaxException {
capabilities.addAll(resource.getCapabilities(null));
computeOsgiServiceCapabilities(capabilities);
}
private void computeOsgiServiceCapabilities(List<Capability> capabilities) throws InvalidSyntaxException {
SubsystemExportServiceHeader header = getSubsystemManifest().getSubsystemExportServiceHeader();
if (header == null)
return;
for (Resource resource : getContentResources())
capabilities.addAll(header.toCapabilities(resource));
}
public DeploymentManifest getDeploymentManifest() {
return deploymentManifest;
}
public long getId() {
return resource.getId();
}
public Collection<Resource> getInstallableContent() {
return installableContent;
}
public Collection<Resource> getInstallableDependencies() {
return installableDependencies;
}
public org.apache.aries.subsystem.core.repository.Repository getLocalRepository() {
return resource.getLocalRepository();
}
public String getLocation() {
return resource.getLocation().getValue();
}
Collection<Resource> getMandatoryResources() {
return mandatoryResources;
}
public Collection<DeployedContentHeader.Clause> getMissingResources() {
return missingResources;
}
Collection<Resource> getOptionalResources() {
return optionalResources;
}
public Collection<BasicSubsystem> getParents() {
if (parent == null) {
AriesSubsystemParentsHeader header = getDeploymentManifest().getAriesSubsystemParentsHeader();
if (header == null)
return Collections.emptyList();
Collection<AriesSubsystemParentsHeader.Clause> clauses = header.getClauses();
Collection<BasicSubsystem> result = new ArrayList<BasicSubsystem>(clauses.size());
Subsystems subsystems = Activator.getInstance().getSubsystems();
for (AriesSubsystemParentsHeader.Clause clause : clauses) {
result.add(subsystems.getSubsystemById(clause.getId()));
}
return result;
}
return Collections.singleton(parent);
}
public synchronized Region getRegion() throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
if (region == null) {
region = createRegion(getId());
Coordination coordination = Activator.getInstance().getCoordinator().peek();
coordination.addParticipant(new Participant() {
@Override
public void ended(Coordination arg0) throws Exception {
// Nothing.
}
@Override
public void failed(Coordination arg0) throws Exception {
if (isScoped())
region.getRegionDigraph().removeRegion(region);
}
});
if (!isApplication()) {
setImportIsolationPolicy();
}
}
return region;
}
@Override
public List<Requirement> getRequirements(String namespace) {
if (isScoped())
return resource.getRequirements(namespace);
else {
ArrayList<Requirement> result = new ArrayList<Requirement>();
result.addAll(resource.getRequirements(namespace));
for (Resource r : getContentResources())
result.addAll(r.getRequirements(namespace));
result.trimToSize();
return result;
}
}
public Collection<Resource> getSharedContent() {
return sharedContent;
}
public Collection<Resource> getSharedDependencies() {
return sharedDependencies;
}
public SubsystemManifest getSubsystemManifest() {
return resource.getSubsystemManifest();
}
public Collection<TranslationFile> getTranslations() {
return resource.getTranslations();
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getLocation().hashCode();
return result;
}
private void addContentResource(Resource resource) {
if (resource == null)
return;
if (isMandatory(resource))
mandatoryResources.add(resource);
else
optionalResources.add(resource);
if (isInstallable(resource))
installableContent.add(resource);
else
sharedContent.add(resource);
}
private void addMissingResource(DeployedContentHeader.Clause resource) {
missingResources.add(resource);
}
private void addSubsystemServiceImportToSharingPolicy(
RegionFilterBuilder builder) throws InvalidSyntaxException, BundleException, IOException, URISyntaxException {
builder.allow(
RegionFilter.VISIBLE_SERVICE_NAMESPACE,
new StringBuilder("(&(")
.append(org.osgi.framework.Constants.OBJECTCLASS)
.append('=').append(Subsystem.class.getName())
.append(")(")
.append(Constants.SubsystemServicePropertyRegions)
.append('=').append(getRegion().getName())
.append("))").toString());
}
private void addSubsystemServiceImportToSharingPolicy(RegionFilterBuilder builder, Region to)
throws InvalidSyntaxException, BundleException, IOException, URISyntaxException {
Region root = Activator.getInstance().getSubsystems().getRootSubsystem().getRegion();
if (to.getName().equals(root.getName()))
addSubsystemServiceImportToSharingPolicy(builder);
else {
to = root;
builder = to.getRegionDigraph().createRegionFilterBuilder();
addSubsystemServiceImportToSharingPolicy(builder);
RegionFilter regionFilter = builder.build();
getRegion().connectRegion(to, regionFilter);
}
}
private void computeContentResources(DeploymentManifest manifest) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
if (manifest == null)
computeContentResources(getSubsystemManifest());
else {
DeployedContentHeader header = manifest.getDeployedContentHeader();
if (header == null)
return;
for (DeployedContentHeader.Clause clause : header.getClauses()) {
Resource resource = findContent(clause);
if (resource == null)
addMissingResource(clause);
else
addContentResource(resource);
}
}
}
private void computeContentResources(SubsystemManifest manifest) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
SubsystemContentHeader contentHeader = manifest.getSubsystemContentHeader();
if (contentHeader == null)
return;
for (SubsystemContentHeader.Clause clause : contentHeader.getClauses()) {
Requirement requirement = clause.toRequirement(this);
Resource resource = findContent(requirement);
if (resource == null) {
if (clause.isMandatory())
throw new SubsystemException("A required content resource could not be found. This means the resource was either missing or not recognized as a supported resource format due to, for example, an invalid bundle manifest or blueprint XML file. Turn on debug logging for more information. The resource was: " + requirement);
continue;
}
addContentResource(resource);
}
}
void computeDependencies(DeploymentManifest manifest, Coordination coordination) {
if (manifest == null) {
computeDependencies(getSubsystemManifest(), coordination);
}
else {
ProvisionResourceHeader header = manifest.getProvisionResourceHeader();
if (header == null)
return;
for (ProvisionResourceHeader.Clause clause : header.getClauses()) {
Resource resource = findDependency(clause);
if (resource == null)
throw new SubsystemException("A required dependency could not be found. This means the resource was either missing or not recognized as a supported resource format due to, for example, an invalid bundle manifest or blueprint XML file. Turn on debug logging for more information. The resource was: " + resource);
addDependency(resource);
}
}
}
private void addDependency(Resource resource) {
if (resource == null)
return;
if (isInstallable(resource))
installableDependencies.add(resource);
else
sharedDependencies.add(resource);
}
private void computeDependencies(SubsystemManifest manifest, Coordination coordination) {
try {
// The following line is necessary in order to ensure that the
// export sharing policies of composites are in place for capability
// validation.
StartAction.setExportPolicyOfAllInstallingSubsystemsWithProvisionDependenciesResolve(coordination);
Map<Resource, List<Wire>> resolution = Activator.getInstance().getResolver().resolve(createResolveContext());
setImportIsolationPolicy(resolution);
addDependencies(resolution);
}
catch (Exception e) {
Utils.handleTrowable(e);
}
}
private void addDependencies(Map<Resource, List<Wire>> resolution) {
for (Map.Entry<Resource, List<Wire>> entry : resolution.entrySet()) {
addDependencies(entry, resolution);
}
}
private void addDependencies(Map.Entry<Resource, List<Wire>> entry, Map<Resource, List<Wire>> resolution) {
addDependencies(entry.getKey(), entry, resolution);
}
private void addDependencies(Resource resource, Map.Entry<Resource, List<Wire>> entry, Map<Resource, List<Wire>> resolution) {
String type = ResourceHelper.getTypeAttribute(resource);
SubsystemContentHeader contentHeader = getSubsystemManifest().getSubsystemContentHeader();
if (!Constants.ResourceTypeSynthesized.equals(type) // Do not include synthetic resources as dependencies.
&& !contentHeader.contains(resource)) { // Do not include content as dependencies.
addDependency(resource);
}
}
private DeployedContentHeader computeDeployedContentHeader() {
Collection<Resource> content = getContentResources();
if (content.isEmpty())
return null;
return DeployedContentHeader.newInstance(content);
}
private DeploymentManifest computeDeploymentManifest() throws IOException {
DeploymentManifest result = computeExistingDeploymentManifest();
if (result != null)
return result;
result = new DeploymentManifest.Builder().manifest(resource.getSubsystemManifest())
.header(computeDeployedContentHeader())
.header(computeProvisionResourceHeader()).build();
return result;
}
private DeploymentManifest computeExistingDeploymentManifest() throws IOException {
return resource.getDeploymentManifest();
}
ProvisionResourceHeader computeProvisionResourceHeader() {
Collection<Resource> dependencies = getDependencies();
if (dependencies.isEmpty())
return null;
return ProvisionResourceHeader.newInstance(dependencies);
}
private Region createRegion(long id) throws BundleException {
if (!isScoped())
return getParents().iterator().next().getRegion();
Activator activator = Activator.getInstance();
RegionDigraph digraph = activator.getRegionDigraph();
if (getParents().isEmpty())
// This is the root subsystem. Associate it with the region in which
// the subsystems implementation bundle was installed.
return digraph.getRegion(activator.getBundleContext().getBundle());
String name = getSubsystemManifest()
.getSubsystemSymbolicNameHeader().getSymbolicName()
+ ';'
+ getSubsystemManifest().getSubsystemVersionHeader()
.getVersion()
+ ';'
+ getSubsystemManifest().getSubsystemTypeHeader()
.getType() + ';' + Long.toString(id);
Region region = digraph.getRegion(name);
// TODO New regions need to be cleaned up if this subsystem fails to
// install, but there's no access to the coordination here.
if (region == null)
return digraph.createRegion(name);
return region;
}
private ResolveContext createResolveContext() {
return new org.apache.aries.subsystem.core.internal.ResolveContext(this);
}
private Resource findContent(Requirement requirement) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
Map<Requirement, Collection<Capability>> map;
// TODO System repository for scoped subsystems should be searched in
// the case of a persisted subsystem.
if (isUnscoped()) {
map = Activator.getInstance().getSystemRepository().findProviders(Collections.singleton(requirement));
if (map.containsKey(requirement)) {
Collection<Capability> capabilities = map.get(requirement);
for (Capability capability : capabilities) {
Resource provider = capability.getResource();
if (provider instanceof BundleRevision) {
if (getRegion().contains(((BundleRevision)provider).getBundle())) {
return provider;
}
}
else if (provider instanceof BasicSubsystem) {
if (getRegion().equals(((BasicSubsystem)provider).getRegion())) {
return provider;
}
}
}
}
}
// First search the local repository.
map = resource.getLocalRepository().findProviders(Collections.singleton(requirement));
Collection<Capability> capabilities = map.get(requirement);
if (capabilities.isEmpty()) {
// Nothing found in the local repository so search the repository services.
capabilities = new RepositoryServiceRepository().findProviders(requirement);
}
if (capabilities.isEmpty()) {
// Nothing found period.
return null;
}
for (Capability capability : capabilities) {
if (!IdentityNamespace.TYPE_FRAGMENT.equals(
capability.getAttributes().get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE))) {
// Favor the first resource that is not a fragment bundle.
// See ARIES-1425.
return capability.getResource();
}
}
// Nothing here but fragment bundles. Return the first one.
return capabilities.iterator().next().getResource();
}
private Resource findContent(DeployedContentHeader.Clause clause) throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
Attribute attribute = clause.getAttribute(DeployedContentHeader.Clause.ATTRIBUTE_RESOURCEID);
long resourceId = attribute == null ? -1 : Long.parseLong(String.valueOf(attribute.getValue()));
if (resourceId != -1) {
String type = clause.getType();
if (IdentityNamespace.TYPE_BUNDLE.equals(type) || IdentityNamespace.TYPE_FRAGMENT.equals(type)) {
Bundle resource = Activator.getInstance().getBundleContext().getBundle(0).getBundleContext().getBundle(resourceId);
if (resource == null)
return null;
return resource.adapt(BundleRevision.class);
}
else
return Activator.getInstance().getSubsystems().getSubsystemById(resourceId);
}
return findContent(clause.toRequirement(this));
}
private Resource findDependency(ProvisionResourceHeader.Clause clause) {
Attribute attribute = clause.getAttribute(DeployedContentHeader.Clause.ATTRIBUTE_RESOURCEID);
long resourceId = attribute == null ? -1 : Long.parseLong(String.valueOf(attribute.getValue()));
if (resourceId != -1) {
String type = clause.getType();
if (IdentityNamespace.TYPE_BUNDLE.equals(type) || IdentityNamespace.TYPE_FRAGMENT.equals(type))
return Activator.getInstance().getBundleContext().getBundle(0).getBundleContext().getBundle(resourceId).adapt(BundleRevision.class);
else
return Activator.getInstance().getSubsystems().getSubsystemById(resourceId);
}
OsgiIdentityRequirement requirement = new OsgiIdentityRequirement(
clause.getPath(), clause.getDeployedVersion(),
clause.getType(), true);
List<Capability> capabilities = createResolveContext().findProviders(requirement);
if (capabilities.isEmpty())
return null;
return capabilities.get(0).getResource();
}
private Collection<Resource> getContentResources() {
Collection<Resource> result = new ArrayList<Resource>(installableContent.size() + sharedContent.size());
result.addAll(installableContent);
result.addAll(sharedContent);
return result;
}
private Collection<Resource> getDependencies() {
Collection<Resource> result = new ArrayList<Resource>(installableDependencies.size() + sharedDependencies.size());
result.addAll(installableDependencies);
result.addAll(sharedDependencies);
return result;
}
boolean isApplication() {
String type = resource.getSubsystemManifest().getSubsystemTypeHeader().getType();
return SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION.equals(type);
}
boolean isComposite() {
String type = resource.getSubsystemManifest().getSubsystemTypeHeader().getType();
return SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type);
}
boolean isContent(Resource resource) {
if (installableContent.contains(resource) || sharedContent.contains(resource)) {
return true;
}
// Allow for implicit subsystem installations. An implicit installation
// occurs when a subsystem containing other subsystems as content is
// installed. When identifying the region to be used for validation
// purposes during resolution, resources that are content of children
// must be treated as content of this subsystem. See ResolveContext.isValid().
for (Resource installableResource : installableContent) {
if (installableResource instanceof RawSubsystemResource) {
if (((RawSubsystemResource)installableResource).getSubsystemManifest().getSubsystemContentHeader().contains(resource)) {
return true;
}
}
}
return false;
}
private boolean isInstallable(Resource resource) {
return !isShared(resource);
}
private boolean isMandatory(Resource resource) {
SubsystemContentHeader header = this.resource.getSubsystemManifest().getSubsystemContentHeader();
if (header == null)
return false;
return header.isMandatory(resource);
}
boolean isRoot() {
return BasicSubsystem.ROOT_LOCATION.equals(getLocation());
}
private boolean isShared(Resource resource) {
return Utils.isSharedResource(resource);
}
private boolean isScoped() {
return isApplication() || isComposite();
}
private boolean isUnscoped() {
return !isScoped();
}
private void setImportIsolationPolicy(Map<Resource, List<Wire>> resolution) throws Exception {
if (!isApplication()) {
return;
}
SubsystemContentHeader contentHeader = getSubsystemManifest().getSubsystemContentHeader();
// Prepare the regions and filter builder to set the sharing policy.
Region from = getRegion();
Region to = ((BasicSubsystem)getParents().iterator().next()).getRegion();
RegionFilterBuilder builder = from.getRegionDigraph().createRegionFilterBuilder();
// Always provide visibility to this subsystem's service registration.
addSubsystemServiceImportToSharingPolicy(builder, to);
for (Resource resource : resolution.keySet()) {
if (!contentHeader.contains(resource)) {
continue;
}
// If the resource is content but the wire provider is not,
// the sharing policy must be updated.
List<Wire> wires = resolution.get(resource);
for (Wire wire : wires) {
Resource provider = wire.getProvider();
// First check: If the provider is content there is no need to
// update the sharing policy because the capability is already
// visible.
if (contentHeader.contains(provider)) {
continue;
}
// Second check: If the provider is synthesized but not offering
// a MissingCapability, then the resource is acting as a
// placeholder as part of the Application-ImportService header
// functionality, and the sharing policy does not need to be
// updated.
// Do not exclude resources providing a MissingCapability
// even though they are synthesized. These are added by the
// resolve context to ensure that unsatisfied optional
// requirements become part of the sharing policy.
if (!(wire.getCapability() instanceof DependencyCalculator.MissingCapability)
&& Constants.ResourceTypeSynthesized.equals(ResourceHelper.getTypeAttribute(provider))) {
continue;
}
// The requirement must be added to the sharing policy.
Requirement requirement = wire.getRequirement();
List<String> namespaces = new ArrayList<String>(2);
namespaces.add(requirement.getNamespace());
if (ServiceNamespace.SERVICE_NAMESPACE.equals(namespaces.get(0))) {
// Both service capabilities and services must be visible.
namespaces.add(RegionFilter.VISIBLE_SERVICE_NAMESPACE);
}
String filter = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE);
if (filter == null) {
for (String namespace : namespaces)
builder.allowAll(namespace);
}
else {
for (String namespace : namespaces)
builder.allow(namespace, filter);
}
}
}
// Always add access to osgi.ee and osgi.native namespaces
setImplicitAccessToNativeAndEECapabilities(builder);
// Now set the sharing policy, if the regions are different.
RegionFilter regionFilter = builder.build();
from.connectRegion(to, regionFilter);
}
private void setImportIsolationPolicy() throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
if (isRoot() || !isScoped())
return;
Region region = getRegion();
Region from = region;
RegionFilterBuilder builder = from.getRegionDigraph().createRegionFilterBuilder();
Region to = getParents().iterator().next().getRegion();
addSubsystemServiceImportToSharingPolicy(builder, to);
// TODO Is this check really necessary? Looks like it was done at the beginning of this method.
if (isScoped()) {
// Both applications and composites have Import-Package headers that require processing.
// In the case of applications, the header is generated.
Header<?> header = getSubsystemManifest().getImportPackageHeader();
setImportIsolationPolicy(builder, (ImportPackageHeader)header);
// Both applications and composites have Require-Capability headers that require processing.
// In the case of applications, the header is generated.
header = getSubsystemManifest().getRequireCapabilityHeader();
setImportIsolationPolicy(builder, (RequireCapabilityHeader)header);
// Both applications and composites have Subsystem-ImportService headers that require processing.
// In the case of applications, the header is generated.
header = getSubsystemManifest().getSubsystemImportServiceHeader();
setImportIsolationPolicy(builder, (SubsystemImportServiceHeader)header);
header = getSubsystemManifest().getRequireBundleHeader();
setImportIsolationPolicy(builder, (RequireBundleHeader)header);
// Always add access to osgi.ee and osgi.native namespaces
setImplicitAccessToNativeAndEECapabilities(builder);
}
RegionFilter regionFilter = builder.build();
from.connectRegion(to, regionFilter);
}
private void setImportIsolationPolicy(RegionFilterBuilder builder, ImportPackageHeader header) throws InvalidSyntaxException {
String policy = RegionFilter.VISIBLE_PACKAGE_NAMESPACE;
if (header == null)
return;
for (ImportPackageHeader.Clause clause : header.getClauses()) {
ImportPackageRequirement requirement = new ImportPackageRequirement(clause, this);
String filter = requirement.getDirectives().get(ImportPackageRequirement.DIRECTIVE_FILTER);
builder.allow(policy, filter);
}
}
private void setImportIsolationPolicy(RegionFilterBuilder builder, RequireBundleHeader header) throws InvalidSyntaxException {
if (header == null)
return;
for (RequireBundleHeader.Clause clause : header.getClauses()) {
RequireBundleRequirement requirement = new RequireBundleRequirement(clause, this);
String policy = RegionFilter.VISIBLE_REQUIRE_NAMESPACE;
String filter = requirement.getDirectives().get(RequireBundleRequirement.DIRECTIVE_FILTER);
builder.allow(policy, filter);
}
}
private void setImportIsolationPolicy(RegionFilterBuilder builder, RequireCapabilityHeader header) throws InvalidSyntaxException {
if (header == null)
return;
for (RequireCapabilityHeader.Clause clause : header.getClauses()) {
RequireCapabilityRequirement requirement = new RequireCapabilityRequirement(clause, this);
String policy = requirement.getNamespace();
String filter = requirement.getDirectives().get(RequireCapabilityRequirement.DIRECTIVE_FILTER);
if (filter == null)
// A null filter directive means the requirement matches any
// capability from the same namespace.
builder.allowAll(policy);
else
// Otherwise, the capabilities must be filtered accordingly.
builder.allow(policy, filter);
}
}
private void setImplicitAccessToNativeAndEECapabilities(RegionFilterBuilder builder) {
builder.allowAll(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE);
builder.allowAll(NativeNamespace.NATIVE_NAMESPACE);
}
private void setImportIsolationPolicy(RegionFilterBuilder builder, SubsystemImportServiceHeader header) throws InvalidSyntaxException {
if (header == null)
return;
for (SubsystemImportServiceHeader.Clause clause : header.getClauses()) {
SubsystemImportServiceRequirement requirement = new SubsystemImportServiceRequirement(clause, this);
String policy = RegionFilter.VISIBLE_SERVICE_NAMESPACE;
String filter = requirement.getDirectives().get(SubsystemImportServiceRequirement.DIRECTIVE_FILTER);
builder.allow(policy, filter);
}
}
}
| 8,649 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SharingPolicyValidator.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.HashSet;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionDigraphVisitor;
import org.eclipse.equinox.region.RegionFilter;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
public class SharingPolicyValidator {
private static class Visitor implements RegionDigraphVisitor {
private final Capability capability;
private final Collection<Region> visited;
public Visitor(Capability capability) {
this.capability = capability;
visited = new HashSet<Region>();
}
public boolean contains(Region region) {
return visited.contains(region);
}
@Override
public void postEdgeTraverse(RegionFilter filter) {
// noop
}
@Override
public boolean preEdgeTraverse(RegionFilter filter) {
if (filter
.isAllowed(
// The osgi.service namespace must be translated into the
// org.eclipse.equinox.allow.service namespace in order to validate
// service sharing policies.
ServiceNamespace.SERVICE_NAMESPACE
.equals(capability.getNamespace()) ? RegionFilter.VISIBLE_SERVICE_NAMESPACE
: capability.getNamespace(), capability
.getAttributes()))
return true;
if (capability instanceof BundleCapability)
return filter.isAllowed(((BundleCapability) capability).getRevision());
return false;
}
@Override
public boolean visit(Region region) {
visited.add(region);
return true;
}
}
private final Region from;
private final Region to;
public SharingPolicyValidator(Region from, Region to) {
this.from = from;
this.to = to;
}
public boolean isValid(Capability capability) {
Visitor visitor = new Visitor(capability);
to.visitSubgraph(visitor);
return visitor.contains(from);
}
}
| 8,650 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/RawSubsystemResource.java | /*
* 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.subsystem.core.internal;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
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.Map.Entry;
import java.util.Properties;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.aries.subsystem.ContentHandler;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.core.archive.Attribute;
import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.apache.aries.subsystem.core.archive.GenericHeader;
import org.apache.aries.subsystem.core.archive.Header;
import org.apache.aries.subsystem.core.archive.ImportPackageHeader;
import org.apache.aries.subsystem.core.archive.RequireBundleHeader;
import org.apache.aries.subsystem.core.archive.RequireCapabilityHeader;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader.Clause;
import org.apache.aries.subsystem.core.archive.SubsystemImportServiceHeader;
import org.apache.aries.subsystem.core.archive.SubsystemLocalizationHeader;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.apache.aries.subsystem.core.archive.SubsystemSymbolicNameHeader;
import org.apache.aries.subsystem.core.archive.SubsystemTypeHeader;
import org.apache.aries.subsystem.core.archive.SubsystemVersionHeader;
import org.apache.aries.subsystem.core.capabilityset.SimpleFilter;
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.util.manifest.ManifestProcessor;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.BundleNamespace;
import org.osgi.framework.namespace.ExecutionEnvironmentNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.resolver.ResolutionException;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RawSubsystemResource implements Resource {
private static final Logger logger = LoggerFactory.getLogger(RawSubsystemResource.class);
private static final Pattern PATTERN = Pattern.compile("([^@/\\\\]+)(?:@(.+))?.esa");
private static final String APPLICATION_IMPORT_SERVICE_HEADER = "Application-ImportService";
private static SubsystemManifest computeExistingSubsystemManifest(IDirectory directory) throws IOException {
Manifest manifest = ManifestProcessor.obtainManifestFromAppDir(directory, "OSGI-INF/SUBSYSTEM.MF");
if (manifest == null)
return null;
return new SubsystemManifest(manifest);
}
private static SubsystemManifest computeNewSubsystemManifest() {
return new SubsystemManifest.Builder().build();
}
private static SubsystemManifest computeSubsystemManifest(IDirectory directory) throws IOException {
SubsystemManifest result = computeExistingSubsystemManifest(directory);
if (result == null)
result = computeNewSubsystemManifest();
return result;
}
private static String convertFileToLocation(IFile file) throws MalformedURLException {
String result = convertFileNameToLocation(file.getName());
if (result == null)
result = file.toURL().toString();
return result;
}
private static String convertFileNameToLocation(String fileName) {
Matcher matcher = PATTERN.matcher(fileName);
if (!matcher.matches())
return null;
String version = matcher.group(2);
return new SubsystemUri(matcher.group(1), version == null ? null
: Version.parseVersion(version), null).toString();
}
private final List<Capability> capabilities;
private final DeploymentManifest deploymentManifest;
private final long id;
private final org.apache.aries.subsystem.core.repository.Repository localRepository;
private final Location location;
private final BasicSubsystem parentSubsystem;
private final List<Requirement> requirements;
private final Collection<Resource> resources;
private final Resource fakeImportServiceResource;
private final SubsystemManifest subsystemManifest;
private final Collection<TranslationFile> translations;
public RawSubsystemResource(String location, IDirectory content, BasicSubsystem parent) throws URISyntaxException, IOException, ResolutionException {
id = SubsystemIdentifier.getNextId();
this.location = new Location(location);
this.parentSubsystem = parent;
if (content == null)
content = this.location.open();
try {
SubsystemManifest manifest = computeSubsystemManifest(content);
resources = computeResources(content, manifest);
fakeImportServiceResource = createFakeResource(manifest);
localRepository = computeLocalRepository();
manifest = computeSubsystemManifestBeforeRequirements(content, manifest);
requirements = computeRequirements(manifest);
subsystemManifest = computeSubsystemManifestAfterRequirements(manifest);
capabilities = computeCapabilities();
deploymentManifest = computeDeploymentManifest(content);
translations = computeTranslations(content);
}
finally {
IOUtils.close(content.toCloseable());
}
}
public RawSubsystemResource(File file, BasicSubsystem parent) throws IOException, URISyntaxException, ResolutionException {
this(FileSystem.getFSRoot(file), parent);
}
public RawSubsystemResource(IDirectory idir, BasicSubsystem parent) throws IOException, URISyntaxException, ResolutionException {
subsystemManifest = initializeSubsystemManifest(idir);
requirements = subsystemManifest.toRequirements(this);
capabilities = subsystemManifest.toCapabilities(this);
deploymentManifest = initializeDeploymentManifest(idir);
id = Long.parseLong(deploymentManifest.getHeaders().get(DeploymentManifest.ARIESSUBSYSTEM_ID).getValue());
location = new Location(deploymentManifest.getHeaders().get(DeploymentManifest.ARIESSUBSYSTEM_LOCATION).getValue());
parentSubsystem = parent;
translations = Collections.emptyList();
Map<String, Header<?>> headers = deploymentManifest.getHeaders();
if (State.INSTALLING.equals(
State.valueOf(
headers.get(
DeploymentManifest.ARIESSUBSYSTEM_STATE).getValue()))
&& subsystemManifest.getSubsystemTypeHeader().getAriesProvisionDependenciesDirective().isResolve()) {
URL url = new URL(headers.get(Constants.AriesSubsystemOriginalContent).getValue());
Collection<Resource> resources;
try {
resources = computeResources(FileSystem.getFSRoot(new File(url.toURI())), subsystemManifest);
}
catch (IllegalArgumentException e) {
// Thrown by File if the URI is not hierarchical. For example,
// when handling a JAR URL.
resources = computeResources(FileSystem.getFSRoot(url.openStream()), subsystemManifest);
}
this.resources = resources;
fakeImportServiceResource = createFakeResource(subsystemManifest);
}
else {
resources = Collections.emptyList();
fakeImportServiceResource = null;
}
localRepository = computeLocalRepository();
}
private static Resource createFakeResource(SubsystemManifest manifest) {
Header<?> importServiceHeader = manifest.getHeaders().get(APPLICATION_IMPORT_SERVICE_HEADER);
if (importServiceHeader == null) {
return null;
}
List<Capability> modifiableCaps = new ArrayList<Capability>();
final List<Capability> fakeCapabilities = Collections.unmodifiableList(modifiableCaps);
Resource fakeResource = new Resource() {
@Override
public List<Capability> getCapabilities(String namespace) {
if (namespace == null) {
return fakeCapabilities;
}
List<Capability> results = new ArrayList<Capability>();
for (Capability capability : fakeCapabilities) {
if (namespace.equals(capability.getNamespace())) {
results.add(capability);
}
}
return results;
}
@Override
public List<Requirement> getRequirements(String namespace) {
return Collections.emptyList();
}
};
modifiableCaps.add(new OsgiIdentityCapability(fakeResource, Constants.ResourceTypeSynthesized, new Version(1,0,0), Constants.ResourceTypeSynthesized));
Map<String, Map<String, String>> serviceImports = ManifestHeaderProcessor.parseImportString(importServiceHeader.getValue());
for (Entry<String, Map<String, String>> serviceImport : serviceImports.entrySet()) {
Collection<String> objectClasses = new ArrayList<String>(Arrays.asList(serviceImport.getKey()));
String filter = serviceImport.getValue().get(IdentityNamespace.REQUIREMENT_FILTER_DIRECTIVE);
BasicCapability.Builder capBuilder = new BasicCapability.Builder();
capBuilder.namespace(ServiceNamespace.SERVICE_NAMESPACE);
capBuilder.attribute(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE, objectClasses);
if (filter != null)
capBuilder.attributes(new HashMap<String, Object>(SimpleFilter.attributes(filter)));
capBuilder.attribute("service.imported", "");
capBuilder.resource(fakeResource);
modifiableCaps.add(capBuilder.build());
}
return fakeResource;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof RawSubsystemResource))
return false;
RawSubsystemResource that = (RawSubsystemResource)o;
return getLocation().equals(that.getLocation());
}
@Override
public List<Capability> getCapabilities(String namespace) {
if (namespace == null)
return Collections.unmodifiableList(capabilities);
ArrayList<Capability> result = new ArrayList<Capability>(capabilities.size());
for (Capability capability : capabilities)
if (namespace.equals(capability.getNamespace()))
result.add(capability);
result.trimToSize();
return Collections.unmodifiableList(result);
}
public DeploymentManifest getDeploymentManifest() {
return deploymentManifest;
}
public long getId() {
return id;
}
public org.apache.aries.subsystem.core.repository.Repository getLocalRepository() {
return localRepository;
}
public Location getLocation() {
return location;
}
@Override
public List<Requirement> getRequirements(String namespace) {
if (namespace == null)
return Collections.unmodifiableList(requirements);
ArrayList<Requirement> result = new ArrayList<Requirement>(requirements.size());
for (Requirement requirement : requirements)
if (namespace.equals(requirement.getNamespace()))
result.add(requirement);
result.trimToSize();
return Collections.unmodifiableList(result);
}
public SubsystemManifest getSubsystemManifest() {
return subsystemManifest;
}
public Collection<TranslationFile> getTranslations() {
return translations;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getLocation().hashCode();
return result;
}
private void addHeader(SubsystemManifest.Builder builder, Header<?> header) {
if (header == null)
return;
builder.header(header);
}
private void addImportPackageHeader(SubsystemManifest.Builder builder) {
addHeader(builder, computeImportPackageHeader());
}
private void addRequireBundleHeader(SubsystemManifest.Builder builder) {
addHeader(builder, computeRequireBundleHeader());
}
private void addRequireCapabilityHeader(SubsystemManifest.Builder builder) {
addHeader(builder, computeRequireCapabilityHeader());
}
private void addSubsystemContentHeader(SubsystemManifest.Builder builder, SubsystemManifest manifest) {
addHeader(builder, computeSubsystemContentHeader(manifest));
}
private void addSubsystemImportServiceHeader(SubsystemManifest.Builder builder) {
addHeader(builder, computeSubsystemImportServiceHeader());
}
private void addSubsystemSymbolicNameHeader(SubsystemManifest.Builder builder, SubsystemManifest manifest) {
addHeader(builder, computeSubsystemSymbolicNameHeader(manifest));
}
private void addSubsystemTypeHeader(SubsystemManifest.Builder builder, SubsystemManifest manifest) {
addHeader(builder, computeSubsystemTypeHeader(manifest));
}
private void addSubsystemVersionHeader(SubsystemManifest.Builder builder, SubsystemManifest manifest) {
addHeader(builder, computeSubsystemVersionHeader(manifest));
}
private List<Capability> computeCapabilities() {
return subsystemManifest.toCapabilities(this);
}
private DeploymentManifest computeDeploymentManifest(IDirectory directory) throws IOException {
return computeExistingDeploymentManifest(directory);
}
private DeploymentManifest computeExistingDeploymentManifest(IDirectory directory) throws IOException {
Manifest manifest = ManifestProcessor.obtainManifestFromAppDir(directory, "OSGI-INF/DEPLOYMENT.MF");
if (manifest == null)
return null;
return new DeploymentManifest(manifest);
}
private ImportPackageHeader computeImportPackageHeader() {
if (requirements.isEmpty())
return null;
ArrayList<ImportPackageHeader.Clause> clauses = new ArrayList<ImportPackageHeader.Clause>(requirements.size());
for (Requirement requirement : requirements) {
if (!PackageNamespace.PACKAGE_NAMESPACE.equals(requirement.getNamespace()))
continue;
clauses.add(ImportPackageHeader.Clause.valueOf(requirement));
}
if (clauses.isEmpty())
return null;
clauses.trimToSize();
return new ImportPackageHeader(clauses);
}
private org.apache.aries.subsystem.core.repository.Repository computeLocalRepository() {
if (fakeImportServiceResource != null) {
Collection<Resource> temp = new ArrayList<Resource>(resources);
temp.add(fakeImportServiceResource);
return new LocalRepository(temp);
}
return new LocalRepository(resources);
}
private RequireBundleHeader computeRequireBundleHeader() {
if (requirements.isEmpty())
return null;
ArrayList<RequireBundleHeader.Clause> clauses = new ArrayList<RequireBundleHeader.Clause>(requirements.size());
for (Requirement requirement : requirements) {
if (!BundleNamespace.BUNDLE_NAMESPACE.equals(requirement.getNamespace()))
continue;
clauses.add(RequireBundleHeader.Clause.valueOf(requirement));
}
if (clauses.isEmpty())
return null;
clauses.trimToSize();
return new RequireBundleHeader(clauses);
}
private RequireCapabilityHeader computeRequireCapabilityHeader() {
if (requirements.isEmpty())
return null;
ArrayList<RequireCapabilityHeader.Clause> clauses = new ArrayList<RequireCapabilityHeader.Clause>();
for (Requirement requirement : requirements) {
String namespace = requirement.getNamespace();
if (namespace.startsWith("osgi.") && !(
// Don't filter out the osgi.ee namespace...
namespace.equals(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE) ||
// ...or the osgi.service namespace.
namespace.equals(ServiceNamespace.SERVICE_NAMESPACE)))
continue;
clauses.add(RequireCapabilityHeader.Clause.valueOf(requirement));
}
if (clauses.isEmpty())
return null;
clauses.trimToSize();
return new RequireCapabilityHeader(clauses);
}
private List<Requirement> computeRequirements(SubsystemManifest manifest) throws ResolutionException {
if (isComposite(manifest)) {
// Composites determine their own requirements.
return manifest.toRequirements(this);
}
// Gather up all of the content resources for the subsystem.
SubsystemContentHeader header = manifest.getSubsystemContentHeader();
if (header == null) {
// Empty subsystems (i.e. subsystems with no content) are allowed.
return Collections.emptyList();
}
List<Requirement> requirements = header.toRequirements(this);
List<Resource> resources = new ArrayList<Resource>(requirements.size());
// TODO Do we need the system repository in here (e.g., for features)?
// What about the preferred provider repository?
// Search the local repository and service repositories for content.
RepositoryServiceRepository serviceRepo = new RepositoryServiceRepository();
// TODO Should we search the service repositories first, the assumption
// being they will contain more current content than the subsystem
// archive?
CompositeRepository compositeRepo = new CompositeRepository(localRepository, serviceRepo);
for (Requirement requirement : requirements) {
Collection<Capability> capabilities = compositeRepo.findProviders(requirement);
if (!capabilities.isEmpty()) {
resources.add(capabilities.iterator().next().getResource());
}
}
if (fakeImportServiceResource != null) {
// Add the fake resource so the dependency calculator knows not to
// return service requirements that are included in
// Application-ImportService.
resources.add(fakeImportServiceResource);
}
// Now compute the dependencies of the content resources. These are
// dependencies not satisfied by the content resources themselves.
return new DependencyCalculator(resources).calculateDependencies();
}
private Collection<Resource> computeResources(IDirectory directory, SubsystemManifest manifest) throws IOException, URISyntaxException, ResolutionException {
List<IFile> files = directory.listFiles();
if (files.isEmpty())
return Collections.emptyList();
ArrayList<Resource> result = new ArrayList<Resource>(files.size());
for (IFile file : directory.listFiles()) {
if (file.isFile()) {
addResource(file, file.convertNested(), manifest, result);
} else if (!file.getName().endsWith("OSGI-INF")) {
addResource(file, file.convert(), manifest, result);
}
}
result.trimToSize();
return result;
}
private void addResource(IFile file, IDirectory content, SubsystemManifest manifest, ArrayList<Resource> result) throws URISyntaxException,
IOException, ResolutionException, MalformedURLException {
String name = file.getName();
if (name.endsWith(".esa")) {
result.add(new RawSubsystemResource(convertFileToLocation(file), content, parentSubsystem));
} else if (name.endsWith(".jar")) {
try {
result.add(new BundleResource(file));
} catch (IllegalArgumentException e) {
// Ignore if the resource is an invalid bundle or not a bundle at all.
if (logger.isDebugEnabled()) {
logger.debug("File \"" + file.getName() + "\" in subsystem with location \"" + location + "\" will be ignored because it is not recognized as a supported resource.", e);
}
}
} else {
// This is a different type of file. Add a file resource for it if there is a custom content handler for it.
FileResource fr = new FileResource(file);
fr.setCapabilities(computeFileCapabilities(fr, file, manifest));
List<Capability> idcaps = fr.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE);
if (idcaps.size() > 0) {
Capability idcap = idcaps.get(0);
Object type = idcap.getAttributes().get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE);
if (type instanceof String && parentSubsystem != null) {
if (CustomResources.getCustomContentHandler(parentSubsystem, (String) type) != null) {
// Yes, there is a custom content handler, add it.
result.add(fr);
return;
}
}
}
// There is no custom handler for this resource, let's check if it turns out to be a bundle
try {
result.add(new BundleResource(file));
} catch (Exception e) {
// Ignore if the resource is an invalid bundle or not a bundle at all.
if (logger.isDebugEnabled()) {
logger.debug("File \"" + file.getName() + "\" in subsystem with location \"" + location + "\" will be ignored because it is not recognized as a supported resource.", e);
}
}
}
}
private List<Capability> computeFileCapabilities(FileResource resource, IFile file, SubsystemManifest manifest) {
SubsystemContentHeader ssch = manifest.getSubsystemContentHeader();
if (ssch == null)
return Collections.emptyList();
for (Clause c : ssch.getClauses()) {
Attribute er = c.getAttribute(ContentHandler.EMBEDDED_RESOURCE_ATTRIBUTE);
if (er != null) {
if (file.getName().equals(er.getValue())) {
Map<String, Object> attrs = new HashMap<String, Object>();
attrs.put(ContentHandler.EMBEDDED_RESOURCE_ATTRIBUTE, er.getValue());
return Collections.<Capability> singletonList(
new OsgiIdentityCapability(resource, c.getSymbolicName(), c.getVersionRange().getLeft(), c.getType(), attrs));
}
}
}
return Collections.emptyList();
}
private SubsystemContentHeader computeSubsystemContentHeader(SubsystemManifest manifest) {
SubsystemContentHeader header = manifest.getSubsystemContentHeader();
if (header == null && !resources.isEmpty())
header = SubsystemContentHeader.newInstance(resources);
return header;
}
private SubsystemImportServiceHeader computeSubsystemImportServiceHeader() {
if (requirements.isEmpty())
return null;
ArrayList<SubsystemImportServiceHeader.Clause> clauses = new ArrayList<SubsystemImportServiceHeader.Clause>(requirements.size());
for (Requirement requirement : requirements) {
if (!ServiceNamespace.SERVICE_NAMESPACE.equals(requirement.getNamespace()))
continue;
clauses.add(SubsystemImportServiceHeader.Clause.valueOf(requirement));
}
if (clauses.isEmpty())
return null;
clauses.trimToSize();
return new SubsystemImportServiceHeader(clauses);
}
private SubsystemManifest computeSubsystemManifestAfterRequirements(SubsystemManifest manifest) {
if (isComposite(manifest))
return manifest;
SubsystemManifest.Builder builder = new SubsystemManifest.Builder().manifest(manifest);
addImportPackageHeader(builder);
addRequireBundleHeader(builder);
addRequireCapabilityHeader(builder);
addSubsystemImportServiceHeader(builder);
return builder.build();
}
private SubsystemManifest computeSubsystemManifestBeforeRequirements(IDirectory content, SubsystemManifest manifest) throws MalformedURLException {
SubsystemManifest.Builder builder = new SubsystemManifest.Builder().manifest(manifest);
addSubsystemSymbolicNameHeader(builder, manifest);
addSubsystemVersionHeader(builder, manifest);
addSubsystemTypeHeader(builder, manifest);
addSubsystemContentHeader(builder, manifest);
builder.header(new GenericHeader(Constants.AriesSubsystemOriginalContent, String.valueOf(content.toURL())));
return builder.build();
}
private SubsystemSymbolicNameHeader computeSubsystemSymbolicNameHeader(SubsystemManifest manifest) {
SubsystemSymbolicNameHeader header = manifest.getSubsystemSymbolicNameHeader();
if (header != null)
return header;
String symbolicName = location.getSymbolicName();
if (symbolicName == null)
symbolicName = "org.apache.aries.subsystem." + id;
return new SubsystemSymbolicNameHeader(symbolicName);
}
private SubsystemTypeHeader computeSubsystemTypeHeader(SubsystemManifest manifest) {
SubsystemTypeHeader header = manifest.getSubsystemTypeHeader();
AriesProvisionDependenciesDirective directive = header.getAriesProvisionDependenciesDirective();
if (directive != null) {
// Nothing to do because the directive was specified in the original
// manifest. Validation of the value occurs later.
return header;
}
// The directive was not specified in the original manifest. The value
// of the parent directive becomes the default.
SubsystemManifest parentManifest = ((BasicSubsystem)parentSubsystem).getSubsystemManifest();
SubsystemTypeHeader parentHeader = parentManifest.getSubsystemTypeHeader();
directive = parentHeader.getAriesProvisionDependenciesDirective();
header = new SubsystemTypeHeader(header.getValue() + ';' + directive);
return header;
}
private SubsystemVersionHeader computeSubsystemVersionHeader(SubsystemManifest manifest) {
SubsystemVersionHeader header = manifest.getSubsystemVersionHeader();
if (header.getVersion().equals(Version.emptyVersion) && location.getVersion() != null)
header = new SubsystemVersionHeader(location.getVersion());
return header;
}
private Collection<TranslationFile> computeTranslations(IDirectory directory) throws IOException {
SubsystemManifest manifest = getSubsystemManifest();
SubsystemLocalizationHeader header = manifest.getSubsystemLocalizationHeader();
String directoryName = header.getDirectoryName();
// TODO Assumes the ZIP file includes directory entries. Issues?
IFile file = directoryName == null ? directory : directory.getFile(directoryName);
if (file == null || !file.isDirectory())
return Collections.emptyList();
List<IFile> files = file.convert().listFiles();
if (files == null || files.isEmpty())
return Collections.emptyList();
ArrayList<TranslationFile> result = new ArrayList<TranslationFile>(files.size());
for (IFile f : files) {
Properties properties = new Properties();
InputStream is = f.open();
try {
properties.load(is);
result.add(new TranslationFile(f.getName(), properties));
}
finally {
is.close();
}
}
result.trimToSize();
return result;
}
private DeploymentManifest initializeDeploymentManifest(IDirectory idir)
throws IOException {
Manifest manifest = ManifestProcessor.obtainManifestFromAppDir(idir,
"OSGI-INF/DEPLOYMENT.MF");
if (manifest != null)
return new DeploymentManifest(manifest);
else
return new DeploymentManifest.Builder()
.manifest(getSubsystemManifest())
.location(BasicSubsystem.ROOT_LOCATION).autostart(true).id(0)
.lastId(SubsystemIdentifier.getLastId())
.state(State.INSTALLING)
.build();
}
private SubsystemManifest initializeSubsystemManifest(IDirectory idir)
throws IOException {
Manifest manifest = ManifestProcessor.obtainManifestFromAppDir(idir,
"OSGI-INF/SUBSYSTEM.MF");
if (manifest != null)
return new SubsystemManifest(manifest);
else
return new SubsystemManifest.Builder()
.symbolicName(BasicSubsystem.ROOT_SYMBOLIC_NAME)
.version(BasicSubsystem.ROOT_VERSION)
.type(SubsystemTypeHeader.TYPE_APPLICATION
+ ';'
+ SubsystemTypeHeader.DIRECTIVE_PROVISION_POLICY
+ ":="
+ SubsystemTypeHeader.PROVISION_POLICY_ACCEPT_DEPENDENCIES
+ ';'
+ AriesProvisionDependenciesDirective.INSTALL.toString())
.build();
}
private boolean isComposite(SubsystemManifest manifest) {
return SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(manifest.getSubsystemTypeHeader().getType());
}
Collection<Resource> getResources() {
return resources;
}
}
| 8,651 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/OsgiIdentityCapability.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.subsystem.core.internal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.BundleManifest;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.apache.aries.subsystem.core.archive.SymbolicNameHeader;
import org.apache.aries.subsystem.core.archive.VersionHeader;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
public class OsgiIdentityCapability extends AbstractCapability {
private final Map<String, Object> attributes;
private final Resource resource;
public OsgiIdentityCapability(Resource resource, String symbolicName) {
this(resource, symbolicName, Version.emptyVersion);
}
public OsgiIdentityCapability(Resource resource, String symbolicName, Version version) {
this(resource, symbolicName, version, IdentityNamespace.TYPE_BUNDLE);
}
public OsgiIdentityCapability(Resource resource, String symbolicName, Version version, String identityType) {
this(resource, symbolicName, version, identityType, new HashMap<String, Object>());
}
public OsgiIdentityCapability(Resource resource, String symbolicName, Version version, String identityType, Map<String, Object> attrs) {
this.resource = resource;
attributes = attrs;
attributes.put(
IdentityNamespace.IDENTITY_NAMESPACE,
symbolicName);
attributes.put(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
version);
attributes.put(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
identityType);
// TODO Add directives, particularly "effective" and "singleton".
}
public OsgiIdentityCapability(Resource resource, SubsystemManifest manifest) {
this(
resource,
manifest.getSubsystemSymbolicNameHeader().getSymbolicName(),
manifest.getSubsystemVersionHeader().getVersion(),
manifest.getSubsystemTypeHeader().getType());
}
public OsgiIdentityCapability(Resource resource, BundleManifest manifest) {
this(
resource,
((SymbolicNameHeader)manifest.getHeader(Constants.BUNDLE_SYMBOLICNAME)).getSymbolicName(),
((VersionHeader)manifest.getHeader(Constants.BUNDLE_VERSION)).getVersion(),
manifest.getHeader(Constants.FRAGMENT_HOST) == null ? IdentityNamespace.TYPE_BUNDLE : IdentityNamespace.TYPE_FRAGMENT);
}
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
public Map<String, String> getDirectives() {
return Collections.emptyMap();
}
public String getNamespace() {
return IdentityNamespace.IDENTITY_NAMESPACE;
}
public Resource getResource() {
return resource;
}
}
| 8,652 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/OsgiContentCapability.java | /*
* 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.subsystem.core.internal;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.osgi.resource.Resource;
public class OsgiContentCapability extends AbstractCapability {
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Resource resource;
public OsgiContentCapability(Resource resource, String url) {
// TOOD Add to constants.
attributes.put("osgi.content", url);
// TODO Any directives?
this.resource = resource;
}
public OsgiContentCapability(Resource resource, URL url) {
this(resource, url.toExternalForm());
}
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
public Map<String, String> getDirectives() {
return Collections.emptyMap();
}
public String getNamespace() {
// TODO Add to constants.
return "osgi.content";
}
public Resource getResource() {
return resource;
}
}
| 8,653 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BasicSubsystem.java | /*
* 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.subsystem.core.internal;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.aries.subsystem.AriesSubsystem;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.core.archive.AriesSubsystemParentsHeader;
import org.apache.aries.subsystem.core.archive.DeployedContentHeader;
import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.apache.aries.subsystem.core.archive.Header;
import org.apache.aries.subsystem.core.archive.ProvisionResourceHeader;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.apache.aries.subsystem.core.archive.SubsystemTypeHeader;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.aries.util.filesystem.ICloseableDirectory;
import org.apache.aries.util.filesystem.IDirectory;
import org.apache.aries.util.io.IOUtils;
import org.eclipse.equinox.region.Region;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.HostNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.coordinator.Participant;
import org.osgi.service.resolver.ResolutionException;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BasicSubsystem implements Resource, AriesSubsystem {
private static final Logger logger = LoggerFactory.getLogger(BasicSubsystem.class);
public static final String ROOT_SYMBOLIC_NAME = "org.osgi.service.subsystem.root";
public static final Version ROOT_VERSION = Version.parseVersion("1.0.0");
public static final String ROOT_LOCATION = "subsystem://?"
+ SubsystemConstants.SUBSYSTEM_SYMBOLICNAME + '='
+ ROOT_SYMBOLIC_NAME + '&' + SubsystemConstants.SUBSYSTEM_VERSION
+ '=' + ROOT_VERSION;
private volatile Bundle regionContextBundle;
private DeploymentManifest deploymentManifest;
private SubsystemResource resource;
private SubsystemManifest subsystemManifest;
private final IDirectory directory;
public BasicSubsystem(SubsystemResource resource) throws URISyntaxException, IOException, BundleException, InvalidSyntaxException {
this(resource, null);
}
public BasicSubsystem(SubsystemResource resource, InputStream deploymentManifest) throws URISyntaxException, IOException, BundleException, InvalidSyntaxException {
this.resource = resource;
final File file = new File(Activator.getInstance().getBundleContext().getDataFile(""), Long.toString(resource.getId()));
file.mkdirs();
Coordination coordination = Activator.getInstance().getCoordinator().peek();
if (coordination != null) {
coordination.addParticipant(new Participant() {
@Override
public void ended(Coordination c) throws Exception {
// Nothing
}
@Override
public void failed(Coordination c) throws Exception {
IOUtils.deleteRecursive(file);
}
});
}
directory = FileSystem.getFSRoot(file);
setSubsystemManifest(resource.getSubsystemManifest());
SubsystemManifestValidator.validate(this, getSubsystemManifest());
setDeploymentManifest(new DeploymentManifest.Builder()
.manifest(resource.getSubsystemManifest())
.manifest(deploymentManifest == null ? resource.getDeploymentManifest() : new DeploymentManifest(deploymentManifest))
.location(resource.getLocation())
.autostart(false)
.id(resource.getId())
.lastId(SubsystemIdentifier.getLastId())
.region(resource.getRegion().getName())
.state(State.INSTALLING)
.build());
setTranslations();
}
public BasicSubsystem(File file) throws IOException, URISyntaxException, ResolutionException {
this(FileSystem.getFSRoot(file));
}
public BasicSubsystem(IDirectory directory) throws IOException,
URISyntaxException, ResolutionException {
this.directory = directory;
State state = State
.valueOf(getDeploymentManifestHeaderValue(DeploymentManifest.ARIESSUBSYSTEM_STATE));
if (EnumSet.of(State.STARTING, State.ACTIVE, State.STOPPING).contains(
state)) {
state = State.RESOLVED;
}
else if (State.RESOLVING.equals(state)) {
state = State.INSTALLED;
}
setDeploymentManifest(new DeploymentManifest.Builder()
.manifest(getDeploymentManifest()).state(state).build());
}
/* BEGIN Resource interface methods. */
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof BasicSubsystem))
return false;
BasicSubsystem that = (BasicSubsystem)o;
return getLocation().equals(that.getLocation());
}
@Override
public List<Capability> getCapabilities(String namespace) {
// First, add the capabilities from the manifest.
SubsystemManifest manifest = getSubsystemManifest();
List<Capability> result = manifest.toCapabilities(this);
if (namespace != null)
for (Iterator<Capability> i = result.iterator(); i.hasNext();)
if (!i.next().getNamespace().equals(namespace))
i.remove();
// TODO Somehow, exposing the capabilities of content resources of a
// feature is causing an infinite regression of feature2 installations
// in FeatureTest.testSharedContent() under certain conditions.
if (isScoped() || IdentityNamespace.IDENTITY_NAMESPACE.equals(namespace))
return result;
SubsystemContentHeader header = manifest.getSubsystemContentHeader();
for (Resource constituent : getConstituents()) {
if (header.contains(constituent)) {
for (Capability capability : constituent.getCapabilities(namespace)) {
if (namespace == null && (IdentityNamespace.IDENTITY_NAMESPACE.equals(capability.getNamespace()) || HostNamespace.HOST_NAMESPACE.equals(capability.getNamespace()))) {
// Don't want to include the osgi.identity and/or osgi.wiring.host capabilities of
// content. Need a second check here in case the namespace
// is null.
continue;
}
result.add(new BasicCapability(capability, this));
}
}
}
return result;
}
@Override
public List<Requirement> getRequirements(String namespace) {
// First, add the requirements from the manifest.
SubsystemManifest manifest = getSubsystemManifest();
List<Requirement> result = manifest.toRequirements(this);
if (namespace != null)
for (Iterator<Requirement> i = result.iterator(); i.hasNext();)
if (!i.next().getNamespace().equals(namespace))
i.remove();
if (isScoped())
return result;
SubsystemContentHeader header = manifest.getSubsystemContentHeader();
for (Resource constituent : getConstituents())
if (header.contains(constituent))
for (Requirement requirement : constituent.getRequirements(namespace))
result.add(new BasicRequirement(requirement, this));
return result;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getLocation().hashCode();
return result;
}
/* END Resource interface methods. */
/* BEGIN Subsystem interface methods. */
@Override
public BundleContext getBundleContext() {
SecurityManager.checkContextPermission(this);
return AccessController.doPrivileged(new GetBundleContextAction(this));
}
@Override
public Collection<Subsystem> getChildren() {
return Activator.getInstance().getSubsystems().getChildren(this);
}
@Override
public Map<String, String> getSubsystemHeaders(Locale locale) {
SecurityManager.checkMetadataPermission(this);
return AccessController.doPrivileged(new GetSubsystemHeadersAction(this, locale));
}
@Override
public String getLocation() {
SecurityManager.checkMetadataPermission(this);
return getDeploymentManifestHeaderValue(DeploymentManifest.ARIESSUBSYSTEM_LOCATION);
}
@Override
public Collection<Subsystem> getParents() {
AriesSubsystemParentsHeader header = getDeploymentManifest().getAriesSubsystemParentsHeader();
if (header == null)
return Collections.emptyList();
Collection<Subsystem> result = new ArrayList<Subsystem>(header.getClauses().size());
for (AriesSubsystemParentsHeader.Clause clause : header.getClauses()) {
BasicSubsystem subsystem = Activator.getInstance().getSubsystems().getSubsystemById(clause.getId());
if (subsystem == null)
continue;
result.add(subsystem);
}
return result;
}
@Override
public Collection<Resource> getConstituents() {
return Activator.getInstance().getSubsystems().getConstituents(this);
}
@Override
public State getState() {
return State.valueOf(getDeploymentManifestHeaderValue(DeploymentManifest.ARIESSUBSYSTEM_STATE));
}
@Override
public long getSubsystemId() {
return Long.parseLong(getDeploymentManifestHeaderValue(DeploymentManifest.ARIESSUBSYSTEM_ID));
}
@Override
public String getSymbolicName() {
return getSubsystemManifest().getSubsystemSymbolicNameHeader().getSymbolicName();
}
@Override
public String getType() {
return getSubsystemManifest().getSubsystemTypeHeader().getType();
}
@Override
public Version getVersion() {
return getSubsystemManifest().getSubsystemVersionHeader().getVersion();
}
/** Get "aries-provision-dependencies" directive.
*
* @return requested directive or null if the directive is not specified in the header
*/
public AriesProvisionDependenciesDirective getAriesProvisionDependenciesDirective() {
return getSubsystemManifest().getSubsystemTypeHeader().getAriesProvisionDependenciesDirective();
}
@Override
public AriesSubsystem install(String location) {
return install(location, (InputStream)null);
}
@Override
public AriesSubsystem install(String location, InputStream content) {
return install(location, content, null);
}
@Override
public void start() {
SecurityManager.checkExecutePermission(this);
// Changing the autostart setting must be privileged because of file IO.
// It cannot be done within StartAction because we only want to change
// it on an explicit start operation but StartAction is also used for
// implicit operations.
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
setAutostart(true);
return null;
}
});
AccessController.doPrivileged(new StartAction(this, this, this));
}
@Override
public void stop() {
SecurityManager.checkExecutePermission(this);
// Changing the autostart setting must be privileged because of file IO.
// It cannot be done within StopAction because we only want to change it
// on an explicit stop operation but StopAction is also used for
// implicit operations.
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
setAutostart(false);
return null;
}
});
AccessController.doPrivileged(new StopAction(this, this, !isRoot()));
}
@Override
public void uninstall() {
SecurityManager.checkLifecyclePermission(this);
AccessController.doPrivileged(new UninstallAction(this, this, false));
}
/* END Subsystem interface methods. */
void addedConstituent(Resource resource, boolean referenced) {
try {
if (logger.isDebugEnabled())
logger.debug("Adding constituent {} to deployment manifest...", resource);
synchronized (this) {
setDeploymentManifest(new DeploymentManifest.Builder()
.manifest(getDeploymentManifest()).content(resource, referenced).build());
}
if (logger.isDebugEnabled())
logger.debug("Added constituent {} to deployment manifest", resource);
} catch (Exception e) {
throw new SubsystemException(e);
}
}
void addedParent(BasicSubsystem subsystem, boolean referenceCount) {
try {
if (logger.isDebugEnabled())
logger.debug("Adding parent {} to deployment manifest...", subsystem.getSymbolicName());
synchronized (this) {
setDeploymentManifest(new DeploymentManifest.Builder()
.manifest(getDeploymentManifest()).parent(subsystem, referenceCount).build());
}
if (logger.isDebugEnabled())
logger.debug("Added parent {} to deployment manifest", subsystem.getSymbolicName());
} catch (Exception e) {
throw new SubsystemException(e);
}
}
synchronized DeploymentManifest getDeploymentManifest() {
if (deploymentManifest == null) {
try {
deploymentManifest = new DeploymentManifest(directory.getFile("OSGI-INF/DEPLOYMENT.MF").open());
}
catch (Throwable t) {
throw new SubsystemException(t);
}
}
return deploymentManifest;
}
File getDirectory() {
try {
return new File(directory.toURL().toURI());
}
catch (Exception e) {
throw new SubsystemException(e);
}
}
Region getRegion() {
Bundle bundle = regionContextBundle; // volatile variable
if (bundle == null) {
// At best, RegionDigraph.getRegion(String) is linear time.
// Continue to call this when necessary, however, as a fail safe.
return Activator.getInstance().getRegionDigraph().getRegion(getRegionName());
}
// RegionDigraph.getRegion(Bundle) is constant time.
return Activator.getInstance().getRegionDigraph().getRegion(bundle);
}
String getRegionName() {
DeploymentManifest manifest = getDeploymentManifest();
Header<?> header = manifest.getHeaders().get(DeploymentManifest.ARIESSUBSYSTEM_REGION);
if (header == null)
return null;
return header.getValue();
}
synchronized SubsystemResource getResource() {
if (resource == null) {
try {
resource = new SubsystemResource(null, directory);
}
catch (Exception e) {
throw new SubsystemException(e);
}
Collection<DeployedContentHeader.Clause> missingResources = resource.getMissingResources();
if (!missingResources.isEmpty()) {
if (isRoot())
// We don't care if the root subsystem has missing resources
// because they are either (1) extraneous bundles outside of
// the subsystems API or (2) provisioned dependencies of
// other subsystems. Those that fall in the latter category
// will be detected by the dependent subsystems.
removedContent(missingResources);
else
// If a non-root subsystem has missing dependencies, let's
// fail fast for now.
throw new SubsystemException("Missing resources: " + missingResources);
}
}
return resource;
}
synchronized SubsystemManifest getSubsystemManifest() {
if (subsystemManifest == null) {
try {
subsystemManifest = new SubsystemManifest(directory.getFile("OSGI-INF/SUBSYSTEM.MF").open());
}
catch (Throwable t) {
throw new SubsystemException(t);
}
}
return subsystemManifest;
}
boolean isApplication() {
return getSubsystemManifest().getSubsystemTypeHeader().isApplication();
}
boolean isAutostart() {
DeploymentManifest manifest = getDeploymentManifest();
Header<?> header = manifest.getHeaders().get(DeploymentManifest.ARIESSUBSYSTEM_AUTOSTART);
return Boolean.valueOf(header.getValue());
}
boolean isComposite() {
return getSubsystemManifest().getSubsystemTypeHeader().isComposite();
}
boolean isFeature() {
return getSubsystemManifest().getSubsystemTypeHeader().isFeature();
}
boolean isReadyToStart() {
if (isRoot())
return true;
for (Subsystem parent : getParents())
if (EnumSet.of(State.STARTING, State.ACTIVE).contains(parent.getState()) && isAutostart())
return true;
return false;
}
boolean isReferenced(Resource resource) {
// Everything is referenced for the root subsystem during initialization.
if (isRoot() && EnumSet.of(State.INSTALLING, State.INSTALLED).contains(getState()))
return true;
DeployedContentHeader header = getDeploymentManifest().getDeployedContentHeader();
if (header == null)
return false;
return header.isReferenced(resource);
}
boolean isRoot() {
return ROOT_LOCATION.equals(getLocation());
}
boolean isScoped() {
return isApplication() || isComposite();
}
void removedContent(Resource resource) {
DeploymentManifest manifest = getDeploymentManifest();
DeployedContentHeader header = manifest.getDeployedContentHeader();
if (header == null)
return;
DeployedContentHeader.Clause clause = header.getClause(resource);
if (clause == null)
return;
removedContent(Collections.singleton(clause));
}
synchronized void removedContent(Collection<DeployedContentHeader.Clause> content) {
DeploymentManifest manifest = getDeploymentManifest();
DeployedContentHeader header = manifest.getDeployedContentHeader();
if (header == null)
return;
Collection<DeployedContentHeader.Clause> clauses = new ArrayList<DeployedContentHeader.Clause>(header.getClauses());
for (Iterator<DeployedContentHeader.Clause> i = clauses.iterator(); i.hasNext();)
if (content.contains(i.next())) {
i.remove();
break;
}
DeploymentManifest.Builder builder = new DeploymentManifest.Builder();
for (Entry<String, Header<?>> entry : manifest.getHeaders().entrySet()) {
if (DeployedContentHeader.NAME.equals(entry.getKey()))
continue;
builder.header(entry.getValue());
}
if (!clauses.isEmpty())
builder.header(new DeployedContentHeader(clauses));
try {
setDeploymentManifest(builder.build());
} catch (Exception e) {
throw new SubsystemException(e);
}
}
void setAutostart(boolean value) {
try {
synchronized (this) {
setDeploymentManifest(new DeploymentManifest.Builder()
.manifest(getDeploymentManifest()).autostart(value).build());
}
} catch (Exception e) {
throw new SubsystemException(e);
}
}
synchronized void setDeploymentManifest(DeploymentManifest value) throws IOException {
deploymentManifest = value;
Coordination coordination = Activator.getInstance().getCoordinator().peek();
if (logger.isDebugEnabled())
logger.debug("Setting deployment manifest for subsystem {} using coordination {}", getSymbolicName(), coordination == null ? null : coordination.getName());
if (coordination == null) {
saveDeploymentManifest();
} else {
Map<Class<?>, Object> variables = coordination.getVariables();
synchronized (variables) {
@SuppressWarnings("unchecked")
Set<BasicSubsystem> dirtySubsystems = (Set<BasicSubsystem>) variables.get(SaveManifestParticipant.class);
if (dirtySubsystems == null) {
// currently no dirty subsystems found;
// create a list to hold them and store it as a variable
dirtySubsystems = new HashSet<BasicSubsystem>();
variables.put(SaveManifestParticipant.class, dirtySubsystems);
// add the save manifest participant
coordination.addParticipant(new SaveManifestParticipant());
}
dirtySubsystems.add(this);
}
}
}
synchronized void saveDeploymentManifest() throws IOException {
File file = new File(getDirectory(), "OSGI-INF");
if (!file.exists())
file.mkdirs();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file, "DEPLOYMENT.MF")));
try {
if (logger.isDebugEnabled())
logger.debug("Writing deployment manifest for subsystem {} in state {}", getSymbolicName(), getState());
deploymentManifest.write(out);
if (logger.isDebugEnabled())
logger.debug("Wrote deployment manifest for subsystem {} in state {}", getSymbolicName(), getState());
}
finally {
IOUtils.close(out);
}
}
void setState(State value) {
if (logger.isDebugEnabled())
logger.debug("Setting state of subsystem {} to {}", getSymbolicName(), value);
State state = getState();
if (value.equals(state)) {
if (logger.isDebugEnabled())
logger.debug("Requested state {} equals current state {}", value, state);
return;
}
try {
if (logger.isDebugEnabled())
logger.debug("Setting the deployment manifest...");
synchronized (this) {
setDeploymentManifest(new DeploymentManifest.Builder()
.manifest(getDeploymentManifest()).state(value).build());
}
} catch (Exception e) {
throw new SubsystemException(e);
}
Activator.getInstance().getSubsystemServiceRegistrar().update(this);
synchronized (this) {
if (logger.isDebugEnabled())
logger.debug("Notifying all waiting for state change of subsystem {}", getSymbolicName());
notifyAll();
}
}
void setRegionContextBundle(Bundle value) {
regionContextBundle = value; // volatile variable
}
synchronized void setSubsystemManifest(SubsystemManifest value) throws URISyntaxException, IOException {
File file = new File(getDirectory(), "OSGI-INF");
if (!file.exists())
file.mkdirs();
FileOutputStream fos = new FileOutputStream(new File(file, "SUBSYSTEM.MF"));
try {
value.write(fos);
subsystemManifest = value;
}
finally {
IOUtils.close(fos);
}
}
private final ReentrantLock stateChangeLock = new ReentrantLock();
ReentrantLock stateChangeLock() {
return stateChangeLock;
}
private String getDeploymentManifestHeaderValue(String name) {
DeploymentManifest manifest = getDeploymentManifest();
if (manifest == null)
return null;
Header<?> header = manifest.getHeaders().get(name);
if (header == null)
return null;
return header.getValue();
}
@Override
public synchronized void addRequirements(Collection<Requirement> requirements) {
// The root subsystem has no requirements (there is no parent to import from).
if (isRoot())
throw new UnsupportedOperationException("The root subsystem does not accept additional requirements");
// Unscoped subsystems import everything already.
if (!isScoped())
return;
RegionUpdater updater = new RegionUpdater(getRegion(), ((BasicSubsystem)getParents().iterator().next()).getRegion());
try {
updater.addRequirements(requirements);
}
catch (Exception e) {
throw new SubsystemException(e);
}
}
@Override
public AriesSubsystem install(String location, IDirectory content) {
return install(location, content, null);
}
@Override
public AriesSubsystem install(String location, IDirectory content, InputStream deploymentManifest) {
try {
return AccessController.doPrivileged(new InstallAction(location, content, this, AccessController.getContext(), deploymentManifest));
}
finally {
IOUtils.close(deploymentManifest);
}
}
private static class SaveManifestParticipant implements Participant {
protected SaveManifestParticipant() {}
@Override
public void ended(Coordination coordination) throws Exception {
if (logger.isDebugEnabled())
logger.debug("Saving deployment manifests because coordination {} ended", coordination.getName());
Map<Class<?>, Object> variables = coordination.getVariables();
Set<BasicSubsystem> dirtySubsystems;
synchronized (variables) {
@SuppressWarnings("unchecked")
Set<BasicSubsystem> temp = (Set<BasicSubsystem>) variables.remove(SaveManifestParticipant.class);
dirtySubsystems = temp == null ? Collections. <BasicSubsystem>emptySet() : temp;
}
for (BasicSubsystem dirtySubsystem : dirtySubsystems) {
if (logger.isDebugEnabled())
logger.debug("Saving deployment manifest of subsystem {} for coordination {}", dirtySubsystem.getSymbolicName(), coordination.getName());
dirtySubsystem.saveDeploymentManifest();
}
}
@Override
public void failed(Coordination coordination) throws Exception {
// Do no saving
}
}
@Override
public Map<String, String> getDeploymentHeaders() {
SecurityManager.checkMetadataPermission(this);
return AccessController.doPrivileged(new GetDeploymentHeadersAction(this));
}
@Override
public AriesSubsystem install(String location, final InputStream content, InputStream deploymentManifest) {
AriesSubsystem result = null;
IDirectory directory = null;
try {
directory = content == null ? null :
AccessController.doPrivileged(new PrivilegedAction<IDirectory>() {
@Override
public IDirectory run() {
return FileSystem.getFSRoot(content);
}
});
result = install(location, directory, deploymentManifest);
return result;
}
finally {
// This method must guarantee the content input stream was closed.
// TODO Not sure closing the content is necessary. The content will
// either be null of will have been closed while copying the data
// to the temporary file.
IOUtils.close(content);
// If appropriate, delete the temporary file. Subsystems having
// apache-aries-provision-dependencies:=resolve may need the file
// at start time if it contains any dependencies.
if (directory instanceof ICloseableDirectory) {
if (result == null
|| Utils.isProvisionDependenciesInstall((BasicSubsystem)result)
|| !wasInstalledWithChildrenHavingProvisionDependenciesResolve()) {
final IDirectory toClose = directory;
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
try {
((ICloseableDirectory) toClose).close();
}
catch (IOException ioex) {
logger.info("Exception calling close for content {}. Exception {}",
content, ioex);
}
return null;
}
});
}
}
}
}
private void setTranslations() throws IOException {
String directoryName = getSubsystemManifest().getSubsystemLocalizationHeader().getDirectoryName();
File file = directoryName == null ? getDirectory() : new File(getDirectory(), directoryName);
if (!file.exists())
file.mkdirs();
for (TranslationFile translation : getResource().getTranslations()) {
translation.write(file);
}
}
void computeDependenciesPostInstallation(Coordination coordination) throws IOException {
resource.computeDependencies(null, coordination);
ProvisionResourceHeader header = resource.computeProvisionResourceHeader();
setDeploymentManifest(
new DeploymentManifest.Builder()
.manifest(deploymentManifest)
.header(header)
.build());
}
private boolean wasInstalledWithChildrenHavingProvisionDependenciesResolve() {
return wasInstalledWithChildrenHavingProvisionDependenciesResolve(this);
}
private static boolean wasInstalledWithChildrenHavingProvisionDependenciesResolve(Subsystem child) {
BasicSubsystem bs = (BasicSubsystem) child;
SubsystemManifest manifest = bs.getSubsystemManifest();
SubsystemTypeHeader header = manifest.getSubsystemTypeHeader();
AriesProvisionDependenciesDirective directive = header.getAriesProvisionDependenciesDirective();
if (directive.isResolve()) {
return true;
}
return wasInstalledWithChildrenHavingProvisionDependenciesResolve(child.getChildren());
}
private static boolean wasInstalledWithChildrenHavingProvisionDependenciesResolve(Collection<Subsystem> children) {
for (Subsystem child : children) {
if (wasInstalledWithChildrenHavingProvisionDependenciesResolve(child)) {
return true;
}
}
return false;
}
@Override
public String toString() {
return new StringBuilder()
.append(getClass().getName())
.append(": ")
.append("children=")
.append(getChildren().size())
.append(", constituents=")
.append(getConstituents().size())
.append(", id=")
.append(getSubsystemId())
.append(", location=")
.append(getLocation())
.append(", parents=")
.append(getParents().size())
.append(", state=")
.append(getState())
.append(", symbolicName=")
.append(getSymbolicName())
.append(", type=")
.append(getType())
.append(", version=")
.append(getVersion())
.toString();
}
}
| 8,654 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/GetSubsystemHeadersAction.java | /*
* 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.subsystem.core.internal;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import org.apache.aries.subsystem.core.archive.Header;
public class GetSubsystemHeadersAction implements PrivilegedAction<Map<String, String>> {
private final Locale locale;
private final BasicSubsystem subsystem;
public GetSubsystemHeadersAction(BasicSubsystem subsystem, Locale locale) {
this.subsystem = subsystem;
this.locale = locale;
}
@Override
public Map<String, String> run() {
Map<String, Header<?>> headers = subsystem.getSubsystemManifest().getHeaders();
Map<String, String> result = new HashMap<String, String>(headers.size());
for (Entry<String, Header<?>> entry: headers.entrySet()) {
Header<?> value = entry.getValue();
result.put(entry.getKey(), translate(value.getValue()));
}
return result;
}
private String translate(String value) {
if (locale == null || value == null || !value.startsWith("%"))
return value;
String localizationStr = subsystem.getSubsystemManifest().getSubsystemLocalizationHeader().getValue();
File rootDir;
File localizationFile;
try {
rootDir = subsystem.getDirectory().getCanonicalFile();
localizationFile = new File(rootDir, localizationStr).getCanonicalFile();
}
catch (IOException e) {
// TODO Log this. Particularly a problem if rootDir throws an
// exception as corruption has occurred. May want to let that
// propagate as a runtime exception.
return value;
}
URI rootUri = rootDir.toURI();
// The last segment of the Subsystem-Localization header value is the
// base file name. The directory is its parent.
URI localizationUri = localizationFile.getParentFile().toURI();
if (rootUri.relativize(localizationUri).equals(localizationUri))
// TODO Log this. The value of the Subsystem-Localization header
// is not relative to the subsystem root directory.
return value;
URL localizationUrl;
try {
localizationUrl = localizationUri.toURL();
}
catch (MalformedURLException e) {
// TODO Should never happen but log it anyway.
return value;
}
URLClassLoader classLoader = new URLClassLoader(new URL[]{localizationUrl});
try {
ResourceBundle rb = ResourceBundle.getBundle(localizationFile.getName(), locale, classLoader);
return rb.getString(value.substring(1));
}
catch (Exception e) {
return value;
}
}
}
| 8,655 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/TargetRegion.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.HashSet;
import org.osgi.framework.Version;
import org.osgi.service.subsystem.Subsystem;
public class TargetRegion {
Collection<Subsystem> region = new HashSet<Subsystem>();
public TargetRegion(BasicSubsystem subsystem) {
// Find the scoped subsystem that controls the region.
while (!subsystem.isScoped()) {
subsystem = (BasicSubsystem) subsystem.getParents().iterator().next();
}
// All children of the scoped subsystem controlling the region are
// part of the target region, even those that are scoped subsystems.
add(subsystem.getChildren());
}
public boolean contains(Subsystem subsystem) {
return find(subsystem.getSymbolicName(), subsystem.getVersion()) != null;
}
public Subsystem find(String symbolicName, Version version) {
for (Subsystem s : region) {
if (s.getSymbolicName().equals(symbolicName)
&& s.getVersion().equals(version))
return s;
}
return null;
}
private void add(Collection<Subsystem> children) {
for (Subsystem child : children) {
region.add(child);
if (((BasicSubsystem) child).isScoped()) {
// Children of scoped children are not part of the target region.
continue;
}
// Children of unscoped children are part of the target region.
add(child.getChildren());
}
}
}
| 8,656 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemManifestValidator.java | /*
* 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.subsystem.core.internal;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.core.archive.PreferredProviderHeader;
import org.apache.aries.subsystem.core.archive.ProvisionPolicyDirective;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.apache.aries.subsystem.core.archive.SubsystemTypeHeader;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class SubsystemManifestValidator {
public static void validate(BasicSubsystem subsystem, SubsystemManifest manifest) {
if (subsystem.getResource().getId() == 0) {
return;
}
validatePreferredProviderHeader(manifest.getPreferredProviderHeader());
validateAriesProvisionDependenciesDirective(subsystem);
if (subsystem.isComposite()) {
SubsystemContentHeader header = manifest.getSubsystemContentHeader();
if (header == null) {
return;
}
for (SubsystemContentHeader.Clause clause : header.getClauses()) {
if (!clause.getVersionRange().isExact()) {
throw new SubsystemException("Composite subsystem using version range for content: " + clause);
}
}
}
else if (subsystem.isFeature()) {
SubsystemTypeHeader subsystemTypeHeader = manifest.getSubsystemTypeHeader();
ProvisionPolicyDirective provisionPolicyDirective = subsystemTypeHeader.getProvisionPolicyDirective();
if (provisionPolicyDirective.isAcceptDependencies()) {
throw new SubsystemException("Feature subsystems may not declare a provision-policy of acceptDependencies");
}
if (manifest.getHeaders().get(SubsystemConstants.PREFERRED_PROVIDER) != null) {
throw new SubsystemException("Feature subsystems may not declare a " + SubsystemConstants.PREFERRED_PROVIDER + " header");
}
}
}
private static void validatePreferredProviderHeader(PreferredProviderHeader header) {
if (header == null) {
return;
}
for (PreferredProviderHeader.Clause clause : header.getClauses()) {
String type = (String)clause.getAttribute(PreferredProviderHeader.Clause.ATTRIBUTE_TYPE).getValue();
if (!(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type) ||
SubsystemConstants.SUBSYSTEM_TYPE_FEATURE.equals(type) ||
Constants.ResourceTypeBundle.equals(type))) {
throw new SubsystemException("Unsupported " + PreferredProviderHeader.NAME + " type: " + type);
}
}
}
private static void validateAriesProvisionDependenciesDirective(BasicSubsystem subsystem) {
AriesProvisionDependenciesDirective directive = subsystem.getAriesProvisionDependenciesDirective();
BasicSubsystem parent = subsystem.getResource().getParents().iterator().next();
AriesProvisionDependenciesDirective parentDirective = parent.getAriesProvisionDependenciesDirective();
if (!directive.equals(parentDirective)
&& (subsystem.isFeature()
|| State.INSTALLING.equals(parent.getState()))) {
throw new SubsystemException("The value of the "
+ AriesProvisionDependenciesDirective.NAME
+ " directive must be the same as the parent subsystem for features and implicitly installed subsystems.");
}
}
}
| 8,657 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BundleResourceUninstaller.java | /*
* 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.subsystem.core.internal;
import org.apache.aries.subsystem.core.internal.BundleResourceInstaller.BundleConstituent;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemException;
public class BundleResourceUninstaller extends ResourceUninstaller {
public BundleResourceUninstaller(Resource resource, BasicSubsystem subsystem) {
super(resource, subsystem);
}
public void uninstall() {
removeReference();
// Always remove the bundle as a constituent of the subsystem being
// acted upon. The bundle may or may not actually be a constituent.
// This covers the case of unscoped subsystems with shared content
// where the resource may not be uninstallable.
removeConstituent(subsystem, new BundleConstituent(null, (BundleRevision)resource));
if (!isResourceUninstallable())
return;
// If the resource is uninstallable, remove it from the "provisioned to"
// subsystem in case it was a dependency. The "provisioned to" subsystem
// may be the same subsystem as the one being acted upon. This covers
// the case where a dependency of the subsystem being acted upon was
// provisioned to another subsystem but is not content of the other
// subsystem.
removeConstituent(provisionTo, new BundleConstituent(null, (BundleRevision)resource));
if (isBundleUninstallable())
uninstallBundle();
}
private Bundle getBundle() {
return getBundleRevision().getBundle();
}
private BundleRevision getBundleRevision() {
return (BundleRevision)resource;
}
private boolean isBundleUninstallable() {
return getBundle().getState() != Bundle.UNINSTALLED;
}
private void uninstallBundle() {
ThreadLocalSubsystem.set(provisionTo);
try {
getBundle().uninstall();
}
catch (BundleException e) {
throw new SubsystemException(e);
}
finally {
ThreadLocalSubsystem.remove();
}
}
}
| 8,658 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ServiceModeller.java | /*
* 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.subsystem.core.internal;
import java.util.List;
import org.apache.aries.util.filesystem.IDirectory;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemException;
public interface ServiceModeller {
public static interface ServiceModel {
List<Requirement> getServiceRequirements();
List<Capability> getServiceCapabilities();
}
ServiceModel computeRequirementsAndCapabilities(Resource resource, IDirectory directory) throws SubsystemException;
}
| 8,659 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ThreadLocalBundleRevision.java | /*
* 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.subsystem.core.internal;
import org.osgi.framework.wiring.BundleRevision;
public class ThreadLocalBundleRevision {
private static ThreadLocal<BundleRevision> bundleRevision = new ThreadLocal<BundleRevision>();
public static BundleRevision get() {
return bundleRevision.get();
}
public static void remove() {
bundleRevision.remove();
}
public static void set(BundleRevision value) {
bundleRevision.set(value);
}
}
| 8,660 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/Utils.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.apache.aries.subsystem.core.archive.ProvisionResourceHeader;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.coordinator.CoordinationException;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
import org.osgi.service.subsystem.Subsystem.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Utils {
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
public static String computeCoordinationName(Subsystem subsystem) {
return subsystem.getSymbolicName() + '-' + subsystem.getSubsystemId();
}
public static Coordination createCoordination() {
return Activator.getInstance().getCoordinator().begin(BasicSubsystem.ROOT_SYMBOLIC_NAME + "-0", 0);
}
public static Coordination createCoordination(BasicSubsystem subsystem) {
return Activator.getInstance().getCoordinator().begin(computeCoordinationName(subsystem), 0);
}
public static BasicSubsystem findFirstSubsystemAcceptingDependenciesStartingFrom(BasicSubsystem subsystem) {
// The following loop is guaranteed to end once the root subsystem has
// been reached.
while (!isAcceptDependencies(subsystem))
subsystem = (BasicSubsystem)subsystem.getParents().iterator().next();
return subsystem;
}
public static BasicSubsystem findFirstScopedAncestorWithSharingPolicy(SubsystemResource descendant) {
Collection<BasicSubsystem> parents = descendant.getParents();
if (parents == null || parents.isEmpty()) {
return null;
}
BasicSubsystem result = (BasicSubsystem) parents.iterator().next();
// The result is defined as the first scoped ancestor whose sharing
// policy has already been set. This covers the case of multiple
// subsystems from the same archive being installed whose regions will
// form a tree of depth N.
while ( // We only want scoped subsystems because they control
// the region.
!result.isScoped()
// If the state is INSTALLING then the sharing policy
// has not yet been set. This means we cannot use the
// region in order to test visibility and must proceed
// to the next parent.
|| result.getState().equals(State.INSTALLING)) {
result = result.getResource().getParents().iterator().next();
}
return result;
}
public static BasicSubsystem findScopedSubsystemInRegion(BasicSubsystem subsystem) {
while (!subsystem.isScoped())
subsystem = (BasicSubsystem)subsystem.getParents().iterator().next();
return subsystem;
}
public static int getActiveUseCount(Resource resource) {
int result = 0;
for (BasicSubsystem subsystem : Activator.getInstance().getSubsystems().getSubsystemsReferencing(resource)) {
if ( // ACTIVE subsystem referencing the resource.
Subsystem.State.ACTIVE.equals(subsystem.getState())
// Ensure unmanaged bundle constituents of the root subsystem are not stopped or uninstalled.
|| (subsystem.isRoot() && isBundle(resource))) {
result++;
}
}
return result;
}
public static long getId(Resource resource) {
if (resource instanceof BasicSubsystem)
return ((BasicSubsystem)resource).getSubsystemId();
if (resource instanceof BundleRevision)
return ((BundleRevision)resource).getBundle().getBundleId();
return -1;
}
public static void handleTrowable(Throwable t) {
if (t instanceof SubsystemException) {
throw (SubsystemException)t;
}
if (t instanceof SecurityException) {
throw (SecurityException)t;
}
throw new SubsystemException(t);
}
public static void installResource(Resource resource, BasicSubsystem subsystem) {
Coordination coordination = Utils.createCoordination(subsystem);
try {
ResourceInstaller.newInstance(coordination, resource, subsystem).install();
}
catch (Throwable t) {
coordination.fail(t);
}
finally {
try {
coordination.end();
}
catch (CoordinationException e) {
logger.error("Resource could not be installed", e);
}
}
}
public static boolean isAcceptDependencies(BasicSubsystem subsystem) {
return subsystem.getSubsystemManifest().getSubsystemTypeHeader().getProvisionPolicyDirective().isAcceptDependencies();
}
public static boolean isBundle(Resource resource) {
String type = ResourceHelper.getTypeAttribute(resource);
return IdentityNamespace.TYPE_BUNDLE.equals(type) ||
IdentityNamespace.TYPE_FRAGMENT.equals(type);
}
public static boolean isFragment(Resource resource) {
String type = ResourceHelper.getTypeAttribute(resource);
return IdentityNamespace.TYPE_FRAGMENT.equals(type);
}
public static boolean isEffectiveResolve(Requirement requirement) {
Map<String, String> directives = requirement.getDirectives();
String value = directives.get(Namespace.REQUIREMENT_EFFECTIVE_DIRECTIVE);
return value == null || Namespace.EFFECTIVE_RESOLVE.equals(value);
}
public static boolean isMandatory(Requirement requirement) {
Map<String, String> directives = requirement.getDirectives();
String value = directives.get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE);
return value == null || Namespace.RESOLUTION_MANDATORY.equals(value);
}
/*
* The Deployed-Content header in the deployment manifest is used to store
* information about explicitly installed resources and provisioned
* dependencies in addition to content for persistence purposes. This method
* returns true only if the resource is "true" content of the subsystem and,
* therefore, uses the Subsystem-Content header from the subsystem manifest.
*/
public static boolean isContent(BasicSubsystem subsystem, Resource resource) {
SubsystemManifest subsystemManifest = subsystem.getSubsystemManifest();
if (subsystemManifest == null)
return false;
SubsystemContentHeader subsystemContentHeader = subsystemManifest.getSubsystemContentHeader();
if (subsystemContentHeader == null)
return false;
return subsystemContentHeader.contains(resource);
}
public static boolean isDependency(BasicSubsystem subsystem, Resource resource) {
DeploymentManifest manifest = subsystem.getDeploymentManifest();
if (manifest == null)
return false;
ProvisionResourceHeader header = manifest.getProvisionResourceHeader();
if (header == null)
return false;
return header.contains(resource);
}
public static boolean isInstallableResource(Resource resource) {
return !isSharedResource(resource);
}
public static boolean isRegionContextBundle(Resource resource) {
return ResourceHelper.getSymbolicNameAttribute(resource).startsWith(
RegionContextBundleHelper.SYMBOLICNAME_PREFIX);
}
public static boolean isSharedResource(Resource resource) {
return resource instanceof BasicSubsystem || resource instanceof BundleRevision || resource instanceof BundleRevisionResource;
}
public static boolean isSubsystem(Resource resource) {
String type = ResourceHelper.getTypeAttribute(resource);
return SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION.equals(type) ||
SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type) ||
SubsystemConstants.SUBSYSTEM_TYPE_FEATURE.equals(type);
}
public static boolean isProvisionDependenciesInstall(BasicSubsystem subsystem) {
return subsystem.getSubsystemManifest().getSubsystemTypeHeader().getAriesProvisionDependenciesDirective().isInstall();
}
}
| 8,661 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ContentRepository.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.apache.aries.subsystem.core.capabilityset.CapabilitySetRepository;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
public class ContentRepository implements org.apache.aries.subsystem.core.repository.Repository {
private final CapabilitySetRepository installableContent;
private final CapabilitySetRepository sharedContent;
public ContentRepository(Collection<Resource> installableContent, Collection<Resource> sharedContent) {
this.installableContent = new CapabilitySetRepository();
for (Resource resource : installableContent) {
this.installableContent.addResource(resource);
}
this.sharedContent = new CapabilitySetRepository();
for (Resource resource : sharedContent) {
this.sharedContent.addResource(resource);
}
}
@Override
public Map<Requirement, Collection<Capability>> findProviders(
Collection<? extends Requirement> requirements) {
Map<Requirement, Collection<Capability>> result = sharedContent.findProviders(requirements);
for (Map.Entry<Requirement, Collection<Capability>> entry : result.entrySet()) {
if (entry.getValue().isEmpty()) {
entry.setValue(
installableContent.findProviders(
Collections.singletonList(entry.getKey())).get(entry.getKey()));
}
}
return result;
}
}
| 8,662 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemUri.java | /*
* 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.subsystem.core.internal;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.aries.subsystem.core.archive.SubsystemSymbolicNameHeader;
import org.apache.aries.subsystem.core.archive.SubsystemVersionHeader;
import org.osgi.framework.Version;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemUri {
private static final String REGEXP = "([^=]*)=([^&]*)&?";
private static final Pattern PATTERN = Pattern.compile(REGEXP);
private final String symbolicName;
private final URL url;
private final Version version;
public SubsystemUri(String location) throws URISyntaxException, MalformedURLException {
if (!location.startsWith("subsystem://"))
throw new IllegalArgumentException(location);
URI uri = new URI(location);
if (uri.getAuthority() != null)
url = new URL(uri.getAuthority());
else
url = null;
Matcher matcher = PATTERN.matcher(uri.getQuery());
String symbolicName = null;
Version version = Version.emptyVersion;
while (matcher.find()) {
String name = matcher.group(1);
if (SubsystemSymbolicNameHeader.NAME.equals(name))
symbolicName = new SubsystemSymbolicNameHeader(matcher.group(2)).getValue();
else if (SubsystemVersionHeader.NAME.equals(name))
version = Version.parseVersion(matcher.group(2));
else
throw new IllegalArgumentException("Unsupported subsystem URI parameter: " + name);
}
this.symbolicName = symbolicName;
this.version = version;
}
public SubsystemUri(String symbolicName, Version version, URL url) {
// TODO symbolicName should conform to OSGi grammar.
if (symbolicName == null || symbolicName.length() == 0)
throw new IllegalArgumentException(
"Missing required parameter: symbolicName");
this.symbolicName = symbolicName;
this.version = version;
this.url = url;
}
public String getSymbolicName() {
return symbolicName;
}
public URL getURL() {
return url;
}
public Version getVersion() {
return version;
}
@SuppressWarnings("deprecation")
public String toString() {
StringBuilder builder = new StringBuilder("subsystem://");
if (url != null) {
try {
builder.append(URLEncoder.encode(url.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
builder.append(URLEncoder.encode(url.toString()));
}
}
builder.append('?').append(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME)
.append('=').append(symbolicName);
if (version != null)
builder.append('&').append(SubsystemConstants.SUBSYSTEM_VERSION)
.append('=').append(version);
return builder.toString();
}
}
| 8,663 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BundleDirectory.java | /*
* 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.subsystem.core.internal;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.aries.util.filesystem.ICloseableDirectory;
import org.apache.aries.util.filesystem.IDirectory;
import org.apache.aries.util.filesystem.IFile;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.SubsystemException;
public class BundleDirectory implements IDirectory {
private static class BundleFile implements IFile {
private final BundleDirectory directory;
private final String name;
private final URL url;
public BundleFile(String name, URL url, BundleDirectory directory) {
this.name = name;
this.url = url;
this.directory = directory;
}
@Override
public IDirectory convert() {
return null;
}
@Override
public IDirectory convertNested() {
try {
return FileSystem.getFSRoot(url.openStream());
}
catch (IOException e) {
throw new SubsystemException(e);
}
}
@Override
public long getLastModified() {
return 0;
}
@Override
public String getName() {
if (name.startsWith("/"))
return name.substring(1);
return name;
}
@Override
public IDirectory getParent() {
return directory;
}
@Override
public IDirectory getRoot() {
return directory;
}
@Override
public long getSize() {
return 0;
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public boolean isFile() {
return true;
}
@Override
public InputStream open() throws IOException,
UnsupportedOperationException {
return url.openStream();
}
@Override
public URL toURL() throws MalformedURLException {
return url;
}
}
private final Bundle bundle;
public BundleDirectory(Bundle bundle) {
if (bundle == null)
throw new NullPointerException();
this.bundle = bundle;
}
@Override
public Iterator<IFile> iterator() {
return listAllFiles().iterator();
}
@Override
public IDirectory convert() {
return this;
}
@Override
public IDirectory convertNested() {
return this;
}
@Override
public long getLastModified() {
return 0;
}
@Override
public String getName() {
return "";
}
@Override
public IDirectory getParent() {
return null;
}
@Override
public IDirectory getRoot() {
return this;
}
@Override
public long getSize() {
return 0;
}
@Override
public boolean isDirectory() {
return true;
}
@Override
public boolean isFile() {
return false;
}
@Override
public InputStream open() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public URL toURL() throws MalformedURLException {
return bundle.getEntry("/");
}
@Override
public IFile getFile(final String name) {
if (name == null || name.length() == 0)
return null;
if ("/".equals(name))
return this;
URL entry = bundle.getEntry(name);
if (entry == null)
return null;
return new BundleFile(name, entry, this);
}
@Override
public boolean isRoot() {
return true;
}
@Override
public List<IFile> listAllFiles() {
return listFiles(true);
}
@Override
public List<IFile> listFiles() {
return listFiles(false);
}
@Override
public ICloseableDirectory toCloseable() {
return null;
}
private List<IFile> listFiles(boolean recurse) {
Enumeration<URL> entries = bundle.findEntries("/", null, recurse);
if (entries == null)
return Collections.emptyList();
ArrayList<IFile> files = new ArrayList<IFile>();
while (entries.hasMoreElements()) {
URL entry = entries.nextElement();
if (entry.getPath().endsWith("/"))
continue;
files.add(new BundleFile(entry.getPath(), entry, this));
}
files.trimToSize();
return files;
}
}
| 8,664 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/GetDeploymentHeadersAction.java | /*
* 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.subsystem.core.internal;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.aries.subsystem.core.archive.Header;
public class GetDeploymentHeadersAction implements PrivilegedAction<Map<String, String>> {
private final BasicSubsystem subsystem;
public GetDeploymentHeadersAction(BasicSubsystem subsystem) {
this.subsystem = subsystem;
}
@Override
public Map<String, String> run() {
Map<String, Header<?>> headers = subsystem.getDeploymentManifest().getHeaders();
Map<String, String> result = new HashMap<String, String>(headers.size());
for (Entry<String, Header<?>> entry: headers.entrySet()) {
Header<?> value = entry.getValue();
result.put(entry.getKey(), value.getValue());
}
return result;
}
}
| 8,665 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BundleResource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.subsystem.core.internal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.subsystem.core.archive.BundleManifest;
import org.apache.aries.subsystem.core.archive.BundleRequiredExecutionEnvironmentHeader;
import org.apache.aries.subsystem.core.archive.BundleSymbolicNameHeader;
import org.apache.aries.subsystem.core.archive.BundleVersionHeader;
import org.apache.aries.subsystem.core.archive.ExportPackageHeader;
import org.apache.aries.subsystem.core.archive.FragmentHostCapability;
import org.apache.aries.subsystem.core.archive.FragmentHostHeader;
import org.apache.aries.subsystem.core.archive.FragmentHostRequirement;
import org.apache.aries.subsystem.core.archive.ImportPackageHeader;
import org.apache.aries.subsystem.core.archive.ProvideBundleCapability;
import org.apache.aries.subsystem.core.archive.ProvideCapabilityCapability;
import org.apache.aries.subsystem.core.archive.ProvideCapabilityHeader;
import org.apache.aries.subsystem.core.archive.RequireBundleHeader;
import org.apache.aries.subsystem.core.archive.RequireBundleRequirement;
import org.apache.aries.subsystem.core.archive.RequireCapabilityHeader;
import org.apache.aries.subsystem.core.archive.RequireCapabilityRequirement;
import org.apache.aries.subsystem.core.archive.RequirementHeader;
import org.apache.aries.util.filesystem.IDirectory;
import org.apache.aries.util.filesystem.IFile;
import org.apache.aries.util.io.IOUtils;
import org.osgi.framework.Constants;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemException;
public class BundleResource implements Resource, org.apache.aries.subsystem.core.repository.RepositoryContent {
private static BundleManifest computeManifest(IDirectory directory, IFile content) {
org.apache.aries.util.manifest.BundleManifest bm =
org.apache.aries.util.manifest.BundleManifest.fromBundle(directory);
if (bm == null) {
throw new IllegalArgumentException("File \"" + content.getName() + "\" contains no bundle manifest META-INF/MANIFEST.MF.");
}
Manifest m = bm.getRawManifest();
BundleManifest result = new BundleManifest(m);
if (result.getHeader(Constants.BUNDLE_SYMBOLICNAME) == null) {
throw new IllegalArgumentException("File \"" + content.getName() + "\" has a META-INF/MANIFEST.MF with no Bundle-SymbolicName header.");
}
return result;
}
private final List<Capability> capabilities = new ArrayList<Capability>();
private final IFile content;
private final BundleManifest manifest;
private final List<Requirement> requirements = new ArrayList<Requirement>();
public BundleResource(IFile content) {
this.content = content;
IDirectory dir = content.isDirectory() ? content.convert() : content.convertNested();
manifest = computeManifest(dir, content);
computeRequirementsAndCapabilities(dir);
}
public List<Capability> getCapabilities(String namespace) {
if (namespace == null)
return Collections.unmodifiableList(capabilities);
ArrayList<Capability> result = new ArrayList<Capability>(capabilities.size());
for (Capability capability : capabilities)
if (namespace.equals(capability.getNamespace()))
result.add(capability);
result.trimToSize();
return Collections.unmodifiableList(result);
}
public String getLocation() {
return getFileName(content);
}
@Override
public InputStream getContent() {
try {
if (content.isFile())
return content.open();
try {
// Give the IDirectory a shot at opening in case it supports it.
return content.open();
}
catch (UnsupportedOperationException e) {
// As a last ditch effort, try to jar up the contents.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream out = new JarOutputStream(baos, manifest.getManifest());
try {
jar(out, "", content.convert());
}
finally {
IOUtils.close(out);
}
return new ByteArrayInputStream(baos.toByteArray());
}
}
catch (Exception e) {
throw new SubsystemException(e);
}
}
public List<Requirement> getRequirements(String namespace) {
if (namespace == null)
return Collections.unmodifiableList(requirements);
ArrayList<Requirement> result = new ArrayList<Requirement>(requirements.size());
for (Requirement requirement : requirements)
if (namespace.equals(requirement.getNamespace()))
result.add(requirement);
result.trimToSize();
return Collections.unmodifiableList(result);
}
@Override
public String toString() {
return content.toString();
}
private void computeCapabilitiesOtherThanService() {
computeOsgiIdentityCapability();
computeOsgiWiringPackageCapabilities();
computeOsgiWiringBundleCapability();
computeGenericCapabilities();
}
private void computeGenericCapabilities() {
ProvideCapabilityHeader pch = (ProvideCapabilityHeader)manifest.getHeader(ProvideCapabilityHeader.NAME);
if (pch != null)
for (ProvideCapabilityHeader.Clause clause : pch.getClauses())
capabilities.add(new ProvideCapabilityCapability(clause, this));
}
private void computeGenericRequirements() {
RequireCapabilityHeader rch = (RequireCapabilityHeader)manifest.getHeader(RequireCapabilityHeader.NAME);
if (rch != null)
for (RequireCapabilityHeader.Clause clause : rch.getClauses())
requirements.add(new RequireCapabilityRequirement(clause, this));
}
private void computeOsgiExecutionEnvironmentRequirement() {
RequirementHeader<?> header = (RequirementHeader<?>)manifest.getHeader(BundleRequiredExecutionEnvironmentHeader.NAME);
if (header == null)
return;
requirements.addAll(header.toRequirements(this));
}
private void computeOsgiIdentityCapability() {
capabilities.add(new OsgiIdentityCapability(this, manifest));
}
private void computeOsgiWiringBundleCapability() {
if (manifest.getHeader(org.osgi.framework.Constants.FRAGMENT_HOST) != null) {
// The osgi.wiring.bundle capability is not provided by fragments.
return;
}
BundleSymbolicNameHeader bsnh = (BundleSymbolicNameHeader)manifest.getHeader(BundleSymbolicNameHeader.NAME);
BundleVersionHeader bvh = (BundleVersionHeader)manifest.getHeader(BundleVersionHeader.NAME);
capabilities.add(new ProvideBundleCapability(bsnh, bvh, this));
}
private void computeOsgiWiringBundleRequirements() {
RequireBundleHeader rbh = (RequireBundleHeader)manifest.getHeader(RequireBundleHeader.NAME);
if (rbh != null)
for (RequireBundleHeader.Clause clause : rbh.getClauses())
requirements.add(new RequireBundleRequirement(clause, this));
}
private void computeOsgiWiringHostCapability() {
if (manifest.getHeader(org.osgi.framework.Constants.FRAGMENT_HOST) != null) {
// The osgi.wiring.host capability is not provided by fragments.
return;
}
BundleSymbolicNameHeader bsnh = (BundleSymbolicNameHeader)manifest.getHeader(BundleSymbolicNameHeader.NAME);
BundleVersionHeader bvh = (BundleVersionHeader)manifest.getHeader(BundleVersionHeader.NAME);
capabilities.add(new FragmentHostCapability(bsnh, bvh, this));
}
private void computeOsgiWiringHostRequirement() {
FragmentHostHeader fhh = (FragmentHostHeader)manifest.getHeader(FragmentHostHeader.NAME);
if (fhh != null) {
requirements.add(new FragmentHostRequirement(fhh.getClauses().iterator().next(), this));
}
}
private void computeOsgiWiringPackageCapabilities() {
ExportPackageHeader eph = (ExportPackageHeader)manifest.getHeader(ExportPackageHeader.NAME);
if (eph != null)
capabilities.addAll(eph.toCapabilities(this));
}
private void computeOsgiWiringPackageRequirements() {
ImportPackageHeader iph = (ImportPackageHeader)manifest.getHeader(ImportPackageHeader.NAME);
if (iph != null)
requirements.addAll(iph.toRequirements(this));
}
private void computeRequirementsAndCapabilities(IDirectory directory) {
// Compute all requirements and capabilities other than those related
// to services.
computeRequirementsOtherThanService();
computeCapabilitiesOtherThanService();
// OSGi RFC 201 for R6: The presence of any Require/Provide-Capability
// clauses in the osgi.service namespace overrides any service related
// requirements or capabilities that might have been found by other
// means.
boolean computeServiceRequirements = getRequirements(ServiceNamespace.SERVICE_NAMESPACE).isEmpty();
boolean computeServiceCapabilities = getCapabilities(ServiceNamespace.SERVICE_NAMESPACE).isEmpty();
if (!(computeServiceCapabilities || computeServiceRequirements))
return;
// Compute service requirements and capabilities if the optional
// ModelledResourceManager service is present.
ServiceModeller modeller = getServiceModeller();
if (modeller == null)
return;
ServiceModeller.ServiceModel model = modeller.computeRequirementsAndCapabilities(this, directory);
if (computeServiceCapabilities)
capabilities.addAll(model.getServiceCapabilities());
if (computeServiceRequirements)
requirements.addAll(model.getServiceRequirements());
}
private void computeRequirementsOtherThanService() {
computeOsgiWiringPackageRequirements();
computeGenericRequirements();
computeOsgiWiringBundleRequirements();
computeOsgiExecutionEnvironmentRequirement();
computeOsgiWiringHostRequirement();
computeOsgiWiringHostCapability();
}
private String getFileName(IFile file) {
String name = file.getName();
if ("".equals(name)) {
// The file is the root directory of an archive. Use the URL
// instead. Using the empty string will likely result in duplicate
// locations during installation.
try {
name = file.toURL().toString();
}
catch (MalformedURLException e) {
throw new SubsystemException(e);
}
}
int index = name.lastIndexOf('/');
if (index == -1 || index == name.length() - 1)
return name;
return name.substring(index + 1);
}
private ServiceModeller getServiceModeller() {
return Activator.getInstance().getServiceModeller();
}
private void jar(JarOutputStream out, String prefix, IDirectory directory) throws IOException {
List<IFile> files = directory.listFiles();
for (IFile f : files) {
String fileName;
if (f.isDirectory())
fileName = prefix + getFileName(f) + "/";
else
fileName = prefix + getFileName(f);
if ("META-INF/".equalsIgnoreCase(fileName) || "META-INF/MANIFEST.MF".equalsIgnoreCase(fileName))
continue;
JarEntry entry = new JarEntry(fileName);
entry.setSize(f.getSize());
entry.setTime(f.getLastModified());
out.putNextEntry(entry);
if (f.isDirectory())
jar(out, fileName, f.convert());
else
IOUtils.copy(f.open(), out);
}
}
}
| 8,666 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/StopAction.java | /*
* 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.subsystem.core.internal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashSet;
import java.util.List;
import org.apache.aries.subsystem.ContentHandler;
import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StopAction extends AbstractAction {
private static final Logger logger = LoggerFactory.getLogger(StopAction.class);
public StopAction(BasicSubsystem requestor, BasicSubsystem target, boolean disableRootCheck) {
super(requestor, target, disableRootCheck);
}
@Override
public Object run() {
// Protect against re-entry now that cycles are supported.
if (!Activator.getInstance().getLockingStrategy().set(State.STOPPING, target)) {
return null;
}
try {
// We are now protected against re-entry.
// Acquire the global read lock to prevent installs and uninstalls
// but allow starts and stops.
Activator.getInstance().getLockingStrategy().readLock();
try {
// We are now protected against installs and uninstalls.
checkRoot();
// Compute affected subsystems. This is safe to do while only
// holding the read lock since we know that nothing can be added
// or removed.
LinkedHashSet<BasicSubsystem> subsystems = new LinkedHashSet<BasicSubsystem>();
subsystems.add(target);
List<Resource> resources = new ArrayList<Resource>(Activator.getInstance().getSubsystems().getResourcesReferencedBy(target));
for (Resource resource : resources) {
if (resource instanceof BasicSubsystem) {
subsystems.add((BasicSubsystem)resource);
}
}
// Acquire the global mutual exclusion lock while acquiring the
// state change locks of affected subsystems.
Activator.getInstance().getLockingStrategy().lock();
try {
// We are now protected against cycles.
// Acquire the state change locks of affected subsystems.
Activator.getInstance().getLockingStrategy().lock(subsystems);
}
finally {
// Release the global mutual exclusion lock as soon as possible.
Activator.getInstance().getLockingStrategy().unlock();
}
try {
// We are now protected against other starts and stops of the affected subsystems.
State state = target.getState();
if (EnumSet.of(State.INSTALLED, State.INSTALLING, State.RESOLVED).contains(state)) {
// INSTALLING is included because a subsystem may
// persist in this state without being locked when
// apache-aries-provision-dependencies:=resolve.
return null;
}
else if (EnumSet.of(State.INSTALL_FAILED, State.UNINSTALLED).contains(state)) {
throw new IllegalStateException("Cannot stop from state " + state);
}
target.setState(State.STOPPING);
SubsystemContentHeader header = target.getSubsystemManifest().getSubsystemContentHeader();
if (header != null) {
Collections.sort(resources, new StartResourceComparator(target.getSubsystemManifest().getSubsystemContentHeader()));
Collections.reverse(resources);
}
for (Resource resource : resources) {
// Don't stop the region context bundle.
if (Utils.isRegionContextBundle(resource))
continue;
try {
stopResource(resource);
}
catch (Exception e) {
logger.error("An error occurred while stopping resource " + resource + " of subsystem " + target, e);
}
}
// TODO Can we automatically assume it actually is resolved?
target.setState(State.RESOLVED);
try {
synchronized (target) {
target.setDeploymentManifest(new DeploymentManifest(
target.getDeploymentManifest(),
null,
target.isAutostart(),
target.getSubsystemId(),
SubsystemIdentifier.getLastId(),
target.getLocation(),
false,
false));
}
}
catch (Exception e) {
throw new SubsystemException(e);
}
}
finally {
// Release the state change locks of affected subsystems.
Activator.getInstance().getLockingStrategy().unlock(subsystems);
}
}
finally {
// Release the read lock.
Activator.getInstance().getLockingStrategy().readUnlock();
}
}
finally {
// Protection against re-entry no longer required.
Activator.getInstance().getLockingStrategy().unset(State.STOPPING, target);
}
return null;
}
private void stopBundleResource(Resource resource) throws BundleException {
if (target.isRoot())
return;
((BundleRevision)resource).getBundle().stop();
}
private void stopResource(Resource resource) throws BundleException, IOException {
if (Utils.getActiveUseCount(resource) > 0)
return;
String type = ResourceHelper.getTypeAttribute(resource);
if (SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION.equals(type)
|| SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type)
|| SubsystemConstants.SUBSYSTEM_TYPE_FEATURE.equals(type)) {
stopSubsystemResource(resource);
} else if (IdentityNamespace.TYPE_BUNDLE.equals(type)) {
stopBundleResource(resource);
} else if (IdentityNamespace.TYPE_FRAGMENT.equals(type)) {
return;
} else {
if (!stopCustomHandler(resource, type))
throw new SubsystemException("Unsupported resource type: " + type);
}
}
private boolean stopCustomHandler(Resource resource, String type) {
ServiceReference<ContentHandler> customHandlerRef = CustomResources.getCustomContentHandler(target, type);
if (customHandlerRef != null) {
ContentHandler customHandler = target.getBundleContext().getService(customHandlerRef);
if (customHandler != null) {
try {
customHandler.stop(ResourceHelper.getSymbolicNameAttribute(resource), type, target);
return true;
} finally {
target.getBundleContext().ungetService(customHandlerRef);
}
}
}
return false;
}
private void stopSubsystemResource(Resource resource) throws IOException {
new StopAction(target, (BasicSubsystem)resource, !((BasicSubsystem)resource).isRoot()).run();
}
}
| 8,667 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/OsgiIdentityRequirement.java | /*
* 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.subsystem.core.internal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.Version;
import org.osgi.framework.VersionRange;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemException;
public class OsgiIdentityRequirement extends AbstractRequirement {
private static Filter createFilter(String symbolicName, Version version, String type) {
return createFilter(
symbolicName,
new StringBuilder()
.append('(')
.append(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE)
.append('=')
.append(version)
.append(')')
.toString(),
type);
}
private static Filter createFilter(String symbolicName, VersionRange versionRange, String type) {
return createFilter(
symbolicName,
versionRange.toFilterString(Constants.VERSION_ATTRIBUTE),
type);
}
private static Filter createFilter(Resource resource) {
Map<String, Object> attributes = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE).get(0).getAttributes();
String symbolicName = String.valueOf(attributes.get(IdentityNamespace.IDENTITY_NAMESPACE));
Version version = Version.parseVersion(String.valueOf(attributes.get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE)));
String type = String.valueOf(attributes.get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE));
return createFilter(symbolicName, version, type);
}
private static Filter createFilter(String symbolicName, String versionFilter, String type) {
try {
return FrameworkUtil.createFilter(createFilterString(symbolicName, versionFilter, type));
}
catch (InvalidSyntaxException e) {
throw new SubsystemException(e);
}
}
private static String createFilterString(String symbolicName, String versionFilter, String type) {
return new StringBuilder("(&(")
.append(IdentityNamespace.IDENTITY_NAMESPACE)
.append('=')
.append(symbolicName)
.append(')')
.append(versionFilter)
.append('(')
.append(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE)
.append('=')
.append(type)
.append("))").toString();
}
private final Map<String, String> directives = new HashMap<String, String>();
private final Resource resource;
private final boolean transitive;
public OsgiIdentityRequirement(String symbolicName, VersionRange versionRange, String type, boolean transitive) {
this(createFilter(symbolicName, versionRange, type), null, transitive);
}
public OsgiIdentityRequirement(String symbolicName, Version version, String type, boolean transitive) {
this(createFilter(symbolicName, version, type), null, transitive);
}
public OsgiIdentityRequirement(Resource resource, boolean transitive) {
this(createFilter(resource), resource, transitive);
}
private OsgiIdentityRequirement(Filter filter, Resource resource, boolean transitive) {
this.resource = resource;
this.transitive = transitive;
directives.put(Constants.FILTER_DIRECTIVE, filter.toString());
// TODO Let's not add these directives until we know what we're doing and that
// we really need them.
// directives.put(ResourceConstants.IDENTITY_SINGLETON_DIRECTIVE, Boolean.FALSE.toString());
// directives.put(Constants.EFFECTIVE_DIRECTIVE, Constants.EFFECTIVE_RESOLVE);
}
@Override
public Map<String, Object> getAttributes() {
return Collections.emptyMap();
}
@Override
public Map<String, String> getDirectives() {
return Collections.unmodifiableMap(directives);
}
@Override
public String getNamespace() {
return IdentityNamespace.IDENTITY_NAMESPACE;
}
@Override
public Resource getResource() {
return resource;
}
public boolean isTransitiveDependency() {
return transitive;
}
}
| 8,668 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/CompositeRepository.java | /*
* 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.subsystem.core.internal;
import java.util.Arrays;
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.osgi.resource.Capability;
import org.osgi.resource.Requirement;
public class CompositeRepository implements org.apache.aries.subsystem.core.repository.Repository {
private final Collection<org.apache.aries.subsystem.core.repository.Repository> repositories;
public CompositeRepository(org.apache.aries.subsystem.core.repository.Repository...repositories) {
this(Arrays.asList(repositories));
}
public CompositeRepository(Collection<org.apache.aries.subsystem.core.repository.Repository> repositories) {
this.repositories = repositories;
}
public Collection<Capability> findProviders(Requirement requirement) {
Set<Capability> result = new HashSet<Capability>();
for (org.apache.aries.subsystem.core.repository.Repository repository : repositories) {
Map<Requirement, Collection<Capability>> map = repository.findProviders(Collections.singleton(requirement));
Collection<Capability> capabilities = map.get(requirement);
if (capabilities == null)
continue;
result.addAll(capabilities);
}
return result;
}
@Override
public Map<Requirement, Collection<Capability>> findProviders(
Collection<? extends Requirement> requirements) {
Map<Requirement, Collection<Capability>> result = new HashMap<Requirement, Collection<Capability>>();
for (Requirement requirement : requirements)
result.put(requirement, findProviders(requirement));
return result;
}
}
| 8,669 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/Activator.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import org.apache.aries.subsystem.ContentHandler;
import org.apache.aries.subsystem.core.content.ConfigAdminContentHandler;
import org.apache.aries.util.filesystem.IDirectoryFinder;
import org.eclipse.equinox.region.RegionDigraph;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.hooks.bundle.EventHook;
import org.osgi.framework.hooks.resolver.ResolverHookFactory;
import org.osgi.service.coordinator.Coordinator;
import org.osgi.service.resolver.Resolver;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The bundle activator for the this bundle. When the bundle is starting, this
* activator will create and register the SubsystemAdmin service.
*/
public class Activator implements BundleActivator, ServiceTrackerCustomizer<Object, Object> {
private static final Logger logger = LoggerFactory.getLogger(Activator.class);
public static final String MODELLED_RESOURCE_MANAGER = "org.apache.aries.application.modelling.ModelledResourceManager";
private static final String LOCK_TIMEOUT = "org.apache.aries.subsystem.lock.timeout";
public static final String LOG_ENTRY = "Method entry: {}, args {}";
public static final String LOG_EXIT = "Method exit: {}, returning {}";
private static volatile Activator instance;
public static Activator getInstance() {
Activator result = instance;
if (result == null)
throw new IllegalStateException("The activator has not been initialized or has been shutdown");
return result;
}
private volatile BundleContext bundleContext;
private volatile LockingStrategy lockingStrategy;
private volatile ConfigAdminContentHandler configAdminHandler;
private volatile Coordinator coordinator;
private volatile Object modelledResourceManager;
private volatile RegionDigraph regionDigraph;
private volatile SubsystemServiceRegistrar registrar;
private volatile Resolver resolver;
private volatile ServiceModeller serviceModeller;
private volatile Subsystems subsystems;
private volatile SystemRepositoryManager systemRepositoryManager;
private BundleEventHook bundleEventHook;
private ServiceTracker<?,?> serviceTracker;
private final Collection<IDirectoryFinder> finders = Collections.synchronizedSet(new HashSet<IDirectoryFinder>());
private final Collection<ServiceRegistration<?>> registrations = new HashSet<ServiceRegistration<?>>();
public BundleContext getBundleContext() {
return bundleContext;
}
public LockingStrategy getLockingStrategy() {
return lockingStrategy;
}
public Coordinator getCoordinator() {
return coordinator;
}
public ServiceModeller getServiceModeller() {
return serviceModeller;
}
public RegionDigraph getRegionDigraph() {
return regionDigraph;
}
public Collection<IDirectoryFinder> getIDirectoryFinders() {
return Collections.unmodifiableCollection(finders);
}
public Resolver getResolver() {
return resolver;
}
public Subsystems getSubsystems() {
return subsystems;
}
public SubsystemServiceRegistrar getSubsystemServiceRegistrar() {
logger.debug(LOG_ENTRY, "getSubsystemServiceRegistrar");
SubsystemServiceRegistrar result = registrar;
logger.debug(LOG_EXIT, "getSubsystemServiceRegistrar", result);
return result;
}
public SystemRepository getSystemRepository() {
return systemRepositoryManager.getSystemRepository();
}
@Override
public synchronized void start(BundleContext context) throws Exception {
logger.debug(LOG_ENTRY, "start", context);
bundleContext = context;
lockingStrategy = new LockingStrategy(bundleContext.getProperty(LOCK_TIMEOUT));
serviceTracker = new ServiceTracker<Object, Object>(bundleContext, generateServiceFilter(), this);
serviceTracker.open();
logger.debug(LOG_EXIT, "start");
}
@Override
public synchronized void stop(BundleContext context) {
logger.debug(LOG_ENTRY, "stop", context);
serviceTracker.close();
serviceTracker = null;
bundleContext = null;
logger.debug(LOG_EXIT, "stop");
}
private void activate() {
if (isActive() || !hasRequiredServices())
return;
synchronized (Activator.class) {
instance = Activator.this;
}
subsystems = new Subsystems();
registerBundleEventHook();
registrations.add(bundleContext.registerService(ResolverHookFactory.class, new SubsystemResolverHookFactory(subsystems), null));
Dictionary<String, Object> handlerProps = new Hashtable<String, Object>();
handlerProps.put(ContentHandler.CONTENT_TYPE_PROPERTY, ConfigAdminContentHandler.CONTENT_TYPES);
configAdminHandler = new ConfigAdminContentHandler(bundleContext);
registrations.add(bundleContext.registerService(ContentHandler.class, configAdminHandler, handlerProps));
registrar = new SubsystemServiceRegistrar(bundleContext);
systemRepositoryManager = new SystemRepositoryManager(bundleContext.getBundle(0).getBundleContext());
systemRepositoryManager.open();
BasicSubsystem root = subsystems.getRootSubsystem();
bundleEventHook.activate();
root.start();
registerWovenClassListener();
}
private void deactivate() {
if (!isActive())
return;
bundleEventHook.deactivate();
systemRepositoryManager.close();
new StopAction(subsystems.getRootSubsystem(), subsystems.getRootSubsystem(), true).run();
for (ServiceRegistration<?> registration : registrations) {
try {
registration.unregister();
}
catch (IllegalStateException e) {
logger.debug("Service had already been unregistered", e);
}
}
configAdminHandler.shutDown();
bundleEventHook.processPendingEvents();
synchronized (Activator.class) {
instance = null;
}
}
private <T> T findAlternateServiceFor(Class<T> service) {
Object[] services = serviceTracker.getServices();
if (services == null)
return null;
for (Object alternate : services)
if (service.isInstance(alternate))
return service.cast(alternate);
return null;
}
private Filter generateServiceFilter() throws InvalidSyntaxException {
return FrameworkUtil.createFilter(generateServiceFilterString());
}
private String generateServiceFilterString() {
return new StringBuilder("(|(")
.append(org.osgi.framework.Constants.OBJECTCLASS).append('=')
.append(Coordinator.class.getName()).append(")(")
.append(org.osgi.framework.Constants.OBJECTCLASS).append('=')
.append(RegionDigraph.class.getName()).append(")(")
.append(org.osgi.framework.Constants.OBJECTCLASS).append('=')
.append(Resolver.class.getName()).append(")(")
.append(org.osgi.framework.Constants.OBJECTCLASS).append('=')
.append("org.osgi.service.repository.Repository").append(")(")
.append(org.osgi.framework.Constants.OBJECTCLASS).append('=')
.append(MODELLED_RESOURCE_MANAGER).append(")(")
.append(org.osgi.framework.Constants.OBJECTCLASS).append('=')
.append(IDirectoryFinder.class.getName()).append("))").toString();
}
private boolean hasRequiredServices() {
return coordinator != null &&
regionDigraph != null &&
resolver != null;
}
private boolean isActive() {
synchronized (Activator.class) {
return instance != null && getSubsystems() != null;
}
}
private void registerBundleEventHook() {
Dictionary<String, Object> properties = new Hashtable<String, Object>(1);
properties.put(org.osgi.framework.Constants.SERVICE_RANKING, Integer.MAX_VALUE);
bundleEventHook = new BundleEventHook();
registrations.add(bundleContext.registerService(EventHook.class, bundleEventHook, properties));
}
private void registerWovenClassListener() {
registrations.add(
bundleContext.registerService(
org.osgi.framework.hooks.weaving.WovenClassListener.class,
new WovenClassListener(bundleContext, subsystems),
null));
}
/* Begin ServiceTrackerCustomizer methods */
@Override
public synchronized Object addingService(ServiceReference<Object> reference) {
Object service = bundleContext.getService(reference);
// Use all of each type of the following services.
if (service instanceof IDirectoryFinder)
finders.add((IDirectoryFinder) service);
// Use only one of each type of the following services.
else if (service instanceof Coordinator && coordinator == null)
coordinator = (Coordinator) service;
else if (service instanceof RegionDigraph && regionDigraph == null)
regionDigraph = (RegionDigraph) service;
else if (service instanceof Resolver && resolver == null)
resolver = (Resolver) service;
else {
try {
Class clazz = getClass().getClassLoader().loadClass(MODELLED_RESOURCE_MANAGER);
if (clazz.isInstance(service) && serviceModeller == null) {
modelledResourceManager = service;
serviceModeller = new ApplicationServiceModeller(service);
} else {
service = null;
}
} catch (ClassNotFoundException e) {
service = null;
} catch (NoClassDefFoundError e) {
service = null;
}
}
// Activation is harmless if already active or all required services
// have not yet been found.
activate();
// Filter guarantees we want to track all services received.
return service;
}
@Override
public void modifiedService(ServiceReference<Object> reference, Object service) {
// Nothing
}
@Override
public synchronized void removedService(ServiceReference<Object> reference, Object service) {
if (service instanceof Coordinator) {
if (service.equals(coordinator)) {
Coordinator coordinator = findAlternateServiceFor(Coordinator.class);
if (coordinator == null)
deactivate();
this.coordinator = coordinator;
}
}
else if (service instanceof RegionDigraph) {
if (service.equals(regionDigraph)) {
RegionDigraph regionDigraph = findAlternateServiceFor(RegionDigraph.class);
if (regionDigraph == null)
deactivate();
this.regionDigraph = regionDigraph;
}
}
else if (service instanceof Resolver) {
if (service.equals(resolver)) {
Resolver resolver = findAlternateServiceFor(Resolver.class);
if (resolver == null)
deactivate();
this.resolver = resolver;
}
}
else if (service instanceof IDirectoryFinder)
finders.remove(service);
else {
if (service.equals(modelledResourceManager)) {
try {
Class clazz = getClass().getClassLoader().loadClass(MODELLED_RESOURCE_MANAGER);
Object manager = findAlternateServiceFor(clazz);
if (manager == null) {
modelledResourceManager = null;
serviceModeller = null;
} else {
modelledResourceManager = service;
serviceModeller = new ApplicationServiceModeller(service);
}
} catch (ClassNotFoundException e) {
// ignore
} catch (NoClassDefFoundError e) {
// ignore
}
}
}
}
/* End ServiceTrackerCustomizer methods */
}
| 8,670 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResourceUninstaller.java | /*
* 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.subsystem.core.internal;
import org.apache.aries.subsystem.ContentHandler;
import org.apache.aries.subsystem.core.archive.ProvisionResourceHeader;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class ResourceUninstaller {
private static final Logger logger = LoggerFactory.getLogger(ResourceUninstaller.class);
public static ResourceUninstaller newInstance(Resource resource, BasicSubsystem subsystem) {
String type = ResourceHelper.getTypeAttribute(resource);
if (SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION.equals(type)
|| SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type)
|| SubsystemConstants.SUBSYSTEM_TYPE_FEATURE.equals(type)) {
return new SubsystemResourceUninstaller(resource, subsystem);
} else if (IdentityNamespace.TYPE_BUNDLE.equals(type) || IdentityNamespace.TYPE_FRAGMENT.equals(type)) {
return new BundleResourceUninstaller(resource, subsystem);
} else {
ServiceReference<ContentHandler> handlerRef = CustomResources.getCustomContentHandler(subsystem, type);
if (handlerRef != null) {
return new CustomResourceUninstaller(resource, type, subsystem, handlerRef);
} else {
throw new SubsystemException("No uninstaller exists for resource type: " + type);
}
}
}
protected static void removeConstituent(BasicSubsystem subsystem, Resource resource) {
Activator.getInstance().getSubsystems().removeConstituent(subsystem, resource);
}
protected static void removeReference(BasicSubsystem subsystem, Resource resource) {
Activator.getInstance().getSubsystems().removeReference(subsystem, resource);
}
protected final BasicSubsystem provisionTo;
protected final Resource resource;
protected final BasicSubsystem subsystem;
public ResourceUninstaller(Resource resource, BasicSubsystem subsystem) {
if (resource == null)
throw new NullPointerException("Missing required parameter: resource");
if (subsystem == null)
throw new NullPointerException("Missing required parameter: subsystem");
this.resource = resource;
this.subsystem = subsystem;
if (isTransitive())
provisionTo = Utils.findFirstSubsystemAcceptingDependenciesStartingFrom(subsystem);
else
provisionTo = subsystem;
}
public abstract void uninstall();
protected boolean isExplicit() {
// The operation is explicit if it was requested by a user, in which
// case the resource and subsystem are the same.
if (resource.equals(subsystem))
return true;
// The operation is explicit if it was requested by a scoped subsystem
// on a resource within the same region.
if (subsystem.isScoped()) {
if (Utils.isBundle(resource))
return subsystem.getRegion().contains(((BundleRevision)resource).getBundle());
// TODO This is insufficient. The unscoped subsystem could be a
// dependency in another region, which would make it implicit.
return !((BasicSubsystem)resource).isScoped();
}
return false;
}
protected boolean isTransitive() {
ProvisionResourceHeader header = subsystem.getDeploymentManifest().getProvisionResourceHeader();
if (header == null)
return false;
return header.contains(resource);
}
protected boolean isResourceUninstallable() {
int referenceCount = Activator.getInstance().getSubsystems().getSubsystemsReferencing(resource).size();
if (referenceCount == 0)
return true;
if (isExplicit()) {
logger.error("Explicitly uninstalling resource still has dependencies: {}", resource);
return true;
}
return false;
}
protected void removeConstituent() {
removeConstituent(subsystem, resource);
}
protected void removeReference() {
removeReference(subsystem, resource);
}
}
| 8,671 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ApplicationServiceModeller.java | /*
* 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.subsystem.core.internal;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.application.modelling.ExportedService;
import org.apache.aries.application.modelling.ImportedService;
import org.apache.aries.application.modelling.ModelledResourceManager;
import org.apache.aries.application.modelling.ModellerException;
import org.apache.aries.application.modelling.ParsedServiceElements;
import org.apache.aries.util.filesystem.IDirectory;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemException;
public class ApplicationServiceModeller implements ServiceModeller {
private final ModelledResourceManager manager;
public ApplicationServiceModeller(Object manager) {
this.manager = (ModelledResourceManager) manager;
}
@Override
public ServiceModel computeRequirementsAndCapabilities(Resource resource, IDirectory directory) throws SubsystemException {
try {
ServiceModelImpl model = new ServiceModelImpl();
ParsedServiceElements elements = manager.getServiceElements(directory);
for (ExportedService service : elements.getServices()) {
model.capabilities.add(new BasicCapability.Builder()
.namespace(ServiceNamespace.SERVICE_NAMESPACE)
.attribute(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE, new ArrayList<String>(service.getInterfaces()))
.attributes(service.getServiceProperties())
.resource(resource)
.build());
}
for (ImportedService service : elements.getReferences()) {
StringBuilder builder = new StringBuilder();
String serviceInterface = service.getInterface();
String filter = service.getFilter();
if (serviceInterface != null && filter != null) {
builder.append("(&");
}
if (serviceInterface != null) {
builder.append('(')
.append(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE)
.append('=')
.append(serviceInterface)
.append(')');
}
if (filter != null)
builder.append(filter);
if (serviceInterface != null && filter != null) {
builder.append(')');
}
if (builder.length() > 0) {
model.requirements.add(new BasicRequirement.Builder()
.namespace(ServiceNamespace.SERVICE_NAMESPACE)
.directive(Namespace.REQUIREMENT_FILTER_DIRECTIVE, builder.toString())
.directive(
Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE,
service.isOptional() ? Namespace.RESOLUTION_OPTIONAL : Namespace.RESOLUTION_MANDATORY)
.directive(
Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE,
service.isMultiple() ? Namespace.CARDINALITY_MULTIPLE : Namespace.CARDINALITY_SINGLE)
.resource(resource)
.build());
}
}
return model;
} catch (ModellerException e) {
throw new SubsystemException(e);
}
}
static class ServiceModelImpl implements ServiceModel {
final List<Requirement> requirements = new ArrayList<Requirement>();
final List<Capability> capabilities = new ArrayList<Capability>();
@Override
public List<Requirement> getServiceRequirements() {
return requirements;
}
@Override
public List<Capability> getServiceCapabilities() {
return capabilities;
}
}
}
| 8,672 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/RegionUpdater.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionDigraph;
import org.eclipse.equinox.region.RegionDigraph.FilteredRegion;
import org.eclipse.equinox.region.RegionFilter;
import org.eclipse.equinox.region.RegionFilterBuilder;
import org.osgi.framework.BundleException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Requirement;
public class RegionUpdater {
public static final int MAX_ATTEMPTS_DEFAULT = 10;
private final RegionDigraph digraph;
private final Region head;
private final Region tail;
public RegionUpdater(Region tail, Region head) {
if (head == null)
throw new NullPointerException();
this.tail = tail;
this.head = head;
digraph = tail.getRegionDigraph();
}
public void addRequirements(Collection<? extends Requirement> requirements) throws BundleException, InvalidSyntaxException {
for (int i = 0; i < MAX_ATTEMPTS_DEFAULT; i++) {
RegionDigraph copy = copyDigraph();
Region tail = copyTail(copy);
Region head = copyHead(copy);
Set<Long> bundleIds = copyBundleIds(tail);
Map<String, RegionFilterBuilder> heads = copyHeadRegions(tail, copy);
Map<String, RegionFilterBuilder> tails = copyTailRegions(tail, copy);
copy.removeRegion(tail);
tail = copy.createRegion(tail.getName());
addBundleIds(bundleIds, tail);
RegionFilterBuilder builder = heads.get(head.getName());
if (builder == null) {
// Something outside of the subsystems implementation has
// deleted the edge between the parent and child subsystems.
// See ARIES-1429.
throw new IllegalStateException(
new StringBuilder(tail.getName())
.append(" not connected to ")
.append(head.getName())
.toString());
}
if (requirements == null) {
heads.put(head.getName(), null);
}
else {
addRequirements(requirements, builder);
}
addHeadRegions(heads, tail, copy);
addTailRegions(tails, tail, copy);
// Replace the current digraph.
try {
digraph.replace(copy);
}
catch (BundleException e) {
// Something modified digraph since the copy was made.
if (i < MAX_ATTEMPTS_DEFAULT)
// There are more attempts to make.
continue;
// Number of attempts has been exhausted.
throw e;
}
// Success! No need to continue looping.
break;
}
}
private void addBundleIds(Set<Long> ids, Region region) throws BundleException {
for (Long id : ids)
region.addBundle(id);
}
private void addHeadRegions(Map<String, RegionFilterBuilder> heads, Region tail, RegionDigraph digraph) throws BundleException {
for (Map.Entry<String, RegionFilterBuilder> entry : heads.entrySet()) {
RegionFilterBuilder builder = entry.getValue();
if (builder == null) {
continue;
}
tail.connectRegion(digraph.getRegion(entry.getKey()), builder.build());
}
}
private void addTailRegions(Map<String, RegionFilterBuilder> tails, Region head, RegionDigraph digraph) throws BundleException {
for (Map.Entry<String, RegionFilterBuilder> entry : tails.entrySet())
digraph.getRegion(entry.getKey()).connectRegion(head, entry.getValue().build());
}
private void addRequirements(Collection<? extends Requirement> requirements, RegionFilterBuilder builder) throws InvalidSyntaxException {
for (Requirement requirement : requirements) {
String namespace = requirement.getNamespace();
// The osgi.service namespace requires translation.
if (ServiceNamespace.SERVICE_NAMESPACE.equals(namespace))
namespace = RegionFilter.VISIBLE_SERVICE_NAMESPACE;
String filter = requirement.getDirectives().get(IdentityNamespace.REQUIREMENT_FILTER_DIRECTIVE);
// A null filter means import everything from that namespace.
if (filter == null)
builder.allowAll(namespace);
else
builder.allow(namespace, filter);
}
}
private Set<Long> copyBundleIds(Region region) {
return region.getBundleIds();
}
private RegionDigraph copyDigraph() throws BundleException {
return digraph.copy();
}
private Region copyHead(RegionDigraph digraph) {
return digraph.getRegion(head.getName());
}
private Map<String, RegionFilterBuilder> copyHeadRegions(Region tail, RegionDigraph digraph) throws InvalidSyntaxException {
Map<String, RegionFilterBuilder> result = new HashMap<String, RegionFilterBuilder>();
for (FilteredRegion edge : tail.getEdges())
result.put(edge.getRegion().getName(), createRegionFilterBuilder(edge.getFilter().getSharingPolicy(), digraph));
return result;
}
private Region copyTail(RegionDigraph digraph) {
return digraph.getRegion(tail.getName());
}
private Map<String, RegionFilterBuilder> copyTailRegions(Region tail, RegionDigraph digraph) throws InvalidSyntaxException {
Map<String, RegionFilterBuilder> result = new HashMap<String, RegionFilterBuilder>();
for (Region head : digraph.getRegions()) {
if (head.equals(tail))
continue;
for (FilteredRegion edge : head.getEdges())
if (edge.getRegion().equals(tail))
result.put(head.getName(), createRegionFilterBuilder(edge.getFilter().getSharingPolicy(), digraph));
}
return result;
}
private RegionFilterBuilder createRegionFilterBuilder(Map<String, Collection<String>> sharingPolicy, RegionDigraph digraph) throws InvalidSyntaxException {
RegionFilterBuilder result = digraph.createRegionFilterBuilder();
for (Map.Entry<String, Collection<String>> entry : sharingPolicy.entrySet())
for (String filter : entry.getValue())
result.allow(entry.getKey(), filter);
return result;
}
}
| 8,673 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BundleResourceInstaller.java | /*
* 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.subsystem.core.internal;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.aries.util.io.IOUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
import org.osgi.framework.startlevel.BundleStartLevel;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.subsystem.SubsystemException;
public class BundleResourceInstaller extends ResourceInstaller {
/*
* Maps a BundleResource to a BundleRevision for the purpose of tracking
* any service requirements or capabilities. The instance is given to the
* Subsystems data structure as the constituent object.
*
* The resource variable is allowed to be null so this class can be used
* when removing constituents from the data structure; however, note that
* service capabilities and requirements will not be available.
*/
static class BundleConstituent implements BundleRevision {
private final Resource resource;
private final BundleRevision revision;
public BundleConstituent(Resource resource, BundleRevision revision) {
if (resource instanceof BundleRevision) {
try {
this.resource = new BundleRevisionResource((BundleRevision)resource);
}
catch (SubsystemException e) {
throw e;
}
catch (Exception e) {
throw new SubsystemException(e);
}
}
else
this.resource = resource;
this.revision = revision;
}
@Override
public List<Capability> getCapabilities(String namespace) {
List<Capability> result = new ArrayList<Capability>(revision.getCapabilities(namespace));
if (resource != null && (namespace == null || ServiceNamespace.SERVICE_NAMESPACE.equals(namespace)))
for (Capability capability : resource.getCapabilities(ServiceNamespace.SERVICE_NAMESPACE))
result.add(new BasicCapability.Builder()
.namespace(capability.getNamespace())
.attributes(capability.getAttributes())
.directives(capability.getDirectives())
// Use the BundleRevision as the resource so it can be identified as a
// runtime resource within the system repository.
.resource(revision)
.build());
return Collections.unmodifiableList(result);
}
@Override
public List<Requirement> getRequirements(String namespace) {
List<Requirement> result = new ArrayList<Requirement>(revision.getRequirements(namespace));
if (resource != null && (namespace == null || ServiceNamespace.SERVICE_NAMESPACE.equals(namespace)))
for (Requirement requiremnet : resource.getRequirements(ServiceNamespace.SERVICE_NAMESPACE))
result.add(new BasicRequirement.Builder()
.namespace(requiremnet.getNamespace())
.attributes(requiremnet.getAttributes())
.directives(requiremnet.getDirectives())
// Use the BundleRevision as the resource so it can be identified as a
// runtime resource within the system repository.
.resource(revision)
.build());
return Collections.unmodifiableList(result);
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof BundleConstituent))
return false;
BundleConstituent that = (BundleConstituent)o;
return revision.equals(that.revision);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + revision.hashCode();
return result;
}
@Override
public Bundle getBundle() {
return revision.getBundle();
}
public Resource getResource() {
return resource;
}
public BundleRevision getRevision() {
return revision;
}
@Override
public String getSymbolicName() {
return revision.getSymbolicName();
}
@Override
public Version getVersion() {
return revision.getVersion();
}
@Override
public List<BundleCapability> getDeclaredCapabilities(String namespace) {
return revision.getDeclaredCapabilities(namespace);
}
@Override
public List<BundleRequirement> getDeclaredRequirements(String namespace) {
return revision.getDeclaredRequirements(namespace);
}
@Override
public int getTypes() {
return revision.getTypes();
}
@Override
public BundleWiring getWiring() {
return revision.getWiring();
}
@Override
public String toString() {
return revision.toString();
}
}
public BundleResourceInstaller(Coordination coordination, Resource resource, BasicSubsystem subsystem) {
super(coordination, resource, subsystem);
}
public Resource install() {
BundleRevision revision;
if (resource instanceof BundleRevision) {
revision = (BundleRevision)resource;
}
else if (resource instanceof BundleRevisionResource) {
revision = ((BundleRevisionResource)resource).getRevision();
}
else {
try {
revision = installBundle();
}
catch (Exception e) {
throw new SubsystemException(e);
}
}
addReference(revision);
addConstituent(new BundleConstituent(resource, revision));
return revision;
}
private BundleRevision installBundle() throws Exception {
final Bundle bundle;
Method getContent = resource.getClass().getMethod("getContent");
getContent.setAccessible(true);
InputStream is = (InputStream)getContent.invoke(resource);
ThreadLocalSubsystem.set(provisionTo);
try {
bundle = provisionTo.getRegion().installBundleAtLocation(getLocation(), is);
}
finally {
ThreadLocalSubsystem.remove();
// Although Region.installBundle ultimately calls BundleContext.install,
// which closes the input stream, an exception may occur before this
// happens. Also, the Region API does not guarantee the stream will
// be closed.
IOUtils.close(is);
}
// Set the start level of all bundles managed (i.e. installed) by the
// subsystems implementation to 1 in case the framework's default bundle
// start level has been changed. Otherwise, start failures will occur
// if a subsystem is started at a lower start level than the default.
// Setting the start level does no harm since all managed bundles are
// started transiently anyway.
bundle.adapt(BundleStartLevel.class).setStartLevel(1);
return bundle.adapt(BundleRevision.class);
}
}
| 8,674 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/LockingStrategy.java | package org.apache.aries.subsystem.core.internal;
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 java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemException;
public class LockingStrategy {
private final int TRY_LOCK_TIME;
private final TimeUnit TRY_LOCK_TIME_UNIT = TimeUnit.SECONDS;
public LockingStrategy(String tryLockTime) {
int value = 600; // ten mins by default
if (tryLockTime != null) {
try {
value = Integer.parseInt(tryLockTime);
} catch (NumberFormatException e) {
// ignore, the default will be used
}
}
TRY_LOCK_TIME = value;
}
/*
* A mutual exclusion lock used when acquiring the state change locks of
* a collection of subsystems in order to prevent cycle deadlocks.
*/
private final ReentrantLock lock = new ReentrantLock();
/*
* Used when the state change lock of a subsystem cannot be acquired. All
* other state change locks are released while waiting. The condition is met
* whenever the state change lock of one or more subsystems is released.
*/
private final Condition condition = lock.newCondition();
/*
* Allow only one of the following operations to be executing at the same
* time.
*
* (1) Install
* (2) Install Dependencies
* (3) Uninstall
*
* Allow any number of the following operations to be executing at the same
* time.
*
* (1) Resolve
* (2) Start
* (3) Stop
*/
private final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
private final ThreadLocal<Map<Subsystem.State, Set<BasicSubsystem>>> local = new ThreadLocal<Map<Subsystem.State, Set<BasicSubsystem>>>() {
@Override
protected Map<Subsystem.State, Set<BasicSubsystem>> initialValue() {
return new HashMap<Subsystem.State, Set<BasicSubsystem>>();
}
};
public void lock() {
try {
if (!lock.tryLock(TRY_LOCK_TIME, TRY_LOCK_TIME_UNIT)) {
throw new SubsystemException("Unable to acquire the global mutual exclusion lock in time.");
}
}
catch (InterruptedException e) {
throw new SubsystemException(e);
}
}
public void unlock() {
lock.unlock();
}
public void lock(Collection<BasicSubsystem> subsystems) {
Collection<BasicSubsystem> locked = new ArrayList<BasicSubsystem>(subsystems.size());
try {
while (locked.size() < subsystems.size()) {
for (BasicSubsystem subsystem : subsystems) {
if (!subsystem.stateChangeLock().tryLock()) {
unlock(locked);
locked.clear();
if (!condition.await(TRY_LOCK_TIME, TimeUnit.SECONDS)) {
throw new SubsystemException("Unable to acquire the state change lock in time: " + subsystem);
}
break;
}
locked.add(subsystem);
}
}
}
catch (InterruptedException e) {
unlock(locked);
throw new SubsystemException(e);
}
}
public void unlock(Collection<BasicSubsystem> subsystems) {
for (BasicSubsystem subsystem : subsystems) {
subsystem.stateChangeLock().unlock();
}
signalAll();
}
private void signalAll() {
lock();
try {
condition.signalAll();
}
finally {
unlock();
}
}
public boolean set(Subsystem.State state, BasicSubsystem subsystem) {
Map<Subsystem.State, Set<BasicSubsystem>> map = local.get();
Set<BasicSubsystem> subsystems = map.get(state);
if (subsystems == null) {
subsystems = new HashSet<BasicSubsystem>();
map.put(state, subsystems);
local.set(map);
}
if (subsystems.contains(subsystem)) {
return false;
}
subsystems.add(subsystem);
return true;
}
public void unset(Subsystem.State state, BasicSubsystem subsystem) {
Map<Subsystem.State, Set<BasicSubsystem>> map = local.get();
Set<BasicSubsystem> subsystems = map.get(state);
if (subsystems != null) {
subsystems.remove(subsystem);
}
}
public void readLock() {
try {
if (!rwlock.readLock().tryLock(TRY_LOCK_TIME, TRY_LOCK_TIME_UNIT)) {
throw new SubsystemException("Unable to acquire the global read lock in time.");
}
}
catch (InterruptedException e) {
throw new SubsystemException(e);
}
}
public void readUnlock() {
rwlock.readLock().unlock();
}
public void writeLock() {
try {
if (!rwlock.writeLock().tryLock(TRY_LOCK_TIME, TRY_LOCK_TIME_UNIT)) {
throw new SubsystemException("Unable to acquire the global write lock in time.");
}
}
catch (InterruptedException e) {
throw new SubsystemException(e);
}
}
public void writeUnlock() {
rwlock.writeLock().unlock();
}
}
| 8,675 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/WovenClassListener.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.subsystem.core.internal;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.aries.subsystem.core.archive.DynamicImportPackageHeader;
import org.apache.aries.subsystem.core.archive.DynamicImportPackageRequirement;
import org.apache.aries.subsystem.core.internal.BundleResourceInstaller.BundleConstituent;
import org.apache.aries.subsystem.core.internal.StartAction.Restriction;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionDigraph.FilteredRegion;
import org.eclipse.equinox.region.RegionDigraphVisitor;
import org.eclipse.equinox.region.RegionFilter;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemException;
public class WovenClassListener implements org.osgi.framework.hooks.weaving.WovenClassListener {
private static class RegionUpdaterInfo {
private final Region head;
private final Collection<DynamicImportPackageRequirement> requirements;
private final Region tail;
public RegionUpdaterInfo(Region tail, Region head) {
this.tail = tail;
this.head = head;
requirements = new ArrayList<DynamicImportPackageRequirement>();
}
public Region head() {
return head;
}
public void requirement(DynamicImportPackageRequirement requirement) {
requirements.add(requirement);
}
public Collection<DynamicImportPackageRequirement> requirements() {
return requirements;
}
public Region tail() {
return tail;
}
}
private final BundleContext context;
private final Subsystems subsystems;
public WovenClassListener(BundleContext context, Subsystems subsystems) {
this.context = context;
this.subsystems = subsystems;
}
@Override
public void modified(WovenClass wovenClass) {
if (wovenClass.getState() != WovenClass.TRANSFORMED) {
// Dynamic package imports must be added when the woven class is in
// the transformed state in order to ensure the class will load once
// the defined state is reached.
return;
}
List<String> dynamicImports = wovenClass.getDynamicImports();
if (dynamicImports.isEmpty()) {
// Nothing to do if there are no dynamic imports.
return;
}
BundleWiring wiring = wovenClass.getBundleWiring();
Bundle bundle = wiring.getBundle();
BundleRevision revision = bundle.adapt(BundleRevision.class);
BundleConstituent constituent = new BundleConstituent(null, revision);
Collection<BasicSubsystem> basicSubsystems = subsystems.getSubsystemsByConstituent(constituent);
BasicSubsystem subsystem = basicSubsystems.iterator().next();
// Find the scoped subsystem in the region.
subsystem = scopedSubsystem(subsystem);
if (subsystem.getSubsystemId() == 0) {
// The root subsystem needs no sharing policy.
return;
}
if (EnumSet.of(Subsystem.State.INSTALLING, Subsystem.State.INSTALLED).contains(subsystem.getState())) {
// The scoped subsystem must be resolved before adding dynamic
// package imports to the sharing policy in order to minimize
// unpredictable wirings. Resolving the scoped subsystem will also
// resolve all of the unscoped subsystems in the region.
AccessController.doPrivileged(new StartAction(subsystem, subsystem, subsystem, Restriction.RESOLVE_ONLY));
}
Bundle systemBundle = context.getBundle(org.osgi.framework.Constants.SYSTEM_BUNDLE_LOCATION);
FrameworkWiring frameworkWiring = systemBundle.adapt(FrameworkWiring.class);
// The following map tracks all of the necessary updates as each dynamic
// import is processed. The key is the tail region of the connection
// whose filter needs updating.
Map<Region, RegionUpdaterInfo> updates = new HashMap<Region, RegionUpdaterInfo>();
for (String dynamicImport : dynamicImports) {
// For each dynamic import, collect the necessary update information.
DynamicImportPackageHeader header = new DynamicImportPackageHeader(dynamicImport);
List<DynamicImportPackageRequirement> requirements = header.toRequirements(revision);
for (DynamicImportPackageRequirement requirement : requirements) {
Collection<BundleCapability> providers = frameworkWiring.findProviders(requirement);
if (providers.isEmpty()) {
// If nothing provides a capability matching the dynamic
// import, no updates are made.
continue;
}
addSharingPolicyUpdates(requirement, subsystem, providers, updates);
}
}
// Now update each sharing policy only once.
for (RegionUpdaterInfo update : updates.values()) {
RegionUpdater updater = new RegionUpdater(update.tail(), update.head());
try {
updater.addRequirements(update.requirements());
}
catch (IllegalStateException e) {
// Something outside of the subsystems implementation has
// deleted the edge between the parent and child subsystems.
// Assume the dynamic import sharing policy is being handled
// elsewhere. See ARIES-1429.
}
catch (Exception e) {
throw new SubsystemException(e);
}
}
}
private void addSharingPolicyUpdates(
final DynamicImportPackageRequirement requirement,
final BasicSubsystem scopedSubsystem,
final Collection<BundleCapability> providers,
Map<Region, RegionUpdaterInfo> updates) {
final List<BasicSubsystem> subsystems = new ArrayList<BasicSubsystem>();
final Map<Region, BasicSubsystem> regionToSubsystem = new HashMap<Region, BasicSubsystem>();
regionToSubsystem(scopedSubsystem, regionToSubsystem);
scopedSubsystem.getRegion().visitSubgraph(new RegionDigraphVisitor() {
private final List<BasicSubsystem> visited = new ArrayList<BasicSubsystem>();
@Override
public void postEdgeTraverse(RegionFilter filter) {
// Nothing.
}
@Override
public boolean preEdgeTraverse(RegionFilter filter) {
return true;
}
@Override
public boolean visit(Region region) {
BasicSubsystem subsystem = regionToSubsystem.get(region);
if (subsystem == null || subsystem.isRoot()) {
// Don't mess with regions not created by the subsystem
// implementation. Also, the root subsystem never has a
// sharing policy.
return false;
}
if (!visited.isEmpty() && !subsystem.equals(scopedParent(visited.get(visited.size() - 1)))) {
// We're only interested in walking up the scoped parent tree.
return false;
}
visited.add(subsystem);
if (!requirement.getPackageName().contains("*")) {
for (BundleCapability provider : providers) {
BundleRevision br = provider.getResource();
if (region.contains(br.getBundle())) {
// The region contains a bundle providing a matching
// capability, and the dynamic import does not contain a
// wildcard. The requirement is therefore completely
// satisfied.
return false;
}
}
}
boolean allowed = false;
Set<FilteredRegion> filters = region.getEdges();
for (FilteredRegion filteredRegion : filters) {
RegionFilter filter = filteredRegion.getFilter();
if (filter.isAllowed(providers.iterator().next())) {
// The region already allows matching capabilities
// through so there is no need to update the sharing
// policy.
allowed = true;
break;
}
}
if (!allowed) {
// The subsystem region requires a sharing policy update.
subsystems.add(subsystem);
}
// Visit the next region.
return true;
}
});
// Collect the information for the necessary sharing policy updates.
for (BasicSubsystem subsystem : subsystems) {
Region tail = subsystem.getRegion();
Region head = scopedParent(subsystem).getRegion();
RegionUpdaterInfo info = updates.get(tail);
if (info == null) {
info = new RegionUpdaterInfo(tail, head);
updates.put(tail, info);
}
info.requirement(requirement);
}
}
private void regionToSubsystem(BasicSubsystem subsystem, Map<Region, BasicSubsystem> map) {
map.put(subsystem.getRegion(), subsystem);
subsystem = scopedParent(subsystem);
if (subsystem == null) {
return;
}
regionToSubsystem(subsystem, map);
}
private BasicSubsystem scopedParent(BasicSubsystem subsystem) {
Collection<Subsystem> parents = subsystem.getParents();
if (parents.isEmpty()) {
return null;
}
subsystem = (BasicSubsystem)parents.iterator().next();
return scopedSubsystem(subsystem);
}
private BasicSubsystem scopedSubsystem(BasicSubsystem subsystem) {
while (!subsystem.isScoped()) {
subsystem = (BasicSubsystem)subsystem.getParents().iterator().next();
}
return subsystem;
}
}
| 8,676 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemResourceInstaller.java | /*
* 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.subsystem.core.internal;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.aries.util.filesystem.FileSystem;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.coordinator.Participant;
import org.osgi.service.subsystem.Subsystem.State;
public class SubsystemResourceInstaller extends ResourceInstaller {
public SubsystemResourceInstaller(Coordination coordination, Resource resource, BasicSubsystem subsystem) {
super(coordination, resource, subsystem);
}
public Resource install() throws Exception {
if (resource instanceof BasicSubsystem)
return installAriesSubsystem((BasicSubsystem)resource);
else if (resource instanceof RawSubsystemResource)
return installRawSubsystemResource((RawSubsystemResource)resource);
else if (resource instanceof SubsystemResource)
return installSubsystemResource((SubsystemResource)resource);
else {
return installRepositoryContent(resource);
}
}
private void addChild(final BasicSubsystem child) {
// provisionTo will be null if the resource is an already installed
// dependency.
if (provisionTo == null)
return;
// Don't let a resource become a child of itself.
if (resource.equals(provisionTo))
return;
Activator.getInstance().getSubsystems().addChild(provisionTo, child, !isDependency());
}
private void addSubsystem(final BasicSubsystem subsystem) {
Activator.getInstance().getSubsystems().addSubsystem(subsystem);
}
private BasicSubsystem installAriesSubsystem(final BasicSubsystem subsystem) throws Exception {
addChild(subsystem);
addReference(subsystem);
addConstituent(subsystem);
addSubsystem(subsystem);
installRegionContextBundle(subsystem);
// This will emit the initial service event for INSTALLING subsystems.
// The first event for RESOLVED (i.e. persisted) subsystems is emitted later.
if (State.INSTALLING.equals(subsystem.getState())) {
Activator.getInstance().getSubsystemServiceRegistrar().register(subsystem, this.subsystem);
coordination.addParticipant(new Participant() {
@Override
public void ended(Coordination coordination) throws Exception {
// Nothing.
}
@Override
public void failed(Coordination coordination) throws Exception {
subsystem.setState(State.INSTALL_FAILED);
subsystem.uninstall();
}
});
}
Comparator<Resource> comparator = new InstallResourceComparator();
// Install dependencies first if appropriate...
if (!subsystem.isRoot() && Utils.isProvisionDependenciesInstall(subsystem)) {
new InstallDependencies().install(subsystem, this.subsystem, coordination);
}
// ...followed by content.
// Simulate installation of shared content so that necessary relationships are established.
for (Resource content : subsystem.getResource().getSharedContent()) {
ResourceInstaller.newInstance(coordination, content, subsystem).install();
}
// Now take care of the installable content.
if (State.INSTALLING.equals(subsystem.getState())) {
List<Resource> installableContent = new ArrayList<Resource>(subsystem.getResource().getInstallableContent());
Collections.sort(installableContent, comparator);
for (Resource content : installableContent)
ResourceInstaller.newInstance(coordination, content, subsystem).install();
}
// Only brand new subsystems should have acquired the INSTALLING state,
// in which case an INSTALLED event must be propagated.
if (State.INSTALLING.equals(subsystem.getState()) &&
Utils.isProvisionDependenciesInstall(subsystem)) {
subsystem.setState(State.INSTALLED);
}
else {
// This is a persisted subsystem in the RESOLVED state. Emit the first service event.
Activator.getInstance().getSubsystemServiceRegistrar().register(subsystem, this.subsystem);
}
return subsystem;
}
private BasicSubsystem installRawSubsystemResource(RawSubsystemResource resource) throws Exception {
SubsystemResource subsystemResource = new SubsystemResource(resource, provisionTo, coordination);
return installSubsystemResource(subsystemResource);
}
private void installRegionContextBundle(final BasicSubsystem subsystem) throws Exception {
if (!subsystem.isScoped())
return;
RegionContextBundleHelper.installRegionContextBundle(subsystem, coordination);
}
private BasicSubsystem installRepositoryContent(Resource resource) throws Exception {
Method method = resource.getClass().getMethod("getContent");
InputStream is = (InputStream)method.invoke(resource);
RawSubsystemResource rawSubsystemResource = new RawSubsystemResource(getLocation(), FileSystem.getFSRoot(is), subsystem);
return installRawSubsystemResource(rawSubsystemResource);
}
private BasicSubsystem installSubsystemResource(SubsystemResource resource) throws Exception {
BasicSubsystem subsystem = new BasicSubsystem(resource);
installAriesSubsystem(subsystem);
return subsystem;
}
}
| 8,677 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/Subsystems.java | /*
* 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.subsystem.core.internal;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.apache.aries.subsystem.core.internal.BundleResourceInstaller.BundleConstituent;
import org.apache.aries.util.io.IOUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemException;
public class Subsystems {
private BasicSubsystem root;
private volatile SubsystemGraph graph;
private final Map<Long, BasicSubsystem> idToSubsystem = new HashMap<Long, BasicSubsystem>();
private final Map<String, BasicSubsystem> locationToSubsystem = new HashMap<String, BasicSubsystem>();
private final ResourceReferences resourceReferences = new ResourceReferences();
private final Map<BasicSubsystem, Set<Resource>> subsystemToConstituents = new HashMap<BasicSubsystem, Set<Resource>>();
public void addChild(BasicSubsystem parent, BasicSubsystem child, boolean referenceCount) {
graph.add(parent, child);
child.addedParent(parent, referenceCount);
}
public void addConstituent(BasicSubsystem subsystem, Resource constituent, boolean referenced) {
synchronized (subsystemToConstituents) {
Set<Resource> constituents = subsystemToConstituents.get(subsystem);
if (constituents == null) {
constituents = new HashSet<Resource>();
subsystemToConstituents.put(subsystem, constituents);
}
constituents.add(constituent);
}
subsystem.addedConstituent(constituent, referenced);
}
public void addReference(BasicSubsystem subsystem, Resource resource) {
resourceReferences.addReference(subsystem, resource);
}
public void addSubsystem(BasicSubsystem subsystem) {
synchronized (idToSubsystem) {
synchronized (locationToSubsystem) {
addIdToSubsystem(subsystem);
addLocationToSubsystem(subsystem);
}
}
}
public Collection<Subsystem> getChildren(BasicSubsystem parent) {
return graph.getChildren(parent);
}
public Collection<Resource> getConstituents(BasicSubsystem subsystem) {
synchronized (subsystemToConstituents) {
Collection<Resource> result = subsystemToConstituents.get(subsystem);
if (result == null)
return Collections.emptyList();
return Collections.unmodifiableCollection(new ArrayList<Resource>(result));
}
}
public Collection<Subsystem> getParents(BasicSubsystem child) {
return graph.getParents(child);
}
public Collection<Resource> getResourcesReferencedBy(BasicSubsystem subsystem) {
return resourceReferences.getResources(subsystem);
}
public synchronized BasicSubsystem getRootSubsystem() {
if (root == null) {
File file = Activator.getInstance().getBundleContext().getDataFile("");
File[] fileArray = file.listFiles();
List<File> fileList = new ArrayList<File>(Arrays.asList(fileArray));
Collections.sort(fileList, new Comparator<File>() {
@Override
public int compare(File file1, File file2) {
String name1 = file1.getName();
String name2 = file2.getName();
return Long.valueOf(name1).compareTo(Long.valueOf(name2));
}
});
if (fileList.isEmpty()) {
// There are no persisted subsystems, including root.
SubsystemResource resource;
try {
resource = new SubsystemResource(file);
}
catch (SubsystemException e) {
throw e;
}
catch (Exception e) {
throw new SubsystemException(e);
}
Coordination coordination = Utils.createCoordination();
try {
root = new BasicSubsystem(resource);
// TODO This initialization is a bit brittle. The root subsystem
// must be gotten before anything else will be able to use the
// graph. At the very least, throw IllegalStateException where
// appropriate.
graph = new SubsystemGraph(root);
ResourceInstaller.newInstance(coordination, root, root).install();
populateRootSubsystem(root, coordination);
} catch (Exception e) {
coordination.fail(e);
} finally {
coordination.end();
}
}
else {
// There are persisted subsystems.
Coordination coordination = Utils.createCoordination();
Collection<BasicSubsystem> subsystems = new ArrayList<BasicSubsystem>(fileList.size());
try {
for (File f : fileList) {
BasicSubsystem s = new BasicSubsystem(f);
if (State.UNINSTALLED.equals(s.getState())) {
// left over cache, delete this
IOUtils.deleteRecursive(f);
} else {
subsystems.add(s);
addSubsystem(s);
}
}
root = getSubsystemById(0);
SubsystemIdentifier.setLastId(
Long.parseLong(
root.getDeploymentManifest().getHeaders().get(
DeploymentManifest.ARIESSUBSYSTEM_LASTID).getValue()));
graph = new SubsystemGraph(root);
ResourceInstaller.newInstance(coordination, root, root).install();
populateRootSubsystem(root, coordination);
} catch (Exception e) {
coordination.fail(e);
} finally {
coordination.end();
}
}
}
return root;
}
private void populateRootSubsystem(BasicSubsystem root, Coordination coordination) throws Exception {
// TODO Begin proof of concept.
// This is a proof of concept for initializing the relationships between the root subsystem and bundles
// that already existed in its region. Not sure this will be the final resting place. Plus, there are issues
// since this does not take into account the possibility of already existing bundles going away or new bundles
// being installed out of band while this initialization is taking place. Need a bundle event hook for that.
BundleContext context = Activator.getInstance().getBundleContext().getBundle(org.osgi.framework.Constants.SYSTEM_BUNDLE_LOCATION).getBundleContext();
for (Bundle bundle : context.getBundles()) {
BundleRevision revision = bundle.adapt(BundleRevision.class);
if (revision == null)
// The bundle has been uninstalled. Do not process.
continue;
if (!resourceReferences.getSubsystems(revision).isEmpty())
continue;
ResourceInstaller.newInstance(coordination, revision, root).install();
}
// TODO End proof of concept.
}
public BasicSubsystem getSubsystemById(long id) {
synchronized (idToSubsystem) {
return idToSubsystem.get(id);
}
}
public BasicSubsystem getSubsystemByLocation(String location) {
synchronized (locationToSubsystem) {
return locationToSubsystem.get(location);
}
}
public Collection<BasicSubsystem> getSubsystems() {
return new ArrayList<BasicSubsystem>(idToSubsystem.values());
}
// TODO Not very pretty. A quick fix.
public Object[] getSubsystemsByBundle(Bundle bundle) {
BundleRevision revision = null;
ArrayList<BasicSubsystem> result = new ArrayList<BasicSubsystem>();
synchronized (subsystemToConstituents) {
for (BasicSubsystem subsystem : subsystemToConstituents.keySet()) {
for (Resource constituent : getConstituents(subsystem)) {
if (constituent instanceof BundleConstituent &&
((BundleConstituent)constituent).getBundle() == bundle) {
result.add(subsystem);
revision = ((BundleConstituent)constituent).getRevision();
}
}
}
}
result.trimToSize();
if (revision == null)
return null;
return new Object[]{revision, result};
}
public Collection<BasicSubsystem> getSubsystemsByConstituent(Resource constituent) {
ArrayList<BasicSubsystem> result = new ArrayList<BasicSubsystem>();
synchronized (subsystemToConstituents) {
for (BasicSubsystem subsystem : subsystemToConstituents.keySet())
if (getConstituents(subsystem).contains(constituent))
result.add(subsystem);
}
result.trimToSize();
return result;
}
public Collection<BasicSubsystem> getSubsystemsReferencing(Resource resource) {
return resourceReferences.getSubsystems(resource);
}
public void removeChild(BasicSubsystem child) {
graph.remove(child);
}
public void removeChild(BasicSubsystem parent, BasicSubsystem child) {
graph.remove(parent, child);
}
public void removeConstituent(BasicSubsystem subsystem, Resource constituent) {
synchronized (subsystemToConstituents) {
Set<Resource> constituents = subsystemToConstituents.get(subsystem);
if (constituents != null) {
constituents.remove(constituent);
if (constituents.isEmpty())
subsystemToConstituents.remove(subsystem);
}
}
subsystem.removedContent(constituent);
}
public void removeReference(BasicSubsystem subsystem, Resource resource) {
resourceReferences.removeReference(subsystem, resource);
}
public void removeSubsystem(BasicSubsystem subsystem) {
synchronized (idToSubsystem) {
synchronized (locationToSubsystem) {
removeLocationToSubsystem(subsystem);
removeIdToSubsystem(subsystem);
}
}
}
private void addIdToSubsystem(BasicSubsystem subsystem) {
long id = subsystem.getSubsystemId();
idToSubsystem.put(id, subsystem);
}
private void addLocationToSubsystem(BasicSubsystem subsystem) {
String location = subsystem.getLocation();
locationToSubsystem.put(location, subsystem);
}
private void removeIdToSubsystem(BasicSubsystem subsystem) {
long id = subsystem.getSubsystemId();
idToSubsystem.remove(id);
}
private void removeLocationToSubsystem(BasicSubsystem subsystem) {
String location = subsystem.getLocation();
locationToSubsystem.remove(location);
}
}
| 8,678 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ServiceProvider.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
public interface ServiceProvider {
<C> C getService(Class<C> clazz);
<C> Collection<C> getServices(Class<C> clazz);
}
| 8,679 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResourceHelper.java | /*
* 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.subsystem.core.internal;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.aries.subsystem.core.archive.TypeAttribute;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.AbstractWiringNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Capability;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceHelper {
private static final Logger logger = LoggerFactory.getLogger(ResourceHelper.class);
public static boolean areEqual(Resource resource1, Resource resource2) {
if (getTypeAttribute(resource1).equals(getTypeAttribute(resource2))) {
if (getSymbolicNameAttribute(resource1).equals(getSymbolicNameAttribute(resource2))) {
if (getVersionAttribute(resource1).equals(getVersionAttribute(resource2))) {
return true;
}
}
}
return false;
}
public static String getContentAttribute(Resource resource) {
// TODO Add to constants.
return (String)getContentAttribute(resource, "osgi.content");
}
public static Object getContentAttribute(Resource resource, String name) {
// TODO Add to constants.
List<Capability> capabilities = resource.getCapabilities("osgi.content");
Capability capability = capabilities.get(0);
return capability.getAttributes().get(name);
}
public static Object getIdentityAttribute(Resource resource, String name) {
List<Capability> capabilities = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE);
Capability capability = capabilities.get(0);
return capability.getAttributes().get(name);
}
public static String getLocation(Resource resource) {
if (resource instanceof BundleResource)
return ((BundleResource)resource).getLocation();
if (resource instanceof BundleRevision)
return ((BundleRevision)resource).getBundle().getLocation();
if (resource instanceof BasicSubsystem)
return ((BasicSubsystem)resource).getLocation();
if (resource instanceof SubsystemResource)
return ((SubsystemResource)resource).getLocation();
if (resource instanceof RawSubsystemResource)
return ((RawSubsystemResource)resource).getLocation().getValue();
return getSymbolicNameAttribute(resource) + '@' + getVersionAttribute(resource);
}
public static Resource getResource(Requirement requirement, org.apache.aries.subsystem.core.repository.Repository repository) {
Map<Requirement, Collection<Capability>> map = repository.findProviders(Arrays.asList(requirement));
Collection<Capability> capabilities = map.get(requirement);
return capabilities == null ? null : capabilities.size() == 0 ? null : capabilities.iterator().next().getResource();
}
public static String getSymbolicNameAttribute(Resource resource) {
return (String)getIdentityAttribute(resource, IdentityNamespace.IDENTITY_NAMESPACE);
}
public static String getTypeAttribute(Resource resource) {
String result = (String)getIdentityAttribute(resource, IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE);
if (result == null)
result = TypeAttribute.DEFAULT_VALUE;
return result;
}
public static Version getVersionAttribute(Resource resource) {
Version result = (Version)getIdentityAttribute(resource, IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE);
if (result == null)
result = Version.emptyVersion;
return result;
}
public static boolean matches(Requirement requirement, Capability capability) {
if (requirement == null && capability == null)
return true;
else if (requirement == null || capability == null)
return false;
else if (!capability.getNamespace().equals(requirement.getNamespace()))
return false;
else {
Filter filter = null;
try {
if (requirement instanceof AbstractRequirement) {
filter = ((AbstractRequirement)requirement).getFilter();
}
else {
String filterStr = requirement.getDirectives().get(Constants.FILTER_DIRECTIVE);
if (filterStr != null) {
filter = FrameworkUtil.createFilter(filterStr);
}
}
}
catch (InvalidSyntaxException e) {
logger.debug("Requirement had invalid filter string: " + requirement, e);
return false;
}
if (filter != null && !filter.matches(capability.getAttributes())) {
return false;
}
}
return matchMandatoryDirective(requirement, capability);
}
private static final String ATTR = "((?:\\s*[^=><~()]\\s*)+)";
private static final String VALUE = "(?:\\\\\\\\|\\\\\\*|\\\\\\(|\\\\\\)|[^\\*()])+";
private static final String FINAL = "(?:" + VALUE + ")?";
private static final String STAR_VALUE = "(?:" + FINAL + "(?:\\*" + FINAL + ")*)";
private static final String ANY = "(?:\\*" + STAR_VALUE + ")";
private static final String INITIAL = FINAL;
private static final String SUBSTRING = "(?:" + ATTR + "=" + INITIAL + ANY + FINAL + ")";
private static final String PRESENT = "(?:" + ATTR + "=\\*)";
private static final String LESS_EQ = "(?:<=)";
private static final String GREATER_EQ = "(?:>=)";
private static final String APPROX = "(?:~=)";
private static final String EQUAL = "(?:=)";
private static final String FILTER_TYPE = "(?:" + EQUAL + "|" + APPROX + "|" + GREATER_EQ + "|" + LESS_EQ + ")";
private static final String SIMPLE = "(?:" + ATTR + FILTER_TYPE + VALUE + ")";
private static final String OPERATION = "(?:" + SIMPLE + "|" + PRESENT + "|" + SUBSTRING + ")";
private static final Pattern PATTERN = Pattern.compile(OPERATION);
private static boolean matchMandatoryDirective(Requirement requirement, Capability capability) {
if (!requirement.getNamespace().startsWith("osgi.wiring."))
// Mandatory directives only affect osgi.wiring.* namespaces.
return true;
String mandatoryDirective = capability.getDirectives().get(AbstractWiringNamespace.CAPABILITY_MANDATORY_DIRECTIVE);
if (mandatoryDirective == null)
// There are no mandatory attributes to check.
return true;
String filterDirective = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE);
if (filterDirective == null)
// The filter specifies none of the mandatory attributes.
return false;
Set<String> attributeNames = new HashSet<String>();
Matcher matcher = PATTERN.matcher(filterDirective);
// Collect all of the attribute names from the filter.
while (matcher.find())
attributeNames.add(matcher.group(1));
// Collect all of the mandatory attribute names.
for (String s : mandatoryDirective.split(","))
// Although all whitespace appears to be significant in a mandatory
// directive value according to OSGi syntax (since it must be quoted
// due to commas), we'll anticipate issues here and trim off
// whitespace around the commas.
if (!attributeNames.contains(s.trim()))
// The filter does not specify a mandatory attribute.
return false;
// The filter specifies all mandatory attributes.
return true;
}
}
| 8,680 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/PreferredProviderRepository.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.PreferredProviderHeader;
import org.apache.aries.subsystem.core.archive.PreferredProviderRequirement;
import org.apache.aries.subsystem.core.capabilityset.CapabilitySetRepository;
import org.apache.aries.subsystem.core.internal.BundleResourceInstaller.BundleConstituent;
import org.apache.aries.subsystem.core.repository.Repository;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
public class PreferredProviderRepository implements org.apache.aries.subsystem.core.repository.Repository {
private final CapabilitySetRepository repository;
private final SubsystemResource resource;
public PreferredProviderRepository(SubsystemResource resource) {
this.resource = resource;
repository = new CapabilitySetRepository();
PreferredProviderHeader header = resource.getSubsystemManifest().getPreferredProviderHeader();
if (header != null) {
Collection<PreferredProviderRequirement> requirements = header.toRequirements(resource);
for (PreferredProviderRequirement requirement : requirements) {
if (!addProviders(requirement, Activator.getInstance().getSystemRepository(), true)) {
if (!addProviders(requirement, resource.getLocalRepository(), false)) {
addProviders(requirement, new RepositoryServiceRepository(), false);
}
}
}
}
}
@Override
public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) {
return repository.findProviders(requirements);
}
private boolean addProviders(Requirement requirement, Repository repository, boolean checkValid) {
boolean result = false;
Map<Requirement, Collection<Capability>> map = repository.findProviders(Collections.singleton(requirement));
Collection<Capability> capabilities = map.get(requirement);
for (Capability capability : capabilities) {
if (checkValid ? isValid(capability) : true) {
this.repository.addResource(capability.getResource());
result = true;
}
}
return result;
}
/*
* This check is only done on capabilities provided by resources in the
* system repository. This currently includes only BasicSubsystem and
* BundleRevision.
*/
private boolean isValid(Capability capability) {
for (BasicSubsystem parent : resource.getParents()) {
Resource provider = capability.getResource();
if (provider instanceof BundleRevision) {
// To keep the optimization below, wrap bundle revisions with
// a bundle constituent so that the comparison works.
provider = new BundleConstituent(null, (BundleRevision)provider);
}
// Optimization from ARIES-1397. Perform a contains operation on the
// parent constituents rather than use ResourceHelper.
if (parent.getConstituents().contains(provider)) {
return true;
}
}
return false;
}
}
| 8,681 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/GetBundleContextAction.java | /*
* 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.subsystem.core.internal;
import java.security.PrivilegedAction;
import java.util.EnumSet;
import org.eclipse.equinox.region.Region;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.subsystem.Subsystem.State;
public class GetBundleContextAction implements PrivilegedAction<BundleContext> {
private final BasicSubsystem subsystem;
public GetBundleContextAction(BasicSubsystem subsystem) {
this.subsystem = subsystem;
}
@Override
public BundleContext run() {
if (EnumSet.of(State.INSTALL_FAILED, State.UNINSTALLED).contains(
subsystem.getState()))
return null;
BasicSubsystem subsystem = Utils.findScopedSubsystemInRegion(this.subsystem);
Region region = subsystem.getRegion();
String bundleName = RegionContextBundleHelper.SYMBOLICNAME_PREFIX + subsystem.getSubsystemId();
Bundle bundle = region.getBundle(bundleName, RegionContextBundleHelper.VERSION);
return bundle.getBundleContext();
}
}
| 8,682 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/LocalRepository.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.Map;
import org.apache.aries.subsystem.core.capabilityset.CapabilitySetRepository;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
public class LocalRepository implements org.apache.aries.subsystem.core.repository.Repository {
private final CapabilitySetRepository repository;
public LocalRepository(Collection<Resource> resources) {
repository = new CapabilitySetRepository();
addResources(resources);
}
@Override
public Map<Requirement, Collection<Capability>> findProviders(
Collection<? extends Requirement> requirements) {
return repository.findProviders(requirements);
}
private void addResources(Collection<Resource> resources) {
for (Resource resource : resources) {
addResource(resource);
}
}
private void addResource(Resource resource) {
repository.addResource(resource);
if (resource instanceof RawSubsystemResource) {
addResources(((RawSubsystemResource)resource).getResources());
}
}
}
| 8,683 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/AbstractAction.java | /*
* 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.subsystem.core.internal;
import java.security.PrivilegedAction;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractAction implements PrivilegedAction<Object> {
private static final Logger logger = LoggerFactory.getLogger(AbstractAction.class);
protected final boolean disableRootCheck;
protected final BasicSubsystem requestor;
protected final BasicSubsystem target;
public AbstractAction(BasicSubsystem requestor, BasicSubsystem target, boolean disableRootCheck) {
this.requestor = requestor;
this.target = target;
this.disableRootCheck = disableRootCheck;
}
protected void checkRoot() {
if (!disableRootCheck && target.isRoot())
throw new SubsystemException("This operation may not be performed on the root subsystem");
}
protected void checkValid() {
BasicSubsystem s = (BasicSubsystem)Activator.getInstance().getSubsystemServiceRegistrar().getSubsystemService(target);
if (s != target)
throw new IllegalStateException("Detected stale subsystem instance: " + s);
}
protected void waitForStateChange(State fromState) {
long then = System.currentTimeMillis() + 60000;
synchronized (target) {
if (logger.isDebugEnabled())
logger.debug("Request to wait for state change of subsystem {} from state {}", target.getSymbolicName(), target.getState());
while (target.getState().equals(fromState)) {
if (logger.isDebugEnabled())
logger.debug("{} equals {}", target.getState(), fromState);
// State change has not occurred.
long now = System.currentTimeMillis();
if (then <= now)
// Wait time has expired.
throw new SubsystemException("Operation timed out while waiting for the subsystem to change state from " + fromState);
try {
if (logger.isDebugEnabled())
logger.debug("Waiting for {} ms", then - now);
// Wait will never be called with zero or a negative
// argument due to previous check.
target.wait(then - now);
}
catch (InterruptedException e) {
// Reset the interrupted flag.
Thread.currentThread().interrupt();
throw new SubsystemException(e);
}
}
if (logger.isDebugEnabled())
logger.debug("Done waiting for subsystem {} in state {} to change from state {}", new Object[]{target.getSymbolicName(), target.getState(), fromState});
}
}
}
| 8,684 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/StartResourceComparator.java | /*
* 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.subsystem.core.internal;
import java.util.Comparator;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.osgi.resource.Resource;
public class StartResourceComparator implements Comparator<Resource> {
private final SubsystemContentHeader header;
public StartResourceComparator(SubsystemContentHeader header) {
this.header = header;
}
@Override
public int compare(Resource r1, Resource r2) {
Integer r1StartOrder = getStartOrder(r1);
Integer r2StartOrder = getStartOrder(r2);
return r1StartOrder.compareTo(r2StartOrder);
}
private Integer getStartOrder(Resource r) {
SubsystemContentHeader.Clause clause = header.getClause(r);
if (clause == null)
return -1;
return clause.getStartOrder();
}
}
| 8,685 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SystemRepository.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.subsystem.core.internal;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.aries.subsystem.AriesSubsystem;
import org.apache.aries.subsystem.core.capabilityset.CapabilitySetRepository;
import org.apache.aries.subsystem.core.repository.Repository;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.util.tracker.BundleTrackerCustomizer;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
public class SystemRepository
implements
Repository,
BundleTrackerCustomizer<AtomicReference<BundleRevisionResource>>,
ServiceTrackerCustomizer<AriesSubsystem, BasicSubsystem> {
private final BundleContext bundleContext;
private final CapabilitySetRepository repository;
public SystemRepository(BundleContext bundleContext) {
this.bundleContext = bundleContext;
repository = new CapabilitySetRepository();
}
@Override
public AtomicReference<BundleRevisionResource> addingBundle(Bundle bundle, BundleEvent event) {
// The state mask must guarantee this will only be called when the bundle is in the INSTALLED state.
BundleRevision revision = bundle.adapt(BundleRevision.class);
BundleRevisionResource resource = new BundleRevisionResource(revision);
if (ThreadLocalSubsystem.get() == null) {
// This is an explicitly installed bundle. It must be prevented
// from resolving as part of adding it to the repository. Searching
// for service requirements and capabilities will result in a call
// to findEntries which will cause the framework to attempt a
// resolution.
ThreadLocalBundleRevision.set(revision);
try {
repository.addResource(resource);
}
finally {
ThreadLocalBundleRevision.remove();
}
}
else {
// If this is a bundle being installed as part of a subsystem
// installation, it is already protected.
repository.addResource(resource);
}
return new AtomicReference<BundleRevisionResource>(resource);
}
@Override
public BasicSubsystem addingService(ServiceReference<AriesSubsystem> reference) {
// Intentionally letting the ClassCastException propagate. Everything received should be a BasicSubsystem.
BasicSubsystem subsystem = (BasicSubsystem)bundleContext.getService(reference);
repository.addResource(subsystem);
return subsystem;
}
@Override
public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) {
return repository.findProviders(requirements);
}
@Override
public void modifiedBundle(Bundle bundle, BundleEvent event, AtomicReference<BundleRevisionResource> object) {
if (BundleEvent.UPDATED == event.getType()) {
BundleRevision revision = bundle.adapt(BundleRevision.class);
BundleRevisionResource resource = new BundleRevisionResource(revision);
repository.removeResource(object.getAndSet(resource));
repository.addResource(resource);
}
}
@Override
public void modifiedService(ServiceReference<AriesSubsystem> reference, BasicSubsystem service) {
// Nothing.
}
@Override
public void removedBundle(Bundle bundle, BundleEvent event, AtomicReference<BundleRevisionResource> object) {
// The state mask must guarantee this will only be called when the bundle is in the UNINSTALLED state.
repository.removeResource(object.get());
}
@Override
public void removedService(ServiceReference<AriesSubsystem> reference, BasicSubsystem service) {
repository.removeResource(service);
}
}
| 8,686 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/CustomResourceUninstaller.java | /*
* 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.subsystem.core.internal;
import org.apache.aries.subsystem.ContentHandler;
import org.osgi.framework.ServiceReference;
import org.osgi.resource.Resource;
public class CustomResourceUninstaller extends ResourceUninstaller {
private final ServiceReference<ContentHandler> handlerRef;
private final String type;
public CustomResourceUninstaller(Resource resource, String type,
BasicSubsystem subsystem, ServiceReference<ContentHandler> handlerRef) {
super(resource, subsystem);
this.handlerRef = handlerRef;
this.type = type;
}
@Override
public void uninstall() {
removeReference();
try {
ContentHandler handler = subsystem.getBundleContext().getService(handlerRef);
if (handler != null) {
handler.uninstall(ResourceHelper.getSymbolicNameAttribute(resource), type, subsystem);
}
} finally {
subsystem.getBundleContext().ungetService(handlerRef);
}
}
}
| 8,687 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/Location.java | /*
* 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.subsystem.core.internal;
import static org.apache.aries.util.filesystem.IDirectoryFinder.IDIR_SCHEME;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.aries.util.filesystem.IDirectory;
import org.apache.aries.util.filesystem.IDirectoryFinder;
import org.osgi.framework.Version;
public class Location {
enum LocationType {
SUBSYSTEM("subsystem", "subsystem"), IDIRFINDER(IDIR_SCHEME, IDIR_SCHEME), URL("url", null), UNKNOWN("unknown", null);
final String toString;
final String scheme;
LocationType(String toString, String scheme) {this.toString = toString; this.scheme = scheme;}
@Override
public String toString() {return toString;}
};
private final LocationType type;
private final String value;
private final URI uri;
private final URL url;
private final SubsystemUri subsystemUri;
private final IllegalArgumentException subsystemUriException;
/*
* type, value, uri are always set to some non-null value, url and
* subsystemUri depend on the type.
*/
public Location(String location) throws MalformedURLException, URISyntaxException {
value = location;
URI locationUri = null;
try {
locationUri = new URI(location);
} catch ( URISyntaxException urise ) {
// ignore
}
if (locationUri == null) {
type = LocationType.UNKNOWN;
url = null;
uri = null;
subsystemUri = null;
subsystemUriException = null;
} else if (locationUri.isAbsolute()) { // i.e. looks like scheme:something
String scheme = locationUri.getScheme();
if (LocationType.SUBSYSTEM.scheme.equals(scheme)) {
type = LocationType.SUBSYSTEM;
SubsystemUri ssUri;
IllegalArgumentException ssUriException = null;
try {
ssUri = new SubsystemUri(location);
} catch (IllegalArgumentException ex) {
// In some cases the SubsystemUri can't be parsed by the SubsystemUri parser.
ssUri = null;
ssUriException = ex;
}
subsystemUri = ssUri;
subsystemUriException = ssUriException;
if (subsystemUri != null) {
url = subsystemUri.getURL(); // subsystem uris may contain a nested url.
uri = (url==null) ? null : url.toURI();
} else {
url = null;
uri = locationUri;
}
} else if (LocationType.IDIRFINDER.scheme.equals(scheme)) {
type = LocationType.IDIRFINDER;
subsystemUri = null;
subsystemUriException = null;
url = null;
uri = locationUri;
} else { // otherwise will only accept a url, (a url
type = LocationType.URL; // always has a scheme, so fine to have
subsystemUri = null; // this inside the 'if isAbsolute' block).
subsystemUriException = null;
URL localUrl = null;
try {
localUrl = locationUri.toURL();
} catch ( final MalformedURLException mue) {
// ignore
}
url = localUrl;
uri = locationUri;
}
} else {
type = LocationType.UNKNOWN;
url = null;
uri = null;
subsystemUri = null;
subsystemUriException = null;
}
}
public String getValue() {
return value;
}
public String getSymbolicName() {
if (subsystemUriException != null) {
throw subsystemUriException;
}
return (subsystemUri!=null) ? subsystemUri.getSymbolicName() : null;
}
public Version getVersion() {
if (subsystemUriException != null) {
throw subsystemUriException;
}
return (subsystemUri!=null) ? subsystemUri.getVersion() : null;
}
public IDirectory open() throws IOException, URISyntaxException {
switch (type) {
case IDIRFINDER :
return retrieveIDirectory();
case SUBSYSTEM : // drop through to share 'case url' code
case URL :
if ("file".equals(url.getProtocol()))
return FileSystem.getFSRoot(new File(uri));
else
return FileSystem.getFSRoot(url.openStream());
case UNKNOWN:
// Only try to create a URL with the location value here. If the
// location was just a string and an InputStream was provided, this
// method will never be called.
return FileSystem.getFSRoot(new URL(value).openStream());
default : // should never get here as switch should cover all types
throw new UnsupportedOperationException("cannot open location of type " + type);
}
}
/*
* Although the uri should contain information about the directory finder
* service to use to retrieve the directory, there are not expected to be
* many such services in use (typically one), so a simple list of all
* directory finders is maintained by the activator and we loop over them in
* turn until the desired directory is retrieved or there are no more finders
* left to call.
*/
private IDirectory retrieveIDirectory() throws IOException {
Collection<IDirectoryFinder> iDirectoryFinders = Activator.getInstance().getIDirectoryFinders();
for(IDirectoryFinder iDirectoryFinder : iDirectoryFinders) {
IDirectory directory = iDirectoryFinder.retrieveIDirectory(uri);
if (directory!=null)
return directory;
}
throw new IOException("cannot find IDirectory corresponding to id " + uri);
}
@Override
public String toString() {
return value;
}
}
| 8,688 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BundleRevisionResource.java | /*
* 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.subsystem.core.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
public class BundleRevisionResource implements Resource {
private final BundleRevision revision;
public BundleRevisionResource(BundleRevision revision) {
if (revision == null)
throw new NullPointerException();
this.revision = revision;
}
@Override
public List<Capability> getCapabilities(String namespace) {
if (ServiceNamespace.SERVICE_NAMESPACE.equals(namespace)) {
return Collections.unmodifiableList(getServiceCapabilities());
}
List<Capability> revisionCapabilities = revision.getCapabilities(namespace);
if (namespace == null) {
List<Capability> serviceCapabilities = getServiceCapabilities();
List<Capability> result = new ArrayList<Capability>(revisionCapabilities.size() + serviceCapabilities.size());
result.addAll(revisionCapabilities);
result.addAll(serviceCapabilities);
return Collections.unmodifiableList(result);
}
return revisionCapabilities;
}
@Override
public List<Requirement> getRequirements(String namespace) {
if (ServiceNamespace.SERVICE_NAMESPACE.equals(namespace)) {
return Collections.unmodifiableList(getServiceRequirements());
}
List<Requirement> revisionRequirements = revision.getRequirements(namespace);
if (namespace == null) {
List<Requirement> serviceRequirements = getServiceRequirements();
List<Requirement> result = new ArrayList<Requirement>(revisionRequirements.size() + serviceRequirements.size());
result.addAll(revisionRequirements);
result.addAll(serviceRequirements);
return Collections.unmodifiableList(result);
}
return revisionRequirements;
}
public BundleRevision getRevision() {
return revision;
}
private ServiceModeller.ServiceModel getModel() {
Activator activator = Activator.getInstance();
ServiceModeller modeller = activator.getServiceModeller();
if (modeller == null) {
return null;
}
ServiceModeller.ServiceModel model = modeller.computeRequirementsAndCapabilities(this,
new BundleDirectory(revision.getBundle()));
return model;
}
private boolean initialized;
private List<Capability> serviceCapabilities;
private List<Requirement> serviceRequirements;
private synchronized void computeServiceCapabilitiesAndRequirements() {
ServiceModeller.ServiceModel model = null;
boolean gotModel = false;
List<Capability> capabilities = revision.getCapabilities(ServiceNamespace.SERVICE_NAMESPACE);
// OSGi RFC 201 for R6: The presence of any Provide-Capability clauses
// in the osgi.service namespace overrides any service related
// capabilities that might have been found by other means.
if (capabilities.isEmpty()) {
model = getModel();
gotModel = true;
if (model != null) {
capabilities = model.getServiceCapabilities();
}
}
serviceCapabilities = capabilities;
List<Requirement> requirements = revision.getRequirements(ServiceNamespace.SERVICE_NAMESPACE);
// OSGi RFC 201 for R6: The presence of any Require-Capability clauses
// in the osgi.service namespace overrides any service related
// requirements that might have been found by other means.
if (requirements.isEmpty()) {
if (model == null && !gotModel) {
model = getModel();
}
if (model != null) {
requirements = model.getServiceRequirements();
}
}
serviceRequirements = requirements;
initialized = true;
}
private synchronized List<Capability> getServiceCapabilities() {
if (!initialized) {
computeServiceCapabilitiesAndRequirements();
}
return serviceCapabilities;
}
private synchronized List<Requirement> getServiceRequirements() {
if (!initialized) {
computeServiceCapabilitiesAndRequirements();
}
return serviceRequirements;
}
}
| 8,689 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/BasicRequirement.java | /*
* 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.subsystem.core.internal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
public class BasicRequirement extends AbstractRequirement {
public static class Builder {
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Map<String, String> directives = new HashMap<String, String>();
private Resource resource;
private String namespace;
public Builder attribute(String key, Object value) {
attributes.put(key, value);
return this;
}
public Builder attributes(Map<String, Object> values) {
attributes.putAll(values);
return this;
}
public BasicRequirement build() {
return new BasicRequirement(namespace, attributes, directives, resource);
}
public Builder directive(String key, String value) {
directives.put(key, value);
return this;
}
public Builder directives(Map<String, String> values) {
directives.putAll(values);
return this;
}
public Builder namespace(String value) {
namespace = value;
return this;
}
public Builder resource(Resource value) {
resource = value;
return this;
}
}
private final Map<String, Object> attributes;
private final Map<String, String> directives;
private final String namespace;
private final Resource resource;
public BasicRequirement(Requirement requirement, Resource resource) {
attributes = requirement.getAttributes();
directives = requirement.getDirectives();
namespace = requirement.getNamespace();
this.resource = resource;
}
public BasicRequirement(String namespace, String filter) throws InvalidSyntaxException {
this(namespace, FrameworkUtil.createFilter(filter));
}
public BasicRequirement(String namespace, Filter filter) {
if (namespace == null)
throw new NullPointerException("Missing required parameter: namespace");
attributes = Collections.emptyMap();
Map<String, String> directives = new HashMap<String, String>(1);
directives.put(Constants.FILTER_DIRECTIVE, filter.toString());
this.directives = Collections.unmodifiableMap(directives);
this.namespace = namespace;
resource = null;
}
private BasicRequirement(String namespace, Map<String, Object> attributes, Map<String, String> directives, Resource resource) {
if (namespace == null)
throw new NullPointerException();
this.namespace = namespace;
if (attributes == null)
this.attributes = Collections.emptyMap();
else
this.attributes = Collections.unmodifiableMap(new HashMap<String, Object>(attributes));
if (directives == null)
this.directives = Collections.emptyMap();
else
this.directives = Collections.unmodifiableMap(new HashMap<String, String>(directives));
if (resource == null)
throw new NullPointerException();
this.resource = resource;
}
@Override
public Map<String, Object> getAttributes() {
return attributes;
}
@Override
public Map<String, String> getDirectives() {
return directives;
}
@Override
public String getNamespace() {
return namespace;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,690 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemServiceRegistrar.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import org.apache.aries.subsystem.AriesSubsystem;
import org.eclipse.equinox.region.Region;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemServiceRegistrar {
private final BundleContext context;
private final Map<Subsystem, ServiceRegistration<?>> map = new HashMap<Subsystem, ServiceRegistration<?>>();
public SubsystemServiceRegistrar(BundleContext context) {
if (context == null)
throw new NullPointerException("Missing required parameter: context");
this.context = context;
}
public void addRegion(BasicSubsystem subsystem, Region region) {
ServiceRegistration<?> registration;
Dictionary<String, Object> properties;
synchronized (this) {
registration = map.get(subsystem);
if (registration == null)
throw new IllegalStateException("Subsystem '" + subsystem + "' is not registered");
Collection<String> currentRegions = (Collection<String>)registration.getReference().getProperty(Constants.SubsystemServicePropertyRegions);
String regionName = region.getName();
if (currentRegions.contains(regionName))
return;
Collection<String> newRegions = new HashSet<String>(currentRegions.size() + 1);
newRegions.addAll(currentRegions);
newRegions.add(regionName);
properties = properties(subsystem);
properties.put(Constants.SubsystemServicePropertyRegions, Collections.unmodifiableCollection(newRegions));
}
registration.setProperties(properties);
}
public synchronized Subsystem getSubsystemService(BasicSubsystem subsystem) {
ServiceRegistration<?> registration = map.get(subsystem);
if (registration == null)
return null;
return (Subsystem)Activator.getInstance().getBundleContext().getService(registration.getReference());
}
public void register(BasicSubsystem child, BasicSubsystem parent) {
Dictionary<String, Object> properties;
synchronized (this) {
if (map.containsKey(child))
return;
map.put(child, null);
properties = properties(child, parent);
}
ServiceRegistration<?> registration = null;
try {
registration = context.registerService(
new String[] {Subsystem.class.getName(), AriesSubsystem.class.getName()},
child, properties);
}
finally {
synchronized (this) {
if (registration == null)
map.remove(child);
else
map.put(child, registration);
}
}
}
public void removeRegion(BasicSubsystem subsystem, Region region) {
ServiceRegistration<?> registration;
Dictionary<String, Object> properties;
synchronized (this) {
registration = map.get(subsystem);
if (registration == null)
return;
Collection<String> regions = (Collection<String>)registration.getReference().getProperty(Constants.SubsystemServicePropertyRegions);
String regionName = region.getName();
if (regions == null || !regions.contains(regionName))
return;
regions = new HashSet<String>(regions);
regions.remove(regionName);
properties = properties(subsystem);
properties.put(Constants.SubsystemServicePropertyRegions, Collections.unmodifiableCollection(regions));
}
registration.setProperties(properties);
}
public void unregister(Subsystem subsystem) {
ServiceRegistration<?> registration;
synchronized (this) {
registration = map.remove(subsystem);
if (registration == null)
throw new IllegalStateException("Subsystem '" + subsystem + "' is not registered");
}
registration.unregister();
}
public void update(BasicSubsystem subsystem) {
ServiceRegistration<?> registration;
Dictionary<String, Object> properties;
synchronized (this) {
registration = map.get(subsystem);
if (registration == null)
throw new IllegalStateException("Subsystem '" + subsystem + "' is not registered");
properties = properties(subsystem, registration);
}
registration.setProperties(properties);
}
private Dictionary<String, Object> properties(BasicSubsystem subsystem) {
Dictionary<String, Object> result = new Hashtable<String, Object>();
result.put(SubsystemConstants.SUBSYSTEM_ID_PROPERTY, subsystem.getSubsystemId());
result.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME_PROPERTY, subsystem.getSymbolicName());
result.put(SubsystemConstants.SUBSYSTEM_VERSION_PROPERTY, subsystem.getVersion());
result.put(SubsystemConstants.SUBSYSTEM_TYPE_PROPERTY, subsystem.getType());
result.put(SubsystemConstants.SUBSYSTEM_STATE_PROPERTY, subsystem.getState());
result.put(Constants.SubsystemServicePropertyRegions, Collections.singleton(subsystem.getRegionName()));
return result;
}
private Dictionary<String, Object> properties(BasicSubsystem child, BasicSubsystem parent) {
Dictionary<String, Object> result = properties(child);
if (parent == null)
return result;
Collection<String> currentRegions = (Collection<String>)result.get(Constants.SubsystemServicePropertyRegions);
Collection<String> newRegions = new HashSet<String>(currentRegions.size() + 1);
newRegions.addAll(currentRegions);
newRegions.add(parent.getRegion().getName());
result.put(Constants.SubsystemServicePropertyRegions, Collections.unmodifiableCollection(newRegions));
return result;
}
private Dictionary<String, Object> properties(BasicSubsystem subsystem, ServiceRegistration<?> registration) {
Dictionary<String, Object> result = properties(subsystem);
Collection<String> regions = (Collection<String>)registration.getReference().getProperty(Constants.SubsystemServicePropertyRegions);
if (regions == null)
return result;
result.put(Constants.SubsystemServicePropertyRegions, regions);
return result;
}
}
| 8,691 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/CustomResources.java | /*
* 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.subsystem.core.internal;
import org.apache.aries.subsystem.ContentHandler;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
class CustomResources {
private CustomResources() {
// Only static methods
}
/**
* Find a custom content handler in the context of a given subsystem. Custom content handlers are
* services of type {@link ContentHandler} with the service registration property
* {@link ContentHandler#CONTENT_TYPE_PROPERTY} set to the type being handled.
* @param subsystem The subsystem that provides the context to look up the service.
* @param type The content type to find the handler for.
* @return The Service Reference for the Content Handler for the type or {@code null} if not found.
*/
static ServiceReference<ContentHandler> getCustomContentHandler(BasicSubsystem subsystem, String type) {
try {
for(ServiceReference<ContentHandler> ref :
subsystem.getBundleContext().getServiceReferences(ContentHandler.class,
"(" + ContentHandler.CONTENT_TYPE_PROPERTY + "=" + type + ")")) {
return ref;
}
return null;
} catch (InvalidSyntaxException e) {
throw new RuntimeException(e);
}
}
}
| 8,692 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/DependencyCalculator.java | /*
* 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.subsystem.core.internal;
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.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.aries.subsystem.core.capabilityset.CapabilitySetRepository;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.ExecutionEnvironmentNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.NativeNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.resource.Wire;
import org.osgi.resource.Wiring;
import org.osgi.service.resolver.HostedCapability;
import org.osgi.service.resolver.ResolutionException;
import org.osgi.service.resolver.Resolver;
public class DependencyCalculator {
private static class ResolveContext extends
org.osgi.service.resolver.ResolveContext {
private final CapabilitySetRepository repository = new CapabilitySetRepository();
private final Collection<Resource> resources;
public ResolveContext(Collection<Resource> resources) {
this.resources = resources;
for (Resource resource : resources) {
repository.addResource(resource);
}
}
@Override
public List<Capability> findProviders(Requirement requirement) {
String namespace = requirement.getNamespace();
// never check local resources for osgi.ee or osgi.native capabilities
if (ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE.equals(namespace)
|| NativeNamespace.NATIVE_NAMESPACE.equals(namespace)) {
return Collections.<Capability>singletonList(new MissingCapability(requirement));
}
Map<Requirement, Collection<Capability>> map = repository.findProviders(Collections.singleton(requirement));
Collection<Capability> capabilities = map.get(requirement);
if (!capabilities.isEmpty()) {
return new ArrayList<Capability>(capabilities);
}
return Collections.<Capability>singletonList(new MissingCapability(requirement));
}
@Override
public boolean isEffective(Requirement requirement) {
return true;
}
@Override
public Collection<Resource> getMandatoryResources() {
return resources;
}
@Override
public Map<Resource, Wiring> getWirings() {
return Collections.emptyMap();
}
@Override
public int insertHostedCapability(List<Capability> capabilities,
HostedCapability hostedCapability) {
int sz = capabilities.size();
capabilities.add(sz, hostedCapability);
return sz;
}
}
static class MissingCapability extends AbstractCapability {
private static class Resource implements org.osgi.resource.Resource {
public static final Resource INSTANCE = new Resource();
private final Capability identity;
public Resource() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put(IdentityNamespace.IDENTITY_NAMESPACE, org.apache.aries.subsystem.core.internal.Constants.ResourceTypeSynthesized);
attributes.put(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, org.apache.aries.subsystem.core.internal.Constants.ResourceTypeSynthesized);
identity = new BasicCapability(IdentityNamespace.IDENTITY_NAMESPACE, attributes, null, this);
}
@Override
public List<Capability> getCapabilities(String namespace) {
return Collections.singletonList(identity);
}
@Override
public List<Requirement> getRequirements(String namespace) {
return Collections.emptyList();
}
}
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Requirement requirement;
public MissingCapability(Requirement requirement) {
this.requirement = requirement;
initializeAttributes();
}
@Override
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
@Override
public Map<String, String> getDirectives() {
return Collections.emptyMap();
}
@Override
public String getNamespace() {
return requirement.getNamespace();
}
@Override
public Resource getResource() {
return Resource.INSTANCE;
}
private void initializeAttributes() {
String filter = requirement.getDirectives().get(Constants.FILTER_DIRECTIVE);
if (filter == null)
return;
Pattern pattern = Pattern.compile("\\(([^<>~(=]+)(?:=|<=|>=|~=)([^)]+)\\)");
Matcher matcher = pattern.matcher(filter);
while (matcher.find())
attributes.put(matcher.group(1), matcher.group(2));
}
}
private final ResolveContext context;
public DependencyCalculator(Collection<Resource> resources) {
context = new ResolveContext(resources);
}
public List<Requirement> calculateDependencies() throws ResolutionException {
ArrayList<Requirement> result = new ArrayList<Requirement>();
Resolver resolver = Activator.getInstance().getResolver();
Map<Resource, List<Wire>> resolution = resolver.resolve(context);
for (List<Wire> wires : resolution.values())
for (Wire wire : wires)
if (wire.getCapability() instanceof MissingCapability)
result.add(wire.getRequirement());
result.trimToSize();
return result;
}
}
| 8,693 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/TranslationFile.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.subsystem.core.internal;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class TranslationFile {
private static String normalizeName(String name) {
int index = name.lastIndexOf('/');
if (index == -1)
return name;
return name.substring(index + 1);
}
private final String name;
private final Properties properties;
public TranslationFile(String name, Properties properties) {
if (name == null || properties == null)
throw new NullPointerException();
if (name.isEmpty())
throw new IllegalArgumentException();
this.name = normalizeName(name);
this.properties = properties;
}
public void write(File directory) throws IOException {
FileOutputStream fos = new FileOutputStream(new File(directory, name));
try {
properties.store(fos, null);
}
finally {
fos.close();
}
}
}
| 8,694 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemIdentifier.java | /*
* 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.subsystem.core.internal;
public class SubsystemIdentifier {
private static long lastId;
synchronized static long getLastId() {
return lastId;
}
synchronized static long getNextId() {
if (Long.MAX_VALUE == lastId)
throw new IllegalStateException("The next subsystem ID would exceed Long.MAX_VALUE: " + lastId);
// First ID will be 1.
return ++lastId;
}
synchronized static void setLastId(long id) {
lastId = id;
}
}
| 8,695 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/InstallResourceComparator.java | /*
* 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.subsystem.core.internal;
import java.util.Comparator;
import java.util.List;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Resource;
public class InstallResourceComparator implements Comparator<Resource> {
@Override
public int compare(Resource r1, Resource r2) {
String r1type = getResourceType(r1);
String r2type = getResourceType(r2);
if (r1type.equals(r2type))
return 0;
if (r1type.startsWith("osgi.subsystem"))
return 1;
return -1;
}
private String getResourceType(Resource r) {
List<Capability> cl = r.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE);
Capability c = cl.get(0);
Object o = c.getAttributes().get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE);
return String.valueOf(o);
}
}
| 8,696 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SecurityManager.java | /*
* 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.subsystem.core.internal;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemPermission;
public class SecurityManager {
public static void checkContextPermission(Subsystem subsystem) {
checkPermission(new SubsystemPermission(subsystem, SubsystemPermission.CONTEXT));
}
public static void checkExecutePermission(Subsystem subsystem) {
checkPermission(new SubsystemPermission(subsystem, SubsystemPermission.EXECUTE));
}
public static void checkLifecyclePermission(Subsystem subsystem) {
checkPermission(new SubsystemPermission(subsystem, SubsystemPermission.LIFECYCLE));
}
public static void checkMetadataPermission(Subsystem subsystem) {
checkPermission(new SubsystemPermission(subsystem, SubsystemPermission.METADATA));
}
public static void checkPermission(SubsystemPermission permission) {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm == null)
return;
sm.checkPermission(permission);
}
}
| 8,697 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/SubsystemResolverHookFactory.java | /*
* 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.subsystem.core.internal;
import java.util.Collection;
import org.osgi.framework.hooks.resolver.ResolverHook;
import org.osgi.framework.hooks.resolver.ResolverHookFactory;
import org.osgi.framework.wiring.BundleRevision;
public class SubsystemResolverHookFactory implements ResolverHookFactory {
private final Subsystems subsystems;
public SubsystemResolverHookFactory(Subsystems subsystems) {
if (subsystems == null)
throw new NullPointerException("Missing required parameter: subsystems");
this.subsystems = subsystems;
}
public ResolverHook begin(Collection<BundleRevision> triggers) {
return new SubsystemResolverHook(subsystems);
}
}
| 8,698 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/Constants.java | /*
* 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.subsystem.core.internal;
import org.osgi.framework.namespace.IdentityNamespace;
public class Constants {
public static final String AriesSubsystemOriginalContent = "AriesSubsystem-OriginalContent";
public static final String BundleSymbolicName = org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME;
public static final String BundleVersion = org.osgi.framework.Constants.BUNDLE_VERSION;
public static final String RegionContextBundleSymbolicNamePrefix = "org.osgi.service.subsystem.region.context.";
public static final String ResourceTypeBundle = IdentityNamespace.TYPE_BUNDLE;
public static final String ResourceTypeFragment = IdentityNamespace.TYPE_FRAGMENT;
public static final String ResourceTypeSynthesized = "org.apache.aries.subsystem.resource.synthesized";
public static final String SubsystemServicePropertyRegions = "org.apache.aries.subsystem.service.regions";
private Constants() {}
}
| 8,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.