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/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/ServiceReferenceMetadataImpl.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.blueprint.reflect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
import org.osgi.framework.BundleContext;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* Implementation of ServiceReferenceMetadata
*
* @version $Rev$, $Date$
*/
public abstract class ServiceReferenceMetadataImpl extends ComponentMetadataImpl implements MutableServiceReferenceMetadata {
protected int availability;
protected String interfaceName;
protected String componentName;
protected String filter;
protected Collection<ReferenceListener> referenceListeners;
protected int proxyMethod;
protected Class runtimeInterface;
protected BundleContext bundleContext;
protected ValueMetadata extendedFilter;
public ServiceReferenceMetadataImpl() {
}
public ServiceReferenceMetadataImpl(ServiceReferenceMetadata source) {
super(source);
this.availability = source.getAvailability();
this.interfaceName = source.getInterface();
this.componentName = source.getComponentName();
this.filter = source.getFilter();
for (ReferenceListener listener : source.getReferenceListeners()) {
addServiceListener(new ReferenceListenerImpl(listener));
}
}
public int getAvailability() {
return availability;
}
public void setAvailability(int availability) {
this.availability = availability;
}
public String getInterface() {
return interfaceName;
}
public void setInterface(String interfaceName) {
this.interfaceName = interfaceName;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public Collection<ReferenceListener> getReferenceListeners() {
if (this.referenceListeners == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableCollection(this.referenceListeners);
}
}
public void setReferenceListeners(Collection<ReferenceListener> listeners) {
this.referenceListeners = listeners != null ? new ArrayList<ReferenceListener>(listeners) : null;
}
public void addServiceListener(ReferenceListener bindingListenerMetadata) {
if (this.referenceListeners == null) {
this.referenceListeners = new ArrayList<ReferenceListener>();
}
this.referenceListeners.add(bindingListenerMetadata);
}
public ReferenceListener addServiceListener(Target listenerComponent, String bindMethodName, String unbindMethodName) {
ReferenceListener listener = new ReferenceListenerImpl(listenerComponent, bindMethodName, unbindMethodName);
addServiceListener(listener);
return listener;
}
public void removeReferenceListener(ReferenceListener listener) {
if (this.referenceListeners != null) {
this.referenceListeners.remove(listener);
}
}
public int getProxyMethod() {
return proxyMethod;
}
public void setProxyMethod(int proxyMethod) {
this.proxyMethod = proxyMethod;
}
public Class getRuntimeInterface() {
return runtimeInterface;
}
public void setRuntimeInterface(Class runtimeInterface) {
this.runtimeInterface = runtimeInterface;
}
public BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleContext(BundleContext ctx) {
this.bundleContext = ctx;
}
public ValueMetadata getExtendedFilter() {
return extendedFilter;
}
public void setExtendedFilter(ValueMetadata extendedFilter) {
this.extendedFilter = extendedFilter;
}
}
| 9,600 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/ReferenceListenerImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.mutable.MutableReferenceListener;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.Target;
/**
* Implementation of Listener
*
* @version $Rev$, $Date$
*/
public class ReferenceListenerImpl implements MutableReferenceListener {
private Target listenerComponent;
private String bindMethod;
private String unbindMethod;
public ReferenceListenerImpl() {
}
public ReferenceListenerImpl(Target listenerComponent, String bindMethod, String unbindMethod) {
this.listenerComponent = listenerComponent;
this.bindMethod = bindMethod;
this.unbindMethod = unbindMethod;
}
public ReferenceListenerImpl(ReferenceListener source) {
this.listenerComponent = MetadataUtil.cloneTarget(source.getListenerComponent());
this.bindMethod = source.getBindMethod();
this.unbindMethod = source.getUnbindMethod();
}
public Target getListenerComponent() {
return this.listenerComponent;
}
public void setListenerComponent(Target listenerComponent) {
this.listenerComponent = listenerComponent;
}
public String getBindMethod() {
return this.bindMethod;
}
public void setBindMethod(String bindMethodName) {
this.bindMethod = bindMethodName;
}
public String getUnbindMethod() {
return this.unbindMethod;
}
public void setUnbindMethod(String unbindMethodName) {
this.unbindMethod = unbindMethodName;
}
@Override
public String toString() {
return "Listener[" +
"listenerComponent=" + listenerComponent +
", bindMethodName='" + bindMethod + '\'' +
", unbindMethodName='" + unbindMethod + '\'' +
']';
}
}
| 9,601 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/RefMetadataImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.mutable.MutableRefMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
/**
* Implementation of RefMetadata
*
* @version $Rev$, $Date$
*/
public class RefMetadataImpl implements MutableRefMetadata {
protected String componentId;
public RefMetadataImpl() {
}
public RefMetadataImpl(String componentId) {
this.componentId = componentId;
}
public RefMetadataImpl(RefMetadata source) {
componentId = source.getComponentId();
}
public String getComponentId() {
return componentId;
}
public void setComponentId(String componentId) {
this.componentId = componentId;
}
@Override
public String toString() {
return "RefMetadata[" +
"componentId='" + componentId + '\'' +
']';
}
}
| 9,602 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/ReferenceListMetadataImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.mutable.MutableReferenceListMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
/**
* Implementation of RefCollectionMetadata
*
* @version $Rev$, $Date$
*/
public class ReferenceListMetadataImpl extends ServiceReferenceMetadataImpl implements MutableReferenceListMetadata {
private int memberType = USE_SERVICE_OBJECT;
public ReferenceListMetadataImpl() {
}
public ReferenceListMetadataImpl(ReferenceListMetadata source) {
super(source);
memberType = source.getMemberType();
}
public int getMemberType() {
return memberType;
}
public void setMemberType(int memberType) {
this.memberType = memberType;
}
@Override
public String toString() {
return "RefCollectionMetadata[" +
"id='" + id + '\'' +
", activation=" + activation +
", dependsOn=" + dependsOn +
", availability=" + availability +
", interface='" + interfaceName + '\'' +
", componentName='" + componentName + '\'' +
", filter='" + filter + '\'' +
", referenceListeners=" + referenceListeners +
", memberType=" + memberType +
']';
}
}
| 9,603 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/CollectionMetadataImpl.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.blueprint.reflect;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.aries.blueprint.mutable.MutableCollectionMetadata;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
/**
* Implementation of CollectionMetadata
*
* @version $Rev$, $Date$
*/
public class CollectionMetadataImpl implements MutableCollectionMetadata {
private Class collectionClass;
private String valueType;
private List<Metadata> values;
public CollectionMetadataImpl() {
}
public CollectionMetadataImpl(Class collectionClass, String valueType, List<Metadata> values) {
this.collectionClass = collectionClass;
this.valueType = valueType;
this.values = values;
}
public CollectionMetadataImpl(CollectionMetadata source) {
this.collectionClass = source.getCollectionClass();
this.valueType = source.getValueType();
for (Metadata value : source.getValues()) {
addValue(MetadataUtil.cloneMetadata(value));
}
}
public Class getCollectionClass() {
return collectionClass;
}
public void setCollectionClass(Class collectionClass) {
this.collectionClass = collectionClass;
}
public String getValueType() {
return valueType;
}
public void setValueType(String valueType) {
this.valueType = valueType;
}
public List<Metadata> getValues() {
if (this.values == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(this.values);
}
}
public void setValues(List<Metadata> values) {
this.values = values != null ? new ArrayList<Metadata>(values) : null;
}
public void addValue(Metadata value) {
if (this.values == null) {
this.values = new ArrayList<Metadata>();
}
this.values.add(value);
}
public void removeValue(Metadata value) {
if (this.values != null) {
this.values.remove(value);
}
}
@Override
public String toString() {
return "CollectionMetadata[" +
"collectionClass=" + collectionClass +
", valueType='" + valueType + '\'' +
", values=" + values +
']';
}
}
| 9,604 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/BeanMetadataImpl.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.blueprint.reflect;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.aries.blueprint.ExtendedBeanMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.Target;
/**
* Implementation of BeanMetadata
*
* @version $Rev$, $Date$
*/
public class BeanMetadataImpl extends ComponentMetadataImpl implements MutableBeanMetadata {
private String className;
private String initMethod;
private String destroyMethod;
private List<BeanArgument> arguments;
private List<BeanProperty> properties;
private int initialization;
private String factoryMethod;
private Target factoryComponent;
private QName scope;
private Class runtimeClass;
private boolean processor;
private boolean fieldInjection;
private boolean rawConversion;
private boolean nonStandardSetters;
public BeanMetadataImpl() {
this.fieldInjection = false;
}
public BeanMetadataImpl(BeanMetadata source) {
super(source);
this.className = source.getClassName();
this.initMethod = source.getInitMethod();
this.destroyMethod = source.getDestroyMethod();
for (BeanArgument argument : source.getArguments()) {
addArgument(new BeanArgumentImpl(argument));
}
for (BeanProperty property : source.getProperties()) {
addProperty(new BeanPropertyImpl(property));
}
this.initialization = source.getActivation();
this.factoryMethod = source.getFactoryMethod();
this.factoryComponent = MetadataUtil.cloneTarget(source.getFactoryComponent());
this.scope = source.getScope() != null ? QName.valueOf(source.getScope()) : null;
this.dependsOn = new ArrayList<String>(source.getDependsOn());
if (source instanceof ExtendedBeanMetadata) {
this.runtimeClass = ((ExtendedBeanMetadata) source).getRuntimeClass();
this.fieldInjection = ((ExtendedBeanMetadata) source).getFieldInjection();
this.rawConversion = ((ExtendedBeanMetadata) source).getRawConversion();
this.nonStandardSetters = ((ExtendedBeanMetadata) source).getNonStandardSetters();
} else {
this.fieldInjection = false;
this.rawConversion = false;
this.nonStandardSetters = false;
}
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getInitMethod() {
return initMethod;
}
public void setInitMethod(String initMethodName) {
this.initMethod = initMethodName;
}
public String getDestroyMethod() {
return destroyMethod;
}
public void setDestroyMethod(String destroyMethodName) {
this.destroyMethod = destroyMethodName;
}
public List<BeanArgument> getArguments() {
if (this.arguments == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(this.arguments);
}
}
public void setArguments(List<BeanArgument> arguments) {
this.arguments = arguments != null ? new ArrayList<BeanArgument>(arguments) : null;
}
public void addArgument(BeanArgument argument) {
if (this.arguments == null) {
this.arguments = new ArrayList<BeanArgument>();
}
this.arguments.add(argument);
}
public BeanArgument addArgument(Metadata value, String valueType, int index) {
BeanArgument arg = new BeanArgumentImpl(value, valueType, index);
addArgument(arg);
return arg;
}
public void removeArgument(BeanArgument argument) {
if (this.arguments != null) {
this.arguments.remove(argument);
}
}
public List<BeanProperty> getProperties() {
if (this.properties == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(this.properties);
}
}
public void setProperties(List<BeanProperty> properties) {
this.properties = properties != null ? new ArrayList<BeanProperty>(properties) : null;
}
public void addProperty(BeanProperty property) {
if (this.properties == null) {
this.properties = new ArrayList<BeanProperty>();
}
this.properties.add(property);
}
public BeanProperty addProperty(String name, Metadata value) {
BeanProperty prop = new BeanPropertyImpl(name, value);
addProperty(prop);
return prop;
}
public void removeProperty(BeanProperty property) {
if (this.properties != null) {
this.properties.remove(property);
}
}
public String getFactoryMethod() {
return this.factoryMethod;
}
public void setFactoryMethod(String factoryMethodName) {
this.factoryMethod = factoryMethodName;
}
public Target getFactoryComponent() {
return this.factoryComponent;
}
public void setFactoryComponent(Target factoryComponent) {
this.factoryComponent = factoryComponent;
}
public String getScope() {
return this.scope != null ? this.scope.toString() : null;
}
public void setScope(String scope) {
this.scope = scope != null ? QName.valueOf(scope) : null;
}
public Class getRuntimeClass() {
return this.runtimeClass;
}
public void setRuntimeClass(Class runtimeClass) {
this.runtimeClass = runtimeClass;
}
public boolean isProcessor() {
return processor;
}
public void setProcessor(boolean processor) {
this.processor = processor;
}
public boolean getFieldInjection() {
return fieldInjection;
}
public void setFieldInjection(boolean fieldInjection) {
this.fieldInjection = fieldInjection;
}
public boolean getRawConversion() {
return rawConversion;
}
public void setRawConversion(boolean rawConversion) {
this.rawConversion = rawConversion;
}
public boolean getNonStandardSetters() {
return nonStandardSetters;
}
@Override
public void setNonStandardSetters(boolean nonStandardSetters) {
this.nonStandardSetters = nonStandardSetters;
}
@Override
public String toString() {
return "BeanMetadata[" +
"id='" + id + '\'' +
", initialization=" + initialization +
", dependsOn=" + dependsOn +
", className='" + className + '\'' +
", initMethodName='" + initMethod + '\'' +
", destroyMethodName='" + destroyMethod + '\'' +
", arguments=" + arguments +
", properties=" + properties +
", factoryMethodName='" + factoryMethod + '\'' +
", factoryComponent=" + factoryComponent +
", scope='" + scope + '\'' +
", runtimeClass=" + runtimeClass +
", fieldInjection=" + fieldInjection +
']';
}
}
| 9,605 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/MapEntryImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.mutable.MutableMapEntry;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
/**
* Implementation of MapEntry
*
* @version $Rev$, $Date$
*/
public class MapEntryImpl implements MutableMapEntry {
private NonNullMetadata key;
private Metadata value;
public MapEntryImpl() {
}
public MapEntryImpl(NonNullMetadata key, Metadata value) {
this.key = key;
this.value = value;
}
public MapEntryImpl(MapEntry entry) {
this.key = (NonNullMetadata) MetadataUtil.cloneMetadata(entry.getKey());
this.value = MetadataUtil.cloneMetadata(entry.getValue());
}
public NonNullMetadata getKey() {
return key;
}
public void setKey(NonNullMetadata key) {
this.key = key;
}
public Metadata getValue() {
return value;
}
public void setValue(Metadata value) {
this.value = value;
}
@Override
public String toString() {
return "MapEntry[" +
"key=" + key +
", value=" + value +
']';
}
}
| 9,606 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/RegistrationListenerImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.mutable.MutableRegistrationListener;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.Target;
/**
* Implementation of RegistrationListener.
*
* @version $Rev$, $Date$
*/
public class RegistrationListenerImpl implements MutableRegistrationListener {
private Target listenerComponent;
private String registrationMethod;
private String unregistrationMethod;
public RegistrationListenerImpl() {
}
public RegistrationListenerImpl(Target listenerComponent, String registrationMethod, String unregistrationMethod) {
this.listenerComponent = listenerComponent;
this.registrationMethod = registrationMethod;
this.unregistrationMethod = unregistrationMethod;
}
public RegistrationListenerImpl(RegistrationListener source) {
listenerComponent = MetadataUtil.cloneTarget(source.getListenerComponent());
registrationMethod = source.getRegistrationMethod();
unregistrationMethod = source.getUnregistrationMethod();
}
public Target getListenerComponent() {
return listenerComponent;
}
public void setListenerComponent(Target listenerComponent) {
this.listenerComponent = listenerComponent;
}
public String getRegistrationMethod() {
return registrationMethod;
}
public void setRegistrationMethod(String registrationMethod) {
this.registrationMethod = registrationMethod;
}
public String getUnregistrationMethod() {
return unregistrationMethod;
}
public void setUnregistrationMethod(String unregistrationMethod) {
this.unregistrationMethod = unregistrationMethod;
}
@Override
public String toString() {
return "RegistrationListener[" +
"listenerComponent=" + listenerComponent +
", registrationMethodName='" + registrationMethod + '\'' +
", unregistrationMethodName='" + unregistrationMethod + '\'' +
']';
}
}
| 9,607 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/ComponentMetadataImpl.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.blueprint.reflect;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.aries.blueprint.mutable.MutableComponentMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
/**
* Implementation of ComponentMetadata
*
* @version $Rev$, $Date$
*/
public class ComponentMetadataImpl implements MutableComponentMetadata {
protected String id;
protected int activation = ACTIVATION_EAGER;
protected List<String> dependsOn;
protected ComponentMetadataImpl() {
}
protected ComponentMetadataImpl(ComponentMetadata source) {
id = source.getId();
activation = source.getActivation();
dependsOn = new ArrayList<String>(source.getDependsOn());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getActivation() {
return activation;
}
public void setActivation(int activation) {
this.activation = activation;
}
public List<String> getDependsOn() {
if (this.dependsOn == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(this.dependsOn);
}
}
public void setDependsOn(List<String> dependsOn) {
this.dependsOn = dependsOn != null ? new ArrayList<String>(dependsOn) : null;
}
public void addDependsOn(String explicitDependency) {
if (this.dependsOn == null) {
this.dependsOn = new ArrayList<String>();
}
this.dependsOn.add(explicitDependency);
}
public void removeDependsOn(String dependency) {
if (this.dependsOn != null) {
this.dependsOn.remove(dependency);
}
}
}
| 9,608 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/IdRefMetadataImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.mutable.MutableIdRefMetadata;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
/**
* Implementation of IdRefMetadata
*
* @version $Rev$, $Date$
*/
public class IdRefMetadataImpl implements MutableIdRefMetadata {
protected String componentId;
public IdRefMetadataImpl() {
}
public IdRefMetadataImpl(String componentId) {
this.componentId = componentId;
}
public IdRefMetadataImpl(IdRefMetadata source) {
componentId = source.getComponentId();
}
public String getComponentId() {
return componentId;
}
public void setComponentId(String componentId) {
this.componentId = componentId;
}
@Override
public String toString() {
return "IdRefMetadata[" +
"componentId='" + componentId + '\'' +
']';
}
}
| 9,609 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/PassThroughMetadataImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutablePassThroughMetadata;
/**
* A metadata for environment managers.
*
* @version $Rev$, $Date$
*/
public class PassThroughMetadataImpl extends ComponentMetadataImpl implements MutablePassThroughMetadata {
private Object object;
public PassThroughMetadataImpl() {
}
public PassThroughMetadataImpl(PassThroughMetadata source) {
super(source);
this.object = source.getObject();
}
public PassThroughMetadataImpl(String id, Object object) {
this.id = id;
this.object = object;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
| 9,610 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/parser/Parser.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.blueprint.parser;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.Validator;
import java.io.InputStream;
import java.net.URI;
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.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.reflect.BeanArgumentImpl;
import org.apache.aries.blueprint.reflect.BeanMetadataImpl;
import org.apache.aries.blueprint.reflect.BeanPropertyImpl;
import org.apache.aries.blueprint.reflect.CollectionMetadataImpl;
import org.apache.aries.blueprint.reflect.IdRefMetadataImpl;
import org.apache.aries.blueprint.reflect.MapEntryImpl;
import org.apache.aries.blueprint.reflect.MapMetadataImpl;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.apache.aries.blueprint.reflect.PropsMetadataImpl;
import org.apache.aries.blueprint.reflect.RefMetadataImpl;
import org.apache.aries.blueprint.reflect.ReferenceListMetadataImpl;
import org.apache.aries.blueprint.reflect.ReferenceListenerImpl;
import org.apache.aries.blueprint.reflect.ReferenceMetadataImpl;
import org.apache.aries.blueprint.reflect.RegistrationListenerImpl;
import org.apache.aries.blueprint.reflect.ServiceMetadataImpl;
import org.apache.aries.blueprint.reflect.ServiceReferenceMetadataImpl;
import org.apache.aries.blueprint.reflect.ValueMetadataImpl;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.NullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.osgi.service.blueprint.reflect.ValueMetadata;
import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
/**
* TODO: javadoc
*
* @version $Rev: 1135256 $, $Date: 2011-06-13 21:09:27 +0100 (Mon, 13 Jun 2011) $
*/
public class Parser {
public static final String BLUEPRINT_NAMESPACE = "http://www.osgi.org/xmlns/blueprint/v1.0.0";
public static final String BLUEPRINT_ELEMENT = "blueprint";
public static final String DESCRIPTION_ELEMENT = "description";
public static final String TYPE_CONVERTERS_ELEMENT = "type-converters";
public static final String BEAN_ELEMENT = "bean";
public static final String ARGUMENT_ELEMENT = "argument";
public static final String REF_ELEMENT = "ref";
public static final String IDREF_ELEMENT = "idref";
public static final String LIST_ELEMENT = "list";
public static final String SET_ELEMENT = "set";
public static final String MAP_ELEMENT = "map";
public static final String ARRAY_ELEMENT = "array";
public static final String PROPS_ELEMENT = "props";
public static final String PROP_ELEMENT = "prop";
public static final String PROPERTY_ELEMENT = "property";
public static final String NULL_ELEMENT = "null";
public static final String VALUE_ELEMENT = "value";
public static final String SERVICE_ELEMENT = "service";
public static final String REFERENCE_ELEMENT = "reference";
public static final String REFERENCE_LIST_ELEMENT = "reference-list";
public static final String INTERFACES_ELEMENT = "interfaces";
public static final String REFERENCE_LISTENER_ELEMENT = "reference-listener";
public static final String SERVICE_PROPERTIES_ELEMENT = "service-properties";
public static final String REGISTRATION_LISTENER_ELEMENT = "registration-listener";
public static final String ENTRY_ELEMENT = "entry";
public static final String KEY_ELEMENT = "key";
public static final String DEFAULT_ACTIVATION_ATTRIBUTE = "default-activation";
public static final String DEFAULT_TIMEOUT_ATTRIBUTE = "default-timeout";
public static final String DEFAULT_AVAILABILITY_ATTRIBUTE = "default-availability";
public static final String NAME_ATTRIBUTE = "name";
public static final String ID_ATTRIBUTE = "id";
public static final String CLASS_ATTRIBUTE = "class";
public static final String INDEX_ATTRIBUTE = "index";
public static final String TYPE_ATTRIBUTE = "type";
public static final String VALUE_ATTRIBUTE = "value";
public static final String VALUE_REF_ATTRIBUTE = "value-ref";
public static final String KEY_ATTRIBUTE = "key";
public static final String KEY_REF_ATTRIBUTE = "key-ref";
public static final String REF_ATTRIBUTE = "ref";
public static final String COMPONENT_ID_ATTRIBUTE = "component-id";
public static final String INTERFACE_ATTRIBUTE = "interface";
public static final String DEPENDS_ON_ATTRIBUTE = "depends-on";
public static final String AUTO_EXPORT_ATTRIBUTE = "auto-export";
public static final String RANKING_ATTRIBUTE = "ranking";
public static final String TIMEOUT_ATTRIBUTE = "timeout";
public static final String FILTER_ATTRIBUTE = "filter";
public static final String COMPONENT_NAME_ATTRIBUTE = "component-name";
public static final String AVAILABILITY_ATTRIBUTE = "availability";
public static final String REGISTRATION_METHOD_ATTRIBUTE = "registration-method";
public static final String UNREGISTRATION_METHOD_ATTRIBUTE = "unregistration-method";
public static final String BIND_METHOD_ATTRIBUTE = "bind-method";
public static final String UNBIND_METHOD_ATTRIBUTE = "unbind-method";
public static final String KEY_TYPE_ATTRIBUTE = "key-type";
public static final String VALUE_TYPE_ATTRIBUTE = "value-type";
public static final String MEMBER_TYPE_ATTRIBUTE = "member-type";
public static final String SCOPE_ATTRIBUTE = "scope";
public static final String INIT_METHOD_ATTRIBUTE = "init-method";
public static final String DESTROY_METHOD_ATTRIBUTE = "destroy-method";
public static final String ACTIVATION_ATTRIBUTE = "activation";
public static final String FACTORY_REF_ATTRIBUTE = "factory-ref";
public static final String FACTORY_METHOD_ATTRIBUTE = "factory-method";
public static final String AUTO_EXPORT_DISABLED = "disabled";
public static final String AUTO_EXPORT_INTERFACES = "interfaces";
public static final String AUTO_EXPORT_CLASS_HIERARCHY = "class-hierarchy";
public static final String AUTO_EXPORT_ALL = "all-classes";
public static final String AUTO_EXPORT_DEFAULT = AUTO_EXPORT_DISABLED;
public static final String RANKING_DEFAULT = "0";
public static final String AVAILABILITY_MANDATORY = "mandatory";
public static final String AVAILABILITY_OPTIONAL = "optional";
public static final String AVAILABILITY_DEFAULT = AVAILABILITY_MANDATORY;
public static final String TIMEOUT_DEFAULT = "300000";
public static final String USE_SERVICE_OBJECT = "service-object";
public static final String USE_SERVICE_REFERENCE = "service-reference";
public static final String ACTIVATION_EAGER = "eager";
public static final String ACTIVATION_LAZY = "lazy";
public static final String ACTIVATION_DEFAULT = ACTIVATION_EAGER;
private static DocumentBuilderFactory documentBuilderFactory;
private static final NamespaceHandler missingNamespace = new NamespaceHandler() {
@Override
public Metadata parse(Element element, ParserContext context) {
return null;
}
@Override
public URL getSchemaLocation(String namespace) {
return null;
}
@Override
public Set<Class> getManagedClasses() {
return null;
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata component,
ParserContext context) {
return component;
}
};
private final List<Document> documents = new ArrayList<Document>();
private ComponentDefinitionRegistry registry;
private NamespaceHandlerSet handlers;
private final String idPrefix;
private final boolean ignoreUnknownNamespaces;
private final Set<String> ids = new HashSet<String>();
private int idCounter;
private String defaultTimeout;
private String defaultAvailability;
private String defaultActivation;
private Set<URI> namespaces;
private Map<String, String> locations;
public Parser() {
this(null);
}
public Parser(String idPrefix) {
this(idPrefix, false);
}
public Parser(String idPrefix, boolean ignoreUnknownNamespaces) {
this.idPrefix = idPrefix == null ? "component-" : idPrefix;
this.ignoreUnknownNamespaces = ignoreUnknownNamespaces;
}
/**
* Parse an input stream for blueprint xml.
* @param inputStream The data to parse. The caller is responsible for closing the stream afterwards.
* @throws Exception on parse error
*/
public void parse(InputStream inputStream) throws Exception {
parse(null, inputStream);
}
public void parse(String location, InputStream inputStream) throws Exception {
InputSource inputSource = new InputSource(inputStream);
inputSource.setSystemId(location);
DocumentBuilder builder = getDocumentBuilderFactory().newDocumentBuilder();
Document doc = builder.parse(inputSource);
documents.add(doc);
}
/**
* Parse blueprint xml referred to by a list of URLs
* @param urls URLs to blueprint xml to parse
* @throws Exception on parse error
*/
public void parse(List<URL> urls) throws Exception {
// Create document builder factory
// Load documents
for (URL url : urls) {
InputStream inputStream = url.openStream();
try {
parse (url.toString(), inputStream);
} finally {
inputStream.close();
}
}
}
public Set<URI> getNamespaces() {
if (this.namespaces == null) {
Set<URI> namespaces = new LinkedHashSet<URI>();
Map<String, String> locations = new HashMap<String, String>();
for (Document doc : documents) {
findNamespaces(namespaces, locations, doc);
}
this.namespaces = namespaces;
this.locations = locations;
}
return this.namespaces;
}
public Map<String, String> getSchemaLocations() {
getNamespaces();
return locations;
}
private void findNamespaces(Set<URI> namespaces, Map<String, String> locations, Node node) {
if (node instanceof Element || node instanceof Attr) {
String ns = node.getNamespaceURI();
if ("http://www.w3.org/2001/XMLSchema-instance".equals(ns)
&& node instanceof Attr
&& "schemaLocation".equals(node.getLocalName())) {
String val = ((Attr) node).getValue();
List<String> locs = new ArrayList<String>(Arrays.asList(val.split("\\s+")));
locs.remove("");
for (int i = 0; i < locs.size() / 2; i++) {
locations.put(locs.get(i * 2), locs.get(i * 2 + 1));
}
} else if (ns != null && !isBlueprintNamespace(ns) && !isIgnorableAttributeNamespace(ns)) {
namespaces.add(URI.create(ns));
} else if (ns == null && //attributes from blueprint are unqualified as per schema.
node instanceof Attr &&
SCOPE_ATTRIBUTE.equals(node.getNodeName()) &&
((Attr)node).getOwnerElement() != null && //should never occur from parsed doc.
BLUEPRINT_NAMESPACE.equals(((Attr)node).getOwnerElement().getNamespaceURI()) &&
BEAN_ELEMENT.equals(((Attr)node).getOwnerElement().getLocalName()) ){
//Scope attribute is special case, as may contain namespace usage within its value.
URI scopeNS = getNamespaceForAttributeValue(node);
if(scopeNS!=null){
namespaces.add(scopeNS);
}
}
}
NamedNodeMap nnm = node.getAttributes();
if(nnm!=null){
for(int i = 0; i< nnm.getLength() ; i++){
findNamespaces(namespaces, locations, nnm.item(i));
}
}
NodeList nl = node.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
findNamespaces(namespaces, locations, nl.item(i));
}
}
public void populate(NamespaceHandlerSet handlers,
ComponentDefinitionRegistry registry) {
this.handlers = handlers;
this.registry = registry;
if (this.documents == null) {
throw new IllegalStateException("Documents should be parsed before populating the registry");
}
// Parse components
for (Document doc : this.documents) {
loadComponents(doc);
}
}
public void validate(Schema schema) {
validate(schema, null);
}
public void validate(Schema schema, ErrorHandler errorHandler) {
try {
Validator validator = schema.newValidator();
if (errorHandler != null) {
validator.setErrorHandler(errorHandler);
}
for (Document doc : this.documents) {
validator.validate(new DOMSource(doc));
}
} catch (Exception e) {
throw new ComponentDefinitionException("Unable to validate xml", e);
}
}
public void validatePsvi(Schema schema) {
try {
// In order to support validation with the built-in xml parser
// from the JDK, we can't use Validator.validate(source, result)
// as it fails with an exception, see
// https://issues.apache.org/jira/browse/XERCESJ-1212
// This was fixed in xerces 2.9.0 years ago but still is not
// included in my JDK.
List<String> locations = new ArrayList<String>();
for (Document doc : documents) {
locations.add(doc.getDocumentURI());
}
List<Document> validated = new ArrayList<Document>();
for (String location : locations) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setSchema(schema);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(location);
Document doc = builder.parse(inputSource);
validated.add(doc);
}
this.documents.clear();
this.documents.addAll(validated);
} catch (Exception e) {
throw new ComponentDefinitionException("Unable to validate xml", e);
}
}
private void loadComponents(Document doc) {
defaultTimeout = TIMEOUT_DEFAULT;
defaultAvailability = AVAILABILITY_DEFAULT;
defaultActivation = ACTIVATION_DEFAULT;
Element root = doc.getDocumentElement();
if (!isBlueprintNamespace(root.getNamespaceURI()) ||
!nodeNameEquals(root, BLUEPRINT_ELEMENT)) {
throw new ComponentDefinitionException("Root element must be {" + BLUEPRINT_NAMESPACE + "}" + BLUEPRINT_ELEMENT + " element");
}
// Parse global attributes
if (root.hasAttribute(DEFAULT_ACTIVATION_ATTRIBUTE)) {
defaultActivation = root.getAttribute(DEFAULT_ACTIVATION_ATTRIBUTE);
}
if (root.hasAttribute(DEFAULT_TIMEOUT_ATTRIBUTE)) {
defaultTimeout = root.getAttribute(DEFAULT_TIMEOUT_ATTRIBUTE);
}
if (root.hasAttribute(DEFAULT_AVAILABILITY_ATTRIBUTE)) {
defaultAvailability = root.getAttribute(DEFAULT_AVAILABILITY_ATTRIBUTE);
}
// Parse custom attributes
handleCustomAttributes(root.getAttributes(), null);
// Parse elements
// Break into 2 loops to ensure we scan the blueprint elements before
// This is needed so that when we process the custom element, we know
// the component definition registry has populated all blueprint components.
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element element = (Element) node;
String namespaceUri = element.getNamespaceURI();
if (isBlueprintNamespace(namespaceUri)) {
parseBlueprintElement(element);
}
}
}
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element element = (Element) node;
String namespaceUri = element.getNamespaceURI();
if (!isBlueprintNamespace(namespaceUri)) {
Metadata component = parseCustomElement(element, null);
if (component != null) {
if (!(component instanceof ComponentMetadata)) {
throw new ComponentDefinitionException("Expected a ComponentMetadata to be returned when parsing element " + element.getNodeName());
}
registry.registerComponentDefinition((ComponentMetadata) component);
}
}
}
}
}
public <T> T parseElement(Class<T> type, ComponentMetadata enclosingComponent, Element element) {
if (BeanArgument.class.isAssignableFrom(type)) {
return type.cast(parseBeanArgument(enclosingComponent, element));
} else if (BeanProperty.class.isAssignableFrom(type)) {
return type.cast(parseBeanProperty(enclosingComponent, element));
} else if (MapEntry.class.isAssignableFrom(type)) {
return type.cast(parseMapEntry(element, enclosingComponent, null, null));
} else if (MapMetadata.class.isAssignableFrom(type)) {
return type.cast(parseMap(element, enclosingComponent));
} else if (BeanMetadata.class.isAssignableFrom(type)) {
return type.cast(parseBeanMetadata(element, enclosingComponent == null));
} else if (NullMetadata.class.isAssignableFrom(type)) {
return type.cast(NullMetadata.NULL);
} else if (CollectionMetadata.class.isAssignableFrom(type)) {
return type.cast(parseCollection(Collection.class, element, enclosingComponent));
} else if (PropsMetadata.class.isAssignableFrom(type)) {
return type.cast(parseProps(element));
} else if (ReferenceMetadata.class.isAssignableFrom(type)) {
return type.cast(parseReference(element, enclosingComponent == null));
} else if (ReferenceListMetadata.class.isAssignableFrom(type)) {
return type.cast(parseRefList(element, enclosingComponent == null));
} else if (ServiceMetadata.class.isAssignableFrom(type)) {
return type.cast(parseService(element, enclosingComponent == null));
} else if (IdRefMetadata.class.isAssignableFrom(type)) {
return type.cast(parseIdRef(element));
} else if (RefMetadata.class.isAssignableFrom(type)) {
return type.cast(parseRef(element));
} else if (ValueMetadata.class.isAssignableFrom(type)) {
return type.cast(parseValue(element, null));
} else if (ReferenceListener.class.isAssignableFrom(type)) {
return type.cast(parseServiceListener(element, enclosingComponent));
} else if (Metadata.class.isAssignableFrom(type)) {
return type.cast(parseValueGroup(element, enclosingComponent, null, true));
} else {
throw new ComponentDefinitionException("Unknown type to parse element: " + type.getName());
}
}
private void parseBlueprintElement(Element element) {
if (nodeNameEquals(element, DESCRIPTION_ELEMENT)) {
// Ignore description
} else if (nodeNameEquals(element, TYPE_CONVERTERS_ELEMENT)) {
parseTypeConverters(element);
} else if (nodeNameEquals(element, BEAN_ELEMENT)) {
ComponentMetadata component = parseBeanMetadata(element, true);
registry.registerComponentDefinition(component);
} else if (nodeNameEquals(element, SERVICE_ELEMENT)) {
ComponentMetadata service = parseService(element, true);
registry.registerComponentDefinition(service);
} else if (nodeNameEquals(element, REFERENCE_ELEMENT)) {
ComponentMetadata reference = parseReference(element, true);
registry.registerComponentDefinition(reference);
} else if (nodeNameEquals(element, REFERENCE_LIST_ELEMENT) ) {
ComponentMetadata references = parseRefList(element, true);
registry.registerComponentDefinition(references);
} else {
throw new ComponentDefinitionException("Unknown element " + element.getNodeName() + " in namespace " + BLUEPRINT_NAMESPACE);
}
}
private void parseTypeConverters(Element element) {
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
Object target = null;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, BEAN_ELEMENT)) {
target = parseBeanMetadata(e, true);
} else if (nodeNameEquals(e, REF_ELEMENT)) {
String componentName = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
target = new RefMetadataImpl(componentName);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
target = parseReference(e, true);
}
} else {
target = parseCustomElement(e, null);
}
if (!(target instanceof Target)) {
throw new ComponentDefinitionException("Metadata parsed for element " + e.getNodeName() + " can not be used as a type converter");
}
registry.registerTypeConverter((Target) target);
}
}
}
/**
* Takes an Attribute Node containing a namespace prefix qualified attribute value, and resolves the namespace using the DOM Node.<br>
*
* @param attrNode The DOM Node with the qualified attribute value.
* @return The URI if one is resolvable, or null if the attr is null, or not namespace prefixed. (or not a DOM Attribute Node)
* @throws ComponentDefinitionException if the namespace prefix in the attribute value cannot be resolved.
*/
private URI getNamespaceForAttributeValue(Node attrNode) throws ComponentDefinitionException {
URI uri = null;
if(attrNode!=null && (attrNode instanceof Attr)){
Attr attr = (Attr)attrNode;
String attrValue = attr.getValue();
if(attrValue!=null && attrValue.indexOf(":")!=-1){
String parts[] = attrValue.split(":");
String uriStr = attr.getOwnerElement().lookupNamespaceURI(parts[0]);
if(uriStr!=null){
uri = URI.create(uriStr);
}else{
throw new ComponentDefinitionException("Unsupported attribute namespace prefix "+parts[0]+" "+attr);
}
}
}
return uri;
}
/**
* Takes an Attribute Node for the scope, and returns the value.<br>
*
* @param attrNode The DOM Node with the attribute value.
* @return The scope as a stringified value. It should be either the value <code>prototype</code>,
* <code>singleton</code>, or a namespace qualified value, e.g. {http://foo}bar
* @throws ComponentDefinitionException if the namespace prefix in the attribute value cannot be resolved.
*/
private String getScope(Node attrNode) throws ComponentDefinitionException {
String scope = null;
if(attrNode!=null && (attrNode instanceof Attr)){
Attr attr = (Attr)attrNode;
String attrValue = attr.getValue();
if(attrValue!=null && attrValue.indexOf(":")!=-1){
String[] parts = attrValue.split(":");
String prefix = parts[0];
String localName = parts[1];
String namespaceURI = attr.getOwnerElement().lookupNamespaceURI(prefix);
if(namespaceURI!=null){
scope = new QName(namespaceURI, localName).toString();
}else{
throw new ComponentDefinitionException("Unable to determine namespace binding for prefix, " + prefix);
}
}
else {
scope = attrValue;
}
}
return scope;
}
/**
* Tests if a scope attribute value is a custom scope, and if so invokes
* the appropriate namespace handler, passing the blueprint scope node.
* <p>
* Currently this tests for custom scope by looking for the presence of
* a ':' char within the scope attribute value. This is valid as long as
* the blueprint schema continues to restrict that custom scopes should
* require that characters presence.
* <p>
*
* @param scope Value of scope attribute
* @param bean DOM element for bean associated to this scope
* @return Metadata as processed by NS Handler.
* @throws ComponentDefinitionException if an undeclared prefix is used,
* if a namespace handler is unavailable for a resolved prefix,
* or if the resolved prefix results as the blueprint namespace.
*/
private ComponentMetadata handleCustomScope(Node scope, Element bean, ComponentMetadata metadata){
URI scopeNS = getNamespaceForAttributeValue(scope);
if(scopeNS!=null && !BLUEPRINT_NAMESPACE.equals(scopeNS.toString())){
NamespaceHandler nsHandler = getNamespaceHandler(scopeNS);
ParserContextImpl context = new ParserContextImpl(this, registry, metadata, scope);
metadata = nsHandler.decorate(scope, metadata, context);
}else if(scopeNS!=null){
throw new ComponentDefinitionException("Custom scopes cannot use the blueprint namespace "+scope);
}
return metadata;
}
private ComponentMetadata parseBeanMetadata(Element element, boolean topElement) {
BeanMetadataImpl metadata = new BeanMetadataImpl();
if (topElement) {
metadata.setId(getId(element));
if (element.hasAttribute(SCOPE_ATTRIBUTE)) {
metadata.setScope(getScope(element.getAttributeNode(SCOPE_ATTRIBUTE)));
if (!metadata.getScope().equals(BeanMetadata.SCOPE_SINGLETON)) {
if (element.hasAttribute(ACTIVATION_ATTRIBUTE)) {
if (element.getAttribute(ACTIVATION_ATTRIBUTE).equals(ACTIVATION_EAGER)) {
throw new ComponentDefinitionException("A <bean> with a prototype or custom scope can not have an eager activation");
}
}
metadata.setActivation(ComponentMetadata.ACTIVATION_LAZY);
} else {
metadata.setActivation(parseActivation(element));
}
} else {
metadata.setActivation(parseActivation(element));
}
} else {
metadata.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(CLASS_ATTRIBUTE)) {
metadata.setClassName(element.getAttribute(CLASS_ATTRIBUTE));
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
metadata.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
if (element.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
metadata.setInitMethod(element.getAttribute(INIT_METHOD_ATTRIBUTE));
}
if (element.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
metadata.setDestroyMethod(element.getAttribute(DESTROY_METHOD_ATTRIBUTE));
}
if (element.hasAttribute(FACTORY_REF_ATTRIBUTE)) {
metadata.setFactoryComponent(new RefMetadataImpl(element.getAttribute(FACTORY_REF_ATTRIBUTE)));
}
if (element.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
String factoryMethod = element.getAttribute(FACTORY_METHOD_ATTRIBUTE);
metadata.setFactoryMethod(factoryMethod);
}
// Do some validation
if (metadata.getClassName() == null && metadata.getFactoryComponent() == null) {
throw new ComponentDefinitionException("Bean class or factory-ref must be specified");
}
if (metadata.getFactoryComponent() != null && metadata.getFactoryMethod() == null) {
throw new ComponentDefinitionException("factory-method is required when factory-component is set");
}
if (MetadataUtil.isPrototypeScope(metadata) && metadata.getDestroyMethod() != null) {
throw new ComponentDefinitionException("destroy-method must not be set for a <bean> with a prototype scope");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(node.getNamespaceURI())) {
if (nodeNameEquals(node, ARGUMENT_ELEMENT)) {
metadata.addArgument(parseBeanArgument(metadata, e));
} else if (nodeNameEquals(node, PROPERTY_ELEMENT)) {
metadata.addProperty(parseBeanProperty(metadata, e));
}
}
}
}
MetadataUtil.validateBeanArguments(metadata.getArguments());
ComponentMetadata m = metadata;
// Parse custom scopes
m = handleCustomScope(element.getAttributeNode(SCOPE_ATTRIBUTE), element, m);
// Parse custom attributes
m = handleCustomAttributes(element.getAttributes(), m);
// Parse custom elements;
m = handleCustomElements(element, m);
return m;
}
public BeanProperty parseBeanProperty(ComponentMetadata enclosingComponent, Element element) {
String name = element.hasAttribute(NAME_ATTRIBUTE) ? element.getAttribute(NAME_ATTRIBUTE) : null;
Metadata value = parseArgumentOrPropertyValue(element, enclosingComponent);
return new BeanPropertyImpl(name, value);
}
private BeanArgument parseBeanArgument(ComponentMetadata enclosingComponent, Element element) {
int index = element.hasAttribute(INDEX_ATTRIBUTE) ? Integer.parseInt(element.getAttribute(INDEX_ATTRIBUTE)) : -1;
String type = element.hasAttribute(TYPE_ATTRIBUTE) ? element.getAttribute(TYPE_ATTRIBUTE) : null;
Metadata value = parseArgumentOrPropertyValue(element, enclosingComponent);
return new BeanArgumentImpl(value, type, index);
}
private ComponentMetadata parseService(Element element, boolean topElement) {
ServiceMetadataImpl service = new ServiceMetadataImpl();
boolean hasInterfaceNameAttribute = false;
if (topElement) {
service.setId(getId(element));
service.setActivation(parseActivation(element));
} else {
service.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(INTERFACE_ATTRIBUTE)) {
service.setInterfaceNames(Collections.singletonList(element.getAttribute(INTERFACE_ATTRIBUTE)));
hasInterfaceNameAttribute = true;
}
if (element.hasAttribute(REF_ATTRIBUTE)) {
service.setServiceComponent(new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE)));
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
service.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
String autoExport = element.hasAttribute(AUTO_EXPORT_ATTRIBUTE) ? element.getAttribute(AUTO_EXPORT_ATTRIBUTE) : AUTO_EXPORT_DEFAULT;
if (AUTO_EXPORT_DISABLED.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_DISABLED);
} else if (AUTO_EXPORT_INTERFACES.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_INTERFACES);
} else if (AUTO_EXPORT_CLASS_HIERARCHY.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY);
} else if (AUTO_EXPORT_ALL.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_ALL_CLASSES);
} else {
throw new ComponentDefinitionException("Illegal value (" + autoExport + ") for " + AUTO_EXPORT_ATTRIBUTE + " attribute");
}
String ranking = element.hasAttribute(RANKING_ATTRIBUTE) ? element.getAttribute(RANKING_ATTRIBUTE) : RANKING_DEFAULT;
try {
service.setRanking(Integer.parseInt(ranking));
} catch (NumberFormatException e) {
throw new ComponentDefinitionException("Attribute " + RANKING_ATTRIBUTE + " must be a valid integer (was: " + ranking + ")");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, INTERFACES_ELEMENT)) {
if (hasInterfaceNameAttribute) {
throw new ComponentDefinitionException("Only one of " + INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must be used");
}
service.setInterfaceNames(parseInterfaceNames(e));
} else if (nodeNameEquals(e, SERVICE_PROPERTIES_ELEMENT)) {
List<MapEntry> entries = parseServiceProperties(e, service).getEntries();
service.setServiceProperties(entries);
} else if (nodeNameEquals(e, REGISTRATION_LISTENER_ELEMENT)) {
service.addRegistrationListener(parseRegistrationListener(e, service));
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
service.setServiceComponent((Target) parseBeanMetadata(e, false));
} else if (nodeNameEquals(e, REF_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
service.setServiceComponent(new RefMetadataImpl(component));
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
service.setServiceComponent((Target) parseReference(e, false));
}
}
}
}
// Check service
if (service.getServiceComponent() == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element must be set");
}
// Check interface
if (service.getAutoExport() == ServiceMetadata.AUTO_EXPORT_DISABLED && service.getInterfaces().isEmpty()) {
throw new ComponentDefinitionException(INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must be set when " + AUTO_EXPORT_ATTRIBUTE + " is set to " + AUTO_EXPORT_DISABLED);
}
// Check for non-disabled auto-exports and interfaces
if (service.getAutoExport() != ServiceMetadata.AUTO_EXPORT_DISABLED && !service.getInterfaces().isEmpty()) {
throw new ComponentDefinitionException(INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must not be set when " + AUTO_EXPORT_ATTRIBUTE + " is set to anything else than " + AUTO_EXPORT_DISABLED);
}
ComponentMetadata s = service;
// Parse custom attributes
s = handleCustomAttributes(element.getAttributes(), s);
// Parse custom elements;
s = handleCustomElements(element, s);
return s;
}
private CollectionMetadata parseArray(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(Object[].class, element, enclosingComponent);
}
private CollectionMetadata parseList(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(List.class, element, enclosingComponent);
}
private CollectionMetadata parseSet(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(Set.class, element, enclosingComponent);
}
private CollectionMetadata parseCollection(Class collectionType, Element element, ComponentMetadata enclosingComponent) {
// Parse attributes
String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
// Parse elements
List<Metadata> list = new ArrayList<Metadata>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Metadata val = parseValueGroup((Element) node, enclosingComponent, null, true);
list.add(val);
}
}
return new CollectionMetadataImpl(collectionType, valueType, list);
}
public PropsMetadata parseProps(Element element) {
// Parse elements
List<MapEntry> entries = new ArrayList<MapEntry>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI()) && nodeNameEquals(e, PROP_ELEMENT)) {
entries.add(parseProperty(e));
}
}
}
return new PropsMetadataImpl(entries);
}
private MapEntry parseProperty(Element element) {
// Parse attributes
if (!element.hasAttribute(KEY_ATTRIBUTE)) {
throw new ComponentDefinitionException(KEY_ATTRIBUTE + " attribute is required");
}
String value;
if (element.hasAttribute(VALUE_ATTRIBUTE)) {
value = element.getAttribute(VALUE_ATTRIBUTE);
} else {
value = getTextValue(element);
}
String key = element.getAttribute(KEY_ATTRIBUTE);
return new MapEntryImpl(new ValueMetadataImpl(key), new ValueMetadataImpl(value));
}
public MapMetadata parseMap(Element element, ComponentMetadata enclosingComponent) {
// Parse attributes
String keyType = element.hasAttribute(KEY_TYPE_ATTRIBUTE) ? element.getAttribute(KEY_TYPE_ATTRIBUTE) : null;
String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
// Parse elements
List<MapEntry> entries = new ArrayList<MapEntry>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, ENTRY_ELEMENT)) {
entries.add(parseMapEntry(e, enclosingComponent, null, null));
}
}
}
return new MapMetadataImpl(keyType, valueType, entries);
}
private MapEntry parseMapEntry(Element element, ComponentMetadata enclosingComponent, String keyType, String valueType) {
// Parse attributes
String key = element.hasAttribute(KEY_ATTRIBUTE) ? element.getAttribute(KEY_ATTRIBUTE) : null;
String keyRef = element.hasAttribute(KEY_REF_ATTRIBUTE) ? element.getAttribute(KEY_REF_ATTRIBUTE) : null;
String value = element.hasAttribute(VALUE_ATTRIBUTE) ? element.getAttribute(VALUE_ATTRIBUTE) : null;
String valueRef = element.hasAttribute(VALUE_REF_ATTRIBUTE) ? element.getAttribute(VALUE_REF_ATTRIBUTE) : null;
// Parse elements
NonNullMetadata keyValue = null;
Metadata valValue = null;
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, KEY_ELEMENT)) {
keyValue = parseMapKeyEntry(e, enclosingComponent, keyType);
} else {
valValue = parseValueGroup(e, enclosingComponent, valueType, true);
}
}
}
// Check key
if (keyValue != null && (key != null || keyRef != null) || (keyValue == null && key == null && keyRef == null)) {
throw new ComponentDefinitionException("Only and only one of " + KEY_ATTRIBUTE + " attribute, " + KEY_REF_ATTRIBUTE + " attribute or " + KEY_ELEMENT + " element must be set");
} else if (keyValue == null && key != null) {
keyValue = new ValueMetadataImpl(key, keyType);
} else if (keyValue == null /*&& keyRef != null*/) {
keyValue = new RefMetadataImpl(keyRef);
}
// Check value
if (valValue != null && (value != null || valueRef != null) || (valValue == null && value == null && valueRef == null)) {
throw new ComponentDefinitionException("Only and only one of " + VALUE_ATTRIBUTE + " attribute, " + VALUE_REF_ATTRIBUTE + " attribute or sub element must be set");
} else if (valValue == null && value != null) {
valValue = new ValueMetadataImpl(value, valueType);
} else if (valValue == null /*&& valueRef != null*/) {
valValue = new RefMetadataImpl(valueRef);
}
return new MapEntryImpl(keyValue, valValue);
}
private NonNullMetadata parseMapKeyEntry(Element element, ComponentMetadata enclosingComponent, String keyType) {
NonNullMetadata keyValue = null;
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (keyValue != null) {
// TODO: throw an exception
}
keyValue = (NonNullMetadata) parseValueGroup(e, enclosingComponent, keyType, false);
break;
}
}
if (keyValue == null) {
// TODO: throw an exception
}
return keyValue;
}
public MapMetadata parseServiceProperties(Element element, ComponentMetadata enclosingComponent) {
// TODO: need to handle this better
MapMetadata map = parseMap(element, enclosingComponent);
handleCustomElements(element, enclosingComponent);
return map;
}
public RegistrationListener parseRegistrationListener(Element element, ComponentMetadata enclosingComponent) {
RegistrationListenerImpl listener = new RegistrationListenerImpl();
Metadata listenerComponent = null;
// Parse attributes
if (element.hasAttribute(REF_ATTRIBUTE)) {
listenerComponent = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
String registrationMethod = null;
if (element.hasAttribute(REGISTRATION_METHOD_ATTRIBUTE)) {
registrationMethod = element.getAttribute(REGISTRATION_METHOD_ATTRIBUTE);
listener.setRegistrationMethod(registrationMethod);
}
String unregistrationMethod = null;
if (element.hasAttribute(UNREGISTRATION_METHOD_ATTRIBUTE)) {
unregistrationMethod = element.getAttribute(UNREGISTRATION_METHOD_ATTRIBUTE);
listener.setUnregistrationMethod(unregistrationMethod);
}
if (registrationMethod == null && unregistrationMethod == null) {
throw new ComponentDefinitionException("One of " + REGISTRATION_METHOD_ATTRIBUTE + " or " + UNREGISTRATION_METHOD_ATTRIBUTE + " must be set");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REF_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
listenerComponent = new RefMetadataImpl(component);
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseBeanMetadata(e, false);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseReference(e, false);
} else if (nodeNameEquals(e, SERVICE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseService(e, false);
}
} else {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseCustomElement(e, enclosingComponent);
}
}
}
if (listenerComponent == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element must be set");
}
listener.setListenerComponent((Target) listenerComponent);
return listener;
}
private ComponentMetadata parseReference(Element element, boolean topElement) {
ReferenceMetadataImpl reference = new ReferenceMetadataImpl();
if (topElement) {
reference.setId(getId(element));
}
parseReference(element, reference, topElement);
String timeout = element.hasAttribute(TIMEOUT_ATTRIBUTE) ? element.getAttribute(TIMEOUT_ATTRIBUTE) : this.defaultTimeout;
try {
reference.setTimeout(Long.parseLong(timeout));
} catch (NumberFormatException e) {
throw new ComponentDefinitionException("Attribute " + TIMEOUT_ATTRIBUTE + " must be a valid long (was: " + timeout + ")");
}
ComponentMetadata r = reference;
// Parse custom attributes
r = handleCustomAttributes(element.getAttributes(), r);
// Parse custom elements;
r = handleCustomElements(element, r);
return r;
}
public String getDefaultTimeout() {
return defaultTimeout;
}
public String getDefaultAvailability() {
return defaultAvailability;
}
public String getDefaultActivation() {
return defaultActivation;
}
private ComponentMetadata parseRefList(Element element, boolean topElement) {
ReferenceListMetadataImpl references = new ReferenceListMetadataImpl();
if (topElement) {
references.setId(getId(element));
}
if (element.hasAttribute(MEMBER_TYPE_ATTRIBUTE)) {
String memberType = element.getAttribute(MEMBER_TYPE_ATTRIBUTE);
if (USE_SERVICE_OBJECT.equals(memberType)) {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_OBJECT);
} else if (USE_SERVICE_REFERENCE.equals(memberType)) {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_REFERENCE);
}
} else {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_OBJECT);
}
parseReference(element, references, topElement);
ComponentMetadata r = references;
// Parse custom attributes
r = handleCustomAttributes(element.getAttributes(), r);
// Parse custom elements;
r = handleCustomElements(element, r);
return r;
}
private void parseReference(Element element, ServiceReferenceMetadataImpl reference, boolean topElement) {
// Parse attributes
if (topElement) {
reference.setActivation(parseActivation(element));
} else {
reference.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
reference.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
if (element.hasAttribute(INTERFACE_ATTRIBUTE)) {
reference.setInterface(element.getAttribute(INTERFACE_ATTRIBUTE));
}
if (element.hasAttribute(FILTER_ATTRIBUTE)) {
reference.setFilter(element.getAttribute(FILTER_ATTRIBUTE));
}
if (element.hasAttribute(COMPONENT_NAME_ATTRIBUTE)) {
reference.setComponentName(element.getAttribute(COMPONENT_NAME_ATTRIBUTE));
}
String availability = element.hasAttribute(AVAILABILITY_ATTRIBUTE) ? element.getAttribute(AVAILABILITY_ATTRIBUTE) : defaultAvailability;
if (AVAILABILITY_MANDATORY.equals(availability)) {
reference.setAvailability(ServiceReferenceMetadata.AVAILABILITY_MANDATORY);
} else if (AVAILABILITY_OPTIONAL.equals(availability)) {
reference.setAvailability(ServiceReferenceMetadata.AVAILABILITY_OPTIONAL);
} else {
throw new ComponentDefinitionException("Illegal value for " + AVAILABILITY_ATTRIBUTE + " attribute: " + availability);
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REFERENCE_LISTENER_ELEMENT)) {
reference.addServiceListener(parseServiceListener(e, reference));
}
}
}
}
}
private ReferenceListener parseServiceListener(Element element, ComponentMetadata enclosingComponent) {
ReferenceListenerImpl listener = new ReferenceListenerImpl();
Metadata listenerComponent = null;
// Parse attributes
if (element.hasAttribute(REF_ATTRIBUTE)) {
listenerComponent = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
String bindMethodName = null;
String unbindMethodName = null;
if (element.hasAttribute(BIND_METHOD_ATTRIBUTE)) {
bindMethodName = element.getAttribute(BIND_METHOD_ATTRIBUTE);
listener.setBindMethod(bindMethodName);
}
if (element.hasAttribute(UNBIND_METHOD_ATTRIBUTE)) {
unbindMethodName = element.getAttribute(UNBIND_METHOD_ATTRIBUTE);
listener.setUnbindMethod(unbindMethodName);
}
if (bindMethodName == null && unbindMethodName == null) {
throw new ComponentDefinitionException("One of " + BIND_METHOD_ATTRIBUTE + " or " + UNBIND_METHOD_ATTRIBUTE + " must be set");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REF_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
listenerComponent = new RefMetadataImpl(component);
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseBeanMetadata(e, false);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseReference(e, false);
} else if (nodeNameEquals(e, SERVICE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseService(e, false);
}
} else {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseCustomElement(e, enclosingComponent);
}
}
}
if (listenerComponent == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element must be set");
}
listener.setListenerComponent((Target) listenerComponent);
return listener;
}
public List<String> parseInterfaceNames(Element element) {
List<String> interfaceNames = new ArrayList<String>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, VALUE_ELEMENT)) {
String v = getTextValue(e).trim();
if (interfaceNames.contains(v)) {
throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice");
}
interfaceNames.add(getTextValue(e));
} else {
throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element");
}
}
}
return interfaceNames;
}
private Metadata parseArgumentOrPropertyValue(Element element, ComponentMetadata enclosingComponent) {
Metadata [] values = new Metadata[3];
if (element.hasAttribute(REF_ATTRIBUTE)) {
values[0] = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
if (element.hasAttribute(VALUE_ATTRIBUTE)) {
values[1] = new ValueMetadataImpl(element.getAttribute(VALUE_ATTRIBUTE));
}
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(node.getNamespaceURI()) && nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
// Ignore description elements
} else {
values[2] = parseValueGroup(e, enclosingComponent, null, true);
break;
}
}
}
Metadata value = null;
for (Metadata v : values) {
if (v != null) {
if (value == null) {
value = v;
} else {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + VALUE_ATTRIBUTE + " attribute or sub element must be set");
}
}
}
if (value == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + VALUE_ATTRIBUTE + " attribute or sub element must be set");
}
return value;
}
private Metadata parseValueGroup(Element element, ComponentMetadata enclosingComponent, String collectionType, boolean allowNull) {
if (isBlueprintNamespace(element.getNamespaceURI())) {
if (nodeNameEquals(element, BEAN_ELEMENT)) {
return parseBeanMetadata(element, false);
} else if (nodeNameEquals(element, REFERENCE_ELEMENT)) {
return parseReference(element, false);
} else if (nodeNameEquals(element, SERVICE_ELEMENT)) {
return parseService(element, false);
} else if (nodeNameEquals(element, REFERENCE_LIST_ELEMENT) ) {
return parseRefList(element, false);
} else if (nodeNameEquals(element, NULL_ELEMENT) && allowNull) {
return NullMetadata.NULL;
} else if (nodeNameEquals(element, VALUE_ELEMENT)) {
return parseValue(element, collectionType);
} else if (nodeNameEquals(element, REF_ELEMENT)) {
return parseRef(element);
} else if (nodeNameEquals(element, IDREF_ELEMENT)) {
return parseIdRef(element);
} else if (nodeNameEquals(element, LIST_ELEMENT)) {
return parseList(element, enclosingComponent);
} else if (nodeNameEquals(element, SET_ELEMENT)) {
return parseSet(element, enclosingComponent);
} else if (nodeNameEquals(element, MAP_ELEMENT)) {
return parseMap(element, enclosingComponent);
} else if (nodeNameEquals(element, PROPS_ELEMENT)) {
return parseProps(element);
} else if (nodeNameEquals(element, ARRAY_ELEMENT)) {
return parseArray(element, enclosingComponent);
} else {
throw new ComponentDefinitionException("Unknown blueprint element " + element.getNodeName());
}
} else {
return parseCustomElement(element, enclosingComponent);
}
}
private ValueMetadata parseValue(Element element, String collectionType) {
String type;
if (element.hasAttribute(TYPE_ATTRIBUTE)) {
type = element.getAttribute(TYPE_ATTRIBUTE);
} else {
type = collectionType;
}
return new ValueMetadataImpl(getTextValue(element), type);
}
private RefMetadata parseRef(Element element) {
String component = element.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
return new RefMetadataImpl(component);
}
private Metadata parseIdRef(Element element) {
String component = element.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + IDREF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
return new IdRefMetadataImpl(component);
}
private int parseActivation(Element element) {
String initialization = element.hasAttribute(ACTIVATION_ATTRIBUTE) ? element.getAttribute(ACTIVATION_ATTRIBUTE) : defaultActivation;
if (ACTIVATION_EAGER.equals(initialization)) {
return ComponentMetadata.ACTIVATION_EAGER;
} else if (ACTIVATION_LAZY.equals(initialization)) {
return ComponentMetadata.ACTIVATION_LAZY;
} else {
throw new ComponentDefinitionException("Attribute " + ACTIVATION_ATTRIBUTE + " must be equal to " + ACTIVATION_EAGER + " or " + ACTIVATION_LAZY);
}
}
private ComponentMetadata handleCustomAttributes(NamedNodeMap attributes, ComponentMetadata enclosingComponent) {
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
//attr is custom if it has a namespace, and it isnt blueprint, or the xmlns ns.
//blueprint ns would be an error, as blueprint attrs are unqualified.
if (node instanceof Attr &&
node.getNamespaceURI() != null &&
!isBlueprintNamespace(node.getNamespaceURI()) &&
!isIgnorableAttributeNamespace(node.getNamespaceURI()) ) {
enclosingComponent = decorateCustomNode(node, enclosingComponent);
}
}
}
return enclosingComponent;
}
private ComponentMetadata handleCustomElements(Element element, ComponentMetadata enclosingComponent) {
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
if (!isBlueprintNamespace(node.getNamespaceURI())) {
enclosingComponent = decorateCustomNode(node, enclosingComponent);
}
}
}
return enclosingComponent;
}
private ComponentMetadata decorateCustomNode(Node node, ComponentMetadata enclosingComponent) {
NamespaceHandler handler = getNamespaceHandler(node);
ParserContextImpl context = new ParserContextImpl(this, registry, enclosingComponent, node);
return handler.decorate(node, enclosingComponent, context);
}
private Metadata parseCustomElement(Element element, ComponentMetadata enclosingComponent) {
NamespaceHandler handler = getNamespaceHandler(element);
ParserContextImpl context = new ParserContextImpl(this, registry, enclosingComponent, element);
return handler.parse(element, context);
}
private NamespaceHandler getNamespaceHandler(Node node) {
URI ns = URI.create(node.getNamespaceURI());
return getNamespaceHandler(ns);
}
public NamespaceHandler getNamespaceHandler(URI uri) {
if (handlers == null) {
throw new ComponentDefinitionException("Unsupported node (namespace handler registry is not set): " + uri);
}
NamespaceHandler handler = this.handlers.getNamespaceHandler(uri);
if (handler == null) {
if (ignoreUnknownNamespaces) {
return missingNamespace;
}
throw new ComponentDefinitionException("Unsupported node namespace: " + uri);
}
return handler;
}
public String generateId() {
String id;
do {
id = "." + idPrefix + ++idCounter;
} while (ids.contains(id));
ids.add(id);
return id;
}
public String getId(Element element) {
String id;
if (element.hasAttribute(ID_ATTRIBUTE)) {
id = element.getAttribute(ID_ATTRIBUTE);
ids.add(id);
} else {
id = generateId();
}
return id;
}
public static boolean isBlueprintNamespace(String ns) {
return BLUEPRINT_NAMESPACE.equals(ns);
}
/**
* Test if this namespace uri does not require a Namespace Handler.<p>
*
* @param ns URI to be tested.
* @return true if the uri does not require a namespace handler.
*/
public static boolean isIgnorableAttributeNamespace(String ns) {
return XMLConstants.RELAXNG_NS_URI.equals(ns) ||
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI.equals(ns) ||
XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(ns) ||
XMLConstants.W3C_XPATH_DATATYPE_NS_URI.equals(ns) ||
XMLConstants.W3C_XPATH_DATATYPE_NS_URI.equals(ns) ||
XMLConstants.XML_DTD_NS_URI.equals(ns) ||
XMLConstants.XML_NS_URI.equals(ns) ||
XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(ns);
}
private static boolean nodeNameEquals(Node node, String name) {
return (name.equals(node.getNodeName()) || name.equals(node.getLocalName()));
}
private static List<String> parseList(String list) {
String[] items = list.split(" ");
List<String> set = new ArrayList<String>();
for (String item : items) {
item = item.trim();
if (item.length() > 0) {
set.add(item);
}
}
return set;
}
private static String getTextValue(Element element) {
StringBuffer value = new StringBuffer();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
value.append(item.getNodeValue());
}
}
return value.toString();
}
private static DocumentBuilderFactory getDocumentBuilderFactory() {
if (documentBuilderFactory == null) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
try {
dbf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
} catch (ParserConfigurationException ex) {
throw new ComponentDefinitionException("Unable to create the document builder", ex);
}
documentBuilderFactory = dbf;
}
return documentBuilderFactory;
}
}
| 9,611 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/parser/ComponentDefinitionRegistryImpl.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.blueprint.parser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.ComponentNameAlreadyInUseException;
import org.apache.aries.blueprint.Interceptor;
import org.apache.aries.blueprint.reflect.PassThroughMetadataImpl;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Target;
/**
* ComponentDefinitionRegistry implementation.
*
* This implementation uses concurrent lists and maps to store components and converters metadata
* to allow its use by concurrent threads.
*
* @version $Rev$, $Date$
*/
public class ComponentDefinitionRegistryImpl implements ComponentDefinitionRegistry {
private final Map<String, ComponentMetadata> components;
private final List<Target> typeConverters;
private final Map<ComponentMetadata, List<Interceptor>> interceptors;
public ComponentDefinitionRegistryImpl() {
// Use a linked hash map to keep the declaration order
components = Collections.synchronizedMap(new LinkedHashMap<String, ComponentMetadata>());
typeConverters = new CopyOnWriteArrayList<Target>();
interceptors = Collections.synchronizedMap(new HashMap<ComponentMetadata, List<Interceptor>>());
}
public void reset() {
components.clear();
typeConverters.clear();
interceptors.clear();
}
public boolean containsComponentDefinition(String name) {
return components.containsKey(name);
}
public ComponentMetadata getComponentDefinition(String name) {
return components.get(name);
}
public Set<String> getComponentDefinitionNames() {
return Collections.unmodifiableSet(components.keySet());
}
public void registerComponentDefinition(ComponentMetadata component) {
String id = component.getId();
if (id == null) {
// TODO: should we generate a unique name?
throw new IllegalArgumentException("Component must have a valid id");
}
if (id.startsWith("blueprint") && !(component instanceof PassThroughMetadataImpl)) {
// TODO: log a warning
}
// TODO: perform other validation: scope, class/runtimeClass/factoryMethod, etc...
if (components.containsKey(id)) {
throw new ComponentNameAlreadyInUseException(id);
}
components.put(id, component);
}
public void removeComponentDefinition(String name) {
ComponentMetadata removed = components.remove(name);
if(removed!=null){
interceptors.remove(removed);
}
}
public void registerTypeConverter(Target component) {
typeConverters.add(component);
if (component instanceof ComponentMetadata) {
registerComponentDefinition((ComponentMetadata) component);
}
}
public List<Target> getTypeConverters() {
return typeConverters;
}
public void registerInterceptorWithComponent(ComponentMetadata component, Interceptor interceptor) {
if(interceptor!=null){
List<Interceptor> componentInterceptorList = interceptors.get(component);
if(componentInterceptorList==null){
componentInterceptorList = new ArrayList<Interceptor>();
interceptors.put(component, componentInterceptorList);
}
if(!componentInterceptorList.contains(interceptor)){
componentInterceptorList.add(interceptor);
Collections.sort(componentInterceptorList, new Comparator<Interceptor>(){
public int compare(Interceptor object1, Interceptor object2) {
//invert the order so higher ranks are sorted 1st
return object2.getRank() - object1.getRank();
}
});
}
}
}
public List<Interceptor> getInterceptors(ComponentMetadata component) {
List<Interceptor> result = interceptors.get(component);
return (result == null) ? Collections.<Interceptor>emptyList() : result;
}
}
| 9,612 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/parser/NamespaceHandlerSet.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.blueprint.parser;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import javax.xml.validation.Schema;
import org.apache.aries.blueprint.NamespaceHandler;
import org.xml.sax.SAXException;
/**
* Interface used to managed a set of namespace handlers
*/
public interface NamespaceHandlerSet {
Set<URI> getNamespaces();
boolean isComplete();
/**
* Retrieve the NamespaceHandler to use for the given namespace
*
* @return the NamespaceHandler to use or <code>null</code> if none is available at this time
*/
NamespaceHandler getNamespaceHandler(URI namespace);
/**
* Obtain a schema to validate the XML for the given list of namespaces
*
* @return the schema to use to validate the XML
*/
Schema getSchema() throws SAXException, IOException;
/**
* Obtain a schema to validate the XML for the given list of namespaces
*
* @return the schema to use to validate the XML
*/
Schema getSchema(Map<String, String> locations) throws SAXException, IOException;
/**
* Add a new Listener to be called when namespace handlers are registerd or unregistered
*
* @param listener the listener to register
*/
void addListener(Listener listener);
/**
* Remove a previously registered Listener
*
* @param listener the listener to unregister
*/
void removeListener(Listener listener);
/**
* Destroy this handler set
*/
void destroy();
/**
* Interface used to listen to registered or unregistered namespace handlers.
*
* @see NamespaceHandlerSet#addListener(org.apache.aries.blueprint.container.NamespaceHandlerRegistry.Listener)
* @see NamespaceHandlerSet#removeListener(org.apache.aries.blueprint.container.NamespaceHandlerRegistry.Listener)
*/
interface Listener {
/**
* Called when a NamespaceHandler has been registered for the specified URI.
*
* @param uri the URI of the newly registered namespace handler
*/
void namespaceHandlerRegistered(URI uri);
/**
* Called when a NamespaceHandler has been unregistered for the specified URI.
*
* @param uri the URI of the newly unregistered namespace handler
*/
void namespaceHandlerUnregistered(URI uri);
}
} | 9,613 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/parser/ParserContextImpl.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.blueprint.parser;
import java.net.URI;
import java.util.Collections;
import java.util.Set;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* A simple ParserContext implementation.
*
* This class is supposed to be short lived and only used for calling a given namespace handler.
*
* @version $Rev: 896324 $, $Date: 2010-01-06 06:05:04 +0000 (Wed, 06 Jan 2010) $
*/
public class ParserContextImpl implements ParserContext {
private final Parser parser;
private final ComponentDefinitionRegistry componentDefinitionRegistry;
private final ComponentMetadata enclosingComponent;
private final Node sourceNode;
public ParserContextImpl(Parser parser,
ComponentDefinitionRegistry componentDefinitionRegistry,
ComponentMetadata enclosingComponent,
Node sourceNode) {
this.parser = parser;
this.componentDefinitionRegistry = componentDefinitionRegistry;
this.enclosingComponent = enclosingComponent;
this.sourceNode = sourceNode;
}
public ComponentDefinitionRegistry getComponentDefinitionRegistry() {
return componentDefinitionRegistry;
}
public ComponentMetadata getEnclosingComponent() {
return enclosingComponent;
}
public Node getSourceNode() {
return sourceNode;
}
public <T extends Metadata> T createMetadata(Class<T> type) {
return MetadataUtil.createMetadata(type);
}
public <T> T parseElement(Class<T> type, ComponentMetadata enclosingComponent, Element element) {
return parser.parseElement(type, enclosingComponent, element);
}
public Parser getParser() {
return parser;
}
public String generateId() {
return parser.generateId();
}
public String getDefaultActivation() {
return parser.getDefaultActivation();
}
public String getDefaultAvailability() {
return parser.getDefaultAvailability();
}
public String getDefaultTimeout() {
return parser.getDefaultTimeout();
}
@Override
public Set<URI> getNamespaces() {
return Collections.unmodifiableSet(parser.getNamespaces());
}
@Override
public NamespaceHandler getNamespaceHandler(URI namespaceUri) {
return parser.getNamespaceHandler(namespaceUri);
}
}
| 9,614 |
0 | Create_ds/aries/blueprint/blueprint-spring-camel/src/main/java/org/apache/camel | Create_ds/aries/blueprint/blueprint-spring-camel/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.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.camel.osgi;
import org.apache.camel.core.osgi.OsgiCamelContextPublisher;
import org.apache.camel.core.osgi.OsgiEventAdminNotifier;
import org.apache.camel.spring.SpringCamelContext;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "camelContext")
@XmlAccessorType(XmlAccessType.FIELD)
public class CamelContextFactoryBean extends org.apache.camel.spring.CamelContextFactoryBean {
private static final Logger LOG = LoggerFactory.getLogger(CamelContextFactoryBean.class);
public BundleContext getBundleContext() {
return (BundleContext) getApplicationContext().getBean("blueprintBundleContext");
}
protected SpringCamelContext createContext() {
SpringCamelContext ctx = newCamelContext();
// only set the name if its explicit (Camel will auto assign name if none explicit set)
if (!isImplicitId()) {
ctx.setName(getId());
}
return ctx;
}
protected SpringCamelContext newCamelContext() {
return new OsgiSpringCamelContext(getApplicationContext(), getBundleContext());
}
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
BundleContext bundleContext = getBundleContext();
getContext().getManagementStrategy().addEventNotifier(new OsgiCamelContextPublisher(bundleContext));
try {
getClass().getClassLoader().loadClass("org.osgi.service.event.EventAdmin");
getContext().getManagementStrategy().addEventNotifier(new OsgiEventAdminNotifier(bundleContext));
} catch (Throwable t) {
// Ignore, if the EventAdmin package is not available, just don't use it
LOG.debug("EventAdmin package is not available, just don't use it");
}
}
}
| 9,615 |
0 | Create_ds/aries/blueprint/blueprint-spring-camel/src/main/java/org/apache/camel | Create_ds/aries/blueprint/blueprint-spring-camel/src/main/java/org/apache/camel/osgi/Activator.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.camel.osgi;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
public class Activator {
public static Bundle getBundle() {
return FrameworkUtil.getBundle(Activator.class);
}
}
| 9,616 |
0 | Create_ds/aries/blueprint/blueprint-spring-camel/src/main/java/org/apache/camel | Create_ds/aries/blueprint/blueprint-spring-camel/src/main/java/org/apache/camel/osgi/OsgiSpringCamelContext.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.camel.osgi;
import org.apache.camel.TypeConverter;
import org.apache.camel.core.osgi.OsgiCamelContextHelper;
import org.apache.camel.core.osgi.OsgiFactoryFinderResolver;
import org.apache.camel.core.osgi.OsgiTypeConverter;
import org.apache.camel.core.osgi.utils.BundleContextUtils;
import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.Registry;
import org.apache.camel.spring.SpringCamelContext;
import org.osgi.framework.BundleContext;
import org.springframework.context.ApplicationContext;
public class OsgiSpringCamelContext extends SpringCamelContext {
private final BundleContext bundleContext;
public OsgiSpringCamelContext(ApplicationContext applicationContext, BundleContext bundleContext) {
super(applicationContext);
this.bundleContext = bundleContext;
OsgiCamelContextHelper.osgiUpdate(this, bundleContext);
}
@Override
protected TypeConverter createTypeConverter() {
// CAMEL-3614: make sure we use a bundle context which imports org.apache.camel.impl.converter package
BundleContext ctx = BundleContextUtils.getBundleContext(getClass());
if (ctx == null) {
ctx = bundleContext;
}
FactoryFinder finder = new OsgiFactoryFinderResolver(bundleContext).resolveDefaultFactoryFinder(getClassResolver());
return new OsgiTypeConverter(ctx, this, getInjector(), finder);
}
@Override
protected Registry createRegistry() {
return OsgiCamelContextHelper.wrapRegistry(this, super.createRegistry(), bundleContext);
}
@Override
public void setName(String name) {
super.setName(name);
// in OSGi prefix the bundle id to the management name so it will be unique in the JVM
// and also nicely sorted based on bundle id
super.setManagementName(bundleContext.getBundle().getBundleId() + "-" + name);
}
}
| 9,617 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/test/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/test/java/org/apache/aries/blueprint/compendium/cm/Helper.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.blueprint.compendium.cm;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.jar.JarInputStream;
import de.kalpatec.pojosr.framework.PojoServiceRegistryFactoryImpl;
import de.kalpatec.pojosr.framework.launch.BundleDescriptor;
import de.kalpatec.pojosr.framework.launch.ClasspathScanner;
import de.kalpatec.pojosr.framework.launch.PojoServiceRegistry;
import de.kalpatec.pojosr.framework.launch.PojoServiceRegistryFactory;
import org.ops4j.pax.swissbox.tinybundles.core.TinyBundle;
import org.ops4j.pax.swissbox.tinybundles.core.TinyBundles;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public final class Helper {
public static final long DEFAULT_TIMEOUT = 30000;
public static final String BUNDLE_FILTER = "(Bundle-SymbolicName=*)";
public static final String BUNDLE_VERSION = "1.0.0";
private static final transient Logger LOG = LoggerFactory.getLogger(Helper.class);
private Helper() {
}
public static BundleContext createBundleContext(String name, String descriptors, boolean includeTestBundle) throws Exception {
return createBundleContext(name, descriptors, includeTestBundle, BUNDLE_FILTER, BUNDLE_VERSION);
}
public static BundleContext createBundleContext(String name, String descriptors, boolean includeTestBundle,
String bundleFilter, String testBundleVersion) throws Exception {
TinyBundle bundle = null;
if (includeTestBundle) {
// add ourselves as a bundle
bundle = createTestBundle(name, testBundleVersion, descriptors);
}
return createBundleContext(bundleFilter, new TinyBundle[] { bundle });
}
public static BundleContext createBundleContext(String bundleFilter, TinyBundle[] testBundles) throws Exception {
deleteDirectory("target/bundles");
createDirectory("target/bundles");
// ensure pojosr stores bundles in an unique target directory
System.setProperty("org.osgi.framework.storage", "target/bundles/" + System.currentTimeMillis());
// get the bundles
List<BundleDescriptor> bundles = getBundleDescriptors(bundleFilter);
// Add the test bundles at the beginning of the list so that they get started first.
// The reason is that the bundle tracker used by blueprint does not work well
// with pojosr because it does not support bundle hooks, so events are lost.
if (testBundles != null) {
for (TinyBundle bundle : testBundles) {
File tmp = File.createTempFile("test-", ".jar", new File("target/bundles/"));
tmp.delete();
bundles.add(0, getBundleDescriptor(tmp.getPath(), bundle));
}
}
if (LOG.isDebugEnabled()) {
for (int i = 0; i < bundles.size(); i++) {
BundleDescriptor desc = bundles.get(i);
LOG.debug("Bundle #{} -> {}", i, desc);
}
}
// setup pojosr to use our bundles
Map<String, List<BundleDescriptor>> config = new HashMap<String, List<BundleDescriptor>>();
config.put(PojoServiceRegistryFactory.BUNDLE_DESCRIPTORS, bundles);
// create pojorsr osgi service registry
PojoServiceRegistry reg = new PojoServiceRegistryFactoryImpl().newPojoServiceRegistry(config);
return reg.getBundleContext();
}
public static void disposeBundleContext(BundleContext bundleContext) throws BundleException {
try {
if (bundleContext != null) {
bundleContext.getBundle().stop();
}
} finally {
System.clearProperty("org.osgi.framework.storage");
}
}
public static <T> T getOsgiService(BundleContext bundleContext, Class<T> type, long timeout) {
return getOsgiService(bundleContext, type, null, timeout);
}
public static <T> T getOsgiService(BundleContext bundleContext, Class<T> type) {
return getOsgiService(bundleContext, type, null, DEFAULT_TIMEOUT);
}
public static <T> T getOsgiService(BundleContext bundleContext, Class<T> type, String filter) {
return getOsgiService(bundleContext, type, filter, DEFAULT_TIMEOUT);
}
public static <T> ServiceReference getOsgiServiceReference(BundleContext bundleContext, Class<T> type, String filter, long timeout) {
ServiceTracker tracker = null;
try {
String flt;
if (filter != null) {
if (filter.startsWith("(")) {
flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")";
} else {
flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))";
}
} else {
flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")";
}
Filter osgiFilter = FrameworkUtil.createFilter(flt);
tracker = new ServiceTracker(bundleContext, osgiFilter, null);
tracker.open(true);
// Note that the tracker is not closed to keep the reference
// This is buggy, as the service reference may change i think
Object svc = tracker.waitForService(timeout);
if (svc == null) {
Dictionary<?, ?> dic = bundleContext.getBundle().getHeaders();
System.err.println("Test bundle headers: " + explode(dic));
for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, null))) {
System.err.println("ServiceReference: " + ref + ", bundle: " + ref.getBundle() + ", symbolicName: " + ref.getBundle().getSymbolicName());
}
for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, flt))) {
System.err.println("Filtered ServiceReference: " + ref + ", bundle: " + ref.getBundle() + ", symbolicName: " + ref.getBundle().getSymbolicName());
}
throw new RuntimeException("Gave up waiting for service " + flt);
}
return tracker.getServiceReference();
} catch (InvalidSyntaxException e) {
throw new IllegalArgumentException("Invalid filter", e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static <T> T getOsgiService(BundleContext bundleContext, Class<T> type, String filter, long timeout) {
ServiceTracker tracker = null;
try {
String flt;
if (filter != null) {
if (filter.startsWith("(")) {
flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")";
} else {
flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))";
}
} else {
flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")";
}
Filter osgiFilter = FrameworkUtil.createFilter(flt);
tracker = new ServiceTracker(bundleContext, osgiFilter, null);
tracker.open(true);
// Note that the tracker is not closed to keep the reference
// This is buggy, as the service reference may change i think
Object svc = tracker.waitForService(timeout);
if (svc == null) {
Dictionary<?, ?> dic = bundleContext.getBundle().getHeaders();
System.err.println("Test bundle headers: " + explode(dic));
for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, null))) {
System.err.println("ServiceReference: " + ref + ", bundle: " + ref.getBundle() + ", symbolicName: " + ref.getBundle().getSymbolicName());
}
for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, flt))) {
System.err.println("Filtered ServiceReference: " + ref + ", bundle: " + ref.getBundle() + ", symbolicName: " + ref.getBundle().getSymbolicName());
}
throw new RuntimeException("Gave up waiting for service " + flt);
}
return type.cast(svc);
} catch (InvalidSyntaxException e) {
throw new IllegalArgumentException("Invalid filter", e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
protected static TinyBundle createTestBundle(String name, String version, String descriptors) throws FileNotFoundException, MalformedURLException {
TinyBundle bundle = TinyBundles.newBundle();
for (URL url : getBlueprintDescriptors(descriptors)) {
LOG.info("Using Blueprint XML file: " + url.getFile());
bundle.add("OSGI-INF/blueprint/blueprint-" + url.getFile().replace("/", "-"), url);
}
bundle.set("Manifest-Version", "2")
.set("Bundle-ManifestVersion", "2")
.set("Bundle-SymbolicName", name)
.set("Bundle-Version", version);
return bundle;
}
/**
* Explode the dictionary into a <code>,</code> delimited list of <code>key=value</code> pairs.
*/
private static String explode(Dictionary<?, ?> dictionary) {
Enumeration<?> keys = dictionary.keys();
StringBuffer result = new StringBuffer();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
result.append(String.format("%s=%s", key, dictionary.get(key)));
if (keys.hasMoreElements()) {
result.append(", ");
}
}
return result.toString();
}
/**
* Provides an iterable collection of references, even if the original array is <code>null</code>.
*/
private static Collection<ServiceReference> asCollection(ServiceReference[] references) {
return references == null ? new ArrayList<ServiceReference>(0) : Arrays.asList(references);
}
/**
* Gets list of bundle descriptors.
* @param bundleFilter Filter expression for OSGI bundles.
*
* @return List pointers to OSGi bundles.
* @throws Exception If looking up the bundles fails.
*/
private static List<BundleDescriptor> getBundleDescriptors(final String bundleFilter) throws Exception {
return new ClasspathScanner().scanForBundles(bundleFilter);
}
/**
* Gets the bundle descriptors as {@link URL} resources.
*
* @param descriptors the bundle descriptors, can be separated by comma
* @return the bundle descriptors.
* @throws FileNotFoundException is thrown if a bundle descriptor cannot be found
*/
private static Collection<URL> getBlueprintDescriptors(String descriptors) throws FileNotFoundException, MalformedURLException {
List<URL> answer = new ArrayList<URL>();
String descriptor = descriptors;
if (descriptor != null) {
// there may be more resources separated by comma
Iterator<Object> it = createIterator(descriptor);
while (it.hasNext()) {
String s = (String) it.next();
LOG.trace("Resource descriptor: {}", s);
// remove leading / to be able to load resource from the classpath
s = stripLeadingSeparator(s);
// if there is wildcards for *.xml then we need to find the urls from the package
if (s.endsWith("*.xml")) {
String packageName = s.substring(0, s.length() - 5);
// remove trailing / to be able to load resource from the classpath
Enumeration<URL> urls = loadResourcesAsURL(packageName);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
File dir = new File(url.getFile());
if (dir.isDirectory()) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.exists() && file.getName().endsWith(".xml")) {
String name = packageName + file.getName();
LOG.debug("Resolving resource: {}", name);
URL xmlUrl = loadResourceAsURL(name);
if (xmlUrl != null) {
answer.add(xmlUrl);
}
}
}
}
}
}
} else {
LOG.debug("Resolving resource: {}", s);
URL url = resolveMandatoryResourceAsUrl(s);
if (url == null) {
throw new FileNotFoundException("Resource " + s + " not found");
}
answer.add(url);
}
}
} else {
throw new IllegalArgumentException("No bundle descriptor configured. Override getBlueprintDescriptor() or getBlueprintDescriptors() method");
}
if (answer.isEmpty()) {
throw new IllegalArgumentException("Cannot find any resources in classpath from descriptor " + descriptors);
}
return answer;
}
private static BundleDescriptor getBundleDescriptor(String path, TinyBundle bundle) throws Exception {
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file, true);
try {
copy(bundle.build(), fos);
} finally {
close(fos);
}
FileInputStream fis = null;
JarInputStream jis = null;
try {
fis = new FileInputStream(file);
jis = new JarInputStream(fis);
Map<String, String> headers = new HashMap<String, String>();
for (Map.Entry<Object, Object> entry : jis.getManifest().getMainAttributes().entrySet()) {
headers.put(entry.getKey().toString(), entry.getValue().toString());
}
return new BundleDescriptor(
bundle.getClass().getClassLoader(),
new URL("jar:" + file.toURI().toString() + "!/"),
headers);
} finally {
close(fis, jis);
}
}
/**
* Closes the given resource if it is available, logging any closing exceptions to the given log.
*
* @param closeable the object to close
* @param name the name of the resource
* @param log the log to use when reporting closure warnings, will use this class's own {@link Logger} if <tt>log == null</tt>
*/
public static void close(Closeable closeable, String name, Logger log) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
if (log == null) {
// then fallback to use the own Logger
log = LOG;
}
if (name != null) {
log.warn("Cannot close: " + name + ". Reason: " + e.getMessage(), e);
} else {
log.warn("Cannot close. Reason: " + e.getMessage(), e);
}
}
}
}
/**
* Closes the given resource if it is available.
*
* @param closeable the object to close
* @param name the name of the resource
*/
public static void close(Closeable closeable, String name) {
close(closeable, name, LOG);
}
/**
* Closes the given resource if it is available.
*
* @param closeable the object to close
*/
public static void close(Closeable closeable) {
close(closeable, null, LOG);
}
/**
* Closes the given resources if they are available.
*
* @param closeables the objects to close
*/
public static void close(Closeable... closeables) {
for (Closeable closeable : closeables) {
close(closeable);
}
}
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final String DEFAULT_DELIMITER = ",";
public static int copy(InputStream input, OutputStream output) throws IOException {
return copy(input, output, DEFAULT_BUFFER_SIZE);
}
public static int copy(final InputStream input, final OutputStream output, int bufferSize) throws IOException {
int avail = input.available();
if (avail > 262144) {
avail = 262144;
}
if (avail > bufferSize) {
bufferSize = avail;
}
final byte[] buffer = new byte[bufferSize];
int n = input.read(buffer);
int total = 0;
while (-1 != n) {
output.write(buffer, 0, n);
total += n;
n = input.read(buffer);
}
output.flush();
return total;
}
/**
* Creates an iterator over the value if the value is a collection, an
* Object[], a String with values separated by comma,
* or a primitive type array; otherwise to simplify the caller's code,
* we just create a singleton collection iterator over a single value
* <p/>
* Will default use comma for String separating String values.
* This method does <b>not</b> allow empty values
*
* @param value the value
* @return the iterator
*/
public static Iterator<Object> createIterator(Object value) {
return createIterator(value, DEFAULT_DELIMITER);
}
/**
* Creates an iterator over the value if the value is a collection, an
* Object[], a String with values separated by the given delimiter,
* or a primitive type array; otherwise to simplify the caller's
* code, we just create a singleton collection iterator over a single value
* <p/>
* This method does <b>not</b> allow empty values
*
* @param value the value
* @param delimiter delimiter for separating String values
* @return the iterator
*/
public static Iterator<Object> createIterator(Object value, String delimiter) {
return createIterator(value, delimiter, false);
}
/**
* Creates an iterator over the value if the value is a collection, an
* Object[], a String with values separated by the given delimiter,
* or a primitive type array; otherwise to simplify the caller's
* code, we just create a singleton collection iterator over a single value
*
* @param value the value
* @param delimiter delimiter for separating String values
* @param allowEmptyValues whether to allow empty values
* @return the iterator
*/
@SuppressWarnings("unchecked")
public static Iterator<Object> createIterator(Object value, String delimiter, final boolean allowEmptyValues) {
if (value == null) {
return Collections.emptyList().iterator();
} else if (value instanceof Iterator) {
return (Iterator<Object>) value;
} else if (value instanceof Iterable) {
return ((Iterable<Object>) value).iterator();
} else if (value.getClass().isArray()) {
// TODO we should handle primitive array types?
List<Object> list = Arrays.asList((Object[]) value);
return list.iterator();
} else if (value instanceof NodeList) {
// lets iterate through DOM results after performing XPaths
final NodeList nodeList = (NodeList) value;
return cast(new Iterator<Node>() {
int idx = -1;
public boolean hasNext() {
return (idx + 1) < nodeList.getLength();
}
public Node next() {
idx++;
return nodeList.item(idx);
}
public void remove() {
throw new UnsupportedOperationException();
}
});
} else if (value instanceof String) {
final String s = (String) value;
// this code is optimized to only use a Scanner if needed, eg there is a delimiter
if (delimiter != null && s.contains(delimiter)) {
// use a scanner if it contains the delimiter
Scanner scanner = new Scanner((String) value);
if (DEFAULT_DELIMITER.equals(delimiter)) {
// we use the default delimiter which is a comma, then cater for bean expressions with OGNL
// which may have balanced parentheses pairs as well.
// if the value contains parentheses we need to balance those, to avoid iterating
// in the middle of parentheses pair, so use this regular expression (a bit hard to read)
// the regexp will split by comma, but honor parentheses pair that may include commas
// as well, eg if value = "bean=foo?method=killer(a,b),bean=bar?method=great(a,b)"
// then the regexp will split that into two:
// -> bean=foo?method=killer(a,b)
// -> bean=bar?method=great(a,b)
// http://stackoverflow.com/questions/1516090/splitting-a-title-into-separate-parts
delimiter = ",(?!(?:[^\\(,]|[^\\)],[^\\)])+\\))";
}
scanner.useDelimiter(delimiter);
return cast(scanner);
} else {
// use a plain iterator that returns the value as is as there are only a single value
return cast(new Iterator<String>() {
int idx = -1;
public boolean hasNext() {
return idx + 1 == 0 && (allowEmptyValues || isNotEmpty(s));
}
public String next() {
idx++;
return s;
}
public void remove() {
throw new UnsupportedOperationException();
}
});
}
} else {
return Collections.singletonList(value).iterator();
}
}
/**
* Tests whether the value is <b>not</b> <tt>null</tt> or an empty string.
*
* @param value the value, if its a String it will be tested for text length as well
* @return true if <b>not</b> empty
*/
public static boolean isNotEmpty(Object value) {
if (value == null) {
return false;
} else if (value instanceof String) {
String text = (String) value;
return text.trim().length() > 0;
} else {
return true;
}
}
public static <T> Iterator<T> cast(Iterator<?> p) {
return (Iterator<T>) p;
}
/**
* Strip any leading separators
*/
public static String stripLeadingSeparator(String name) {
if (name == null) {
return null;
}
while (name.startsWith("/") || name.startsWith(File.separator)) {
name = name.substring(1);
}
return name;
}
/**
* Attempts to load the given resources from the given package name using the thread context
* class loader or the class loader used to load this class
*
* @param packageName the name of the package to load its resources
* @return the URLs for the resources or null if it could not be loaded
*/
public static Enumeration<URL> loadResourcesAsURL(String packageName) {
Enumeration<URL> url = null;
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) {
try {
url = contextClassLoader.getResources(packageName);
} catch (IOException e) {
// ignore
}
}
if (url == null) {
try {
url = Helper.class.getClassLoader().getResources(packageName);
} catch (IOException e) {
// ignore
}
}
return url;
}
/**
* Attempts to load the given resource as a stream using the thread context
* class loader or the class loader used to load this class
*
* @param name the name of the resource to load
* @return the stream or null if it could not be loaded
*/
public static URL loadResourceAsURL(String name) {
URL url = null;
String resolvedName = resolveUriPath(name);
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) {
url = contextClassLoader.getResource(resolvedName);
}
if (url == null) {
url = Helper.class.getClassLoader().getResource(resolvedName);
}
return url;
}
/**
* Helper operation used to remove relative path notation from
* resources. Most critical for resources on the Classpath
* as resource loaders will not resolve the relative paths correctly.
*
* @param name the name of the resource to load
* @return the modified or unmodified string if there were no changes
*/
private static String resolveUriPath(String name) {
String answer = name;
if (answer.indexOf("//") > -1) {
answer = answer.replaceAll("//", "/");
}
if (answer.indexOf("../") > -1) {
answer = answer.replaceAll("[A-Za-z0-9]*/\\.\\./", "");
}
if (answer.indexOf("./") > -1) {
answer = answer.replaceAll("\\./", "");
}
return answer;
}
/**
* Resolves the mandatory resource.
*
* @param uri uri of the resource
* @return the resource as an {@link InputStream}. Remember to close this stream after usage.
* @throws java.io.FileNotFoundException is thrown if the resource file could not be found
* @throws java.net.MalformedURLException if the URI is malformed
*/
public static URL resolveMandatoryResourceAsUrl(String uri) throws FileNotFoundException, MalformedURLException {
if (uri.startsWith("file:")) {
// check if file exists first
String name = after(uri, "file:");
File file = new File(name);
if (!file.exists()) {
throw new FileNotFoundException("File " + file + " not found");
}
return new URL(uri);
} else if (uri.startsWith("http:")) {
return new URL(uri);
} else if (uri.startsWith("classpath:")) {
uri = after(uri, "classpath:");
}
// load from classpath by default
URL url = loadResourceAsURL(uri);
if (url == null) {
throw new FileNotFoundException("Cannot find resource in classpath for URI: " + uri);
} else {
return url;
}
}
public static String after(String text, String after) {
if (!text.contains(after)) {
return null;
}
return text.substring(text.indexOf(after) + after.length());
}
/**
* Recursively delete a directory, useful to zapping test data
*
* @param file the directory to be deleted
* @return <tt>false</tt> if error deleting directory
*/
public static boolean deleteDirectory(String file) {
return deleteDirectory(new File(file));
}
/**
* Recursively delete a directory, useful to zapping test data
*
* @param file the directory to be deleted
* @return <tt>false</tt> if error deleting directory
*/
public static boolean deleteDirectory(File file) {
int tries = 0;
int maxTries = 5;
boolean exists = true;
while (exists && (tries < maxTries)) {
recursivelyDeleteDirectory(file);
tries++;
exists = file.exists();
if (exists) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
return !exists;
}
private static void recursivelyDeleteDirectory(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File child : files) {
recursivelyDeleteDirectory(child);
}
}
boolean success = file.delete();
if (!success) {
LOG.warn("Deletion of file: " + file.getAbsolutePath() + " failed");
}
}
/**
* create the directory
*
* @param file the directory to be created
*/
public static void createDirectory(String file) {
File dir = new File(file);
dir.mkdirs();
}
}
| 9,618 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/CmNamespaceHandler.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.blueprint.compendium.cm;
import java.net.URL;
import java.util.*;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.ext.PlaceholdersUtils;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.apache.aries.blueprint.mutable.MutableCollectionMetadata;
import org.apache.aries.blueprint.mutable.MutableComponentMetadata;
import org.apache.aries.blueprint.mutable.MutableIdRefMetadata;
import org.apache.aries.blueprint.mutable.MutableMapMetadata;
import org.apache.aries.blueprint.mutable.MutableRefMetadata;
import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
import org.apache.aries.blueprint.mutable.MutableValueMetadata;
import org.apache.aries.blueprint.utils.ServiceListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Namespace handler for the Config Admin service.
* This handler will parse the various elements defined and populate / modify the registry
* accordingly.
*
* @see CmManagedProperties
* @see CmManagedServiceFactory
* @see CmProperties
* @see CmPropertyPlaceholder
*
* @version $Rev$, $Date$
*/
public class CmNamespaceHandler implements NamespaceHandler {
public static final String BLUEPRINT_NAMESPACE = "http://www.osgi.org/xmlns/blueprint/v1.0.0";
public static final String BLUEPRINT_CM_NAMESPACE_1_0 = "http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0";
public static final String BLUEPRINT_CM_NAMESPACE_1_1 = "http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0";
public static final String BLUEPRINT_CM_NAMESPACE_1_2 = "http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.2.0";
public static final String BLUEPRINT_CM_NAMESPACE_1_3 = "http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.3.0";
public static final String BLUEPRINT_CM_NAMESPACE_1_4 = "http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.4.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_0 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_1 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.1.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_2 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.2.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_3 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.3.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_4 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.4.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_5 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.5.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_6 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.6.0";
public static final String PROPERTY_PLACEHOLDER_ELEMENT = "property-placeholder";
public static final String MANAGED_PROPERTIES_ELEMENT = "managed-properties";
public static final String MANAGED_SERVICE_FACTORY_ELEMENT = "managed-service-factory";
public static final String CM_PROPERTIES_ELEMENT = "cm-properties";
public static final String DEFAULT_PROPERTIES_ELEMENT = "default-properties";
public static final String PROPERTY_ELEMENT = "property";
public static final String INTERFACES_ELEMENT = "interfaces";
public static final String VALUE_ELEMENT = "value";
public static final String MANAGED_COMPONENT_ELEMENT = "managed-component";
public static final String LOCATION_ELEMENT = "location";
public static final String SERVICE_PROPERTIES_ELEMENT = "service-properties";
public static final String REGISTRATION_LISTENER_ELEMENT = "registration-listener";
public static final String ID_ATTRIBUTE = "id";
public static final String SYSTEM_PROPERTIES_NEVER = "never";
public static final String PERSISTENT_ID_ATTRIBUTE = "persistent-id";
public static final String PLACEHOLDER_PREFIX_ATTRIBUTE = "placeholder-prefix";
public static final String PLACEHOLDER_SUFFIX_ATTRIBUTE = "placeholder-suffix";
public static final String PLACEHOLDER_NULL_VALUE_ATTRIBUTE = "null-value";
public static final String DEFAULTS_REF_ATTRIBUTE = "defaults-ref";
public static final String UPDATE_STRATEGY_ATTRIBUTE = "update-strategy";
public static final String UPDATE_METHOD_ATTRIBUTE = "update-method";
public static final String FACTORY_PID_ATTRIBUTE = "factory-pid";
public static final String AUTO_EXPORT_ATTRIBUTE = "auto-export";
public static final String RANKING_ATTRIBUTE = "ranking";
public static final String INTERFACE_ATTRIBUTE = "interface";
public static final String UPDATE_ATTRIBUTE = "update";
public static final String SYSTEM_PROPERTIES_ATTRIBUTE = "system-properties";
public static final String IGNORE_MISSING_LOCATIONS_ATTRIBUTE = "ignore-missing-locations";
public static final String AUTO_EXPORT_DISABLED = "disabled";
public static final String AUTO_EXPORT_INTERFACES = "interfaces";
public static final String AUTO_EXPORT_CLASS_HIERARCHY = "class-hierarchy";
public static final String AUTO_EXPORT_ALL = "all-classes";
public static final String AUTO_EXPORT_DEFAULT = AUTO_EXPORT_DISABLED;
public static final String RANKING_DEFAULT = "0";
private static final String MANAGED_OBJECT_MANAGER_NAME = "org.apache.aries.managedObjectManager";
private static final Logger LOGGER = LoggerFactory.getLogger(CmNamespaceHandler.class);
private static final Set<String> EXT_URIS = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(
BLUEPRINT_EXT_NAMESPACE_V1_0,
BLUEPRINT_EXT_NAMESPACE_V1_1,
BLUEPRINT_EXT_NAMESPACE_V1_2,
BLUEPRINT_EXT_NAMESPACE_V1_3,
BLUEPRINT_EXT_NAMESPACE_V1_4,
BLUEPRINT_EXT_NAMESPACE_V1_5,
BLUEPRINT_EXT_NAMESPACE_V1_6)));
private static final Set<String> CM_URIS = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(
BLUEPRINT_CM_NAMESPACE_1_0,
BLUEPRINT_CM_NAMESPACE_1_1,
BLUEPRINT_CM_NAMESPACE_1_2,
BLUEPRINT_CM_NAMESPACE_1_3,
BLUEPRINT_CM_NAMESPACE_1_4)));
// This property is static but it should be ok since there will be only a single instance
// of this class for the bundle
private static ConfigurationAdmin configAdmin;
private int idCounter;
public int getIdCounter() {
return idCounter;
}
public void setIdCounter(int idCounter) {
this.idCounter = idCounter;
}
public static ConfigurationAdmin getConfigAdmin() {
return configAdmin;
}
public void setConfigAdmin(ConfigurationAdmin configAdmin) {
CmNamespaceHandler.configAdmin = configAdmin;
}
public URL getSchemaLocation(String namespace) {
if (isCmNamespace(namespace)) {
String v = namespace.substring("http://aries.apache.org/blueprint/xmlns/blueprint-cm/v".length());
return getClass().getResource("blueprint-cm-" + v + ".xsd");
} else if (isExtNamespace(namespace)) {
try {
Class<?> extNsHandlerClazz;
Bundle extBundle = FrameworkUtil.getBundle(PlaceholdersUtils.class);
if (extBundle == null) {
// we may not be in OSGi environment
extNsHandlerClazz = getClass().getClassLoader().loadClass("org.apache.aries.blueprint.ext.impl.ExtNamespaceHandler");
} else {
extNsHandlerClazz = extBundle.loadClass("org.apache.aries.blueprint.ext.impl.ExtNamespaceHandler");
}
return ((NamespaceHandler) extNsHandlerClazz.newInstance()).getSchemaLocation(namespace);
} catch (Throwable t) {
LOGGER.warn("Could not locate ext namespace schema", t);
return null;
}
} else {
return null;
}
}
public Set<Class> getManagedClasses() {
return new HashSet<Class>(Arrays.asList(
CmPropertyPlaceholder.class,
CmManagedServiceFactory.class,
CmManagedProperties.class,
CmProperties.class
));
}
public Metadata parse(Element element, ParserContext context) {
LOGGER.debug("Parsing element {{}}{}", element.getNamespaceURI(), element.getLocalName());
ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
registerManagedObjectManager(context, registry);
if (nodeNameEquals(element, PROPERTY_PLACEHOLDER_ELEMENT)) {
return parsePropertyPlaceholder(context, element);
} else if (nodeNameEquals(element, MANAGED_SERVICE_FACTORY_ELEMENT)) {
return parseManagedServiceFactory(context, element);
} else if (nodeNameEquals(element, CM_PROPERTIES_ELEMENT)) {
return parseCmProperties(context, element);
} else {
throw new ComponentDefinitionException("Unsupported element: " + element.getNodeName());
}
}
public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
LOGGER.debug("Decorating node {{}}{}", node.getNamespaceURI(), node.getLocalName());
ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
registerManagedObjectManager(context, registry);
if (node instanceof Element) {
if (nodeNameEquals(node, MANAGED_PROPERTIES_ELEMENT)) {
return decorateManagedProperties(context, (Element) node, component);
} else if (nodeNameEquals(node, CM_PROPERTIES_ELEMENT)) {
return decorateCmProperties(context, (Element) node, component);
} else {
throw new ComponentDefinitionException("Unsupported element: " + node.getNodeName());
}
} else {
throw new ComponentDefinitionException("Illegal use of blueprint cm namespace");
}
}
private ComponentMetadata parseCmProperties(ParserContext context, Element element) {
String id = getId(context, element);
MutableBeanMetadata factoryMetadata = context.createMetadata(MutableBeanMetadata.class);
generateIdIfNeeded(context, factoryMetadata);
factoryMetadata.setScope(BeanMetadata.SCOPE_SINGLETON);
factoryMetadata.setRuntimeClass(CmProperties.class);
factoryMetadata.setInitMethod("init");
factoryMetadata.setDestroyMethod("destroy");
factoryMetadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
factoryMetadata.addProperty("configAdmin", createConfigurationAdminRef(context));
factoryMetadata.addProperty("managedObjectManager", createRef(context, MANAGED_OBJECT_MANAGER_NAME));
String persistentId = element.getAttribute(PERSISTENT_ID_ATTRIBUTE);
factoryMetadata.addProperty("persistentId", createValue(context, persistentId));
context.getComponentDefinitionRegistry().registerComponentDefinition(factoryMetadata);
MutableBeanMetadata propertiesMetadata = context.createMetadata(MutableBeanMetadata.class);
propertiesMetadata.setId(id);
propertiesMetadata.setScope(BeanMetadata.SCOPE_SINGLETON);
propertiesMetadata.setRuntimeClass(Properties.class);
propertiesMetadata.setFactoryComponent(createRef(context, factoryMetadata.getId()));
propertiesMetadata.setFactoryComponent(factoryMetadata);
propertiesMetadata.setFactoryMethod("getProperties");
// Work around ARIES-877
propertiesMetadata.setDependsOn(Arrays.asList(factoryMetadata.getId()));
return propertiesMetadata;
}
private ComponentMetadata parsePropertyPlaceholder(ParserContext context, Element element) {
MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
metadata.setProcessor(true);
metadata.setId(getId(context, element));
metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
metadata.setRuntimeClass(CmPropertyPlaceholder.class);
metadata.setInitMethod("init");
metadata.setDestroyMethod("destroy");
metadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
metadata.addProperty("configAdmin", createConfigurationAdminRef(context));
metadata.addProperty("persistentId", createValue(context, element.getAttribute(PERSISTENT_ID_ATTRIBUTE)));
String prefix = element.hasAttribute(PLACEHOLDER_PREFIX_ATTRIBUTE)
? element.getAttribute(PLACEHOLDER_PREFIX_ATTRIBUTE)
: "${";
metadata.addProperty("placeholderPrefix", createValue(context, prefix));
String suffix = element.hasAttribute(PLACEHOLDER_SUFFIX_ATTRIBUTE)
? element.getAttribute(PLACEHOLDER_SUFFIX_ATTRIBUTE)
: "}";
metadata.addProperty("placeholderSuffix", createValue(context, suffix));
String nullValue = element.hasAttribute(PLACEHOLDER_NULL_VALUE_ATTRIBUTE)
? element.getAttribute(PLACEHOLDER_NULL_VALUE_ATTRIBUTE)
: null;
if (nullValue != null) {
metadata.addProperty("nullValue", createValue(context, nullValue));
}
String defaultsRef = element.hasAttribute(DEFAULTS_REF_ATTRIBUTE) ? element.getAttribute(DEFAULTS_REF_ATTRIBUTE) : null;
if (defaultsRef != null) {
metadata.addProperty("defaultProperties", createRef(context, defaultsRef));
}
String ignoreMissingLocations = extractIgnoreMissingLocations(element);
if (ignoreMissingLocations != null) {
metadata.addProperty("ignoreMissingLocations", createValue(context, ignoreMissingLocations));
}
String systemProperties = extractSystemPropertiesAttribute(element);
if (systemProperties == null) {
systemProperties = SYSTEM_PROPERTIES_NEVER;
}
metadata.addProperty("systemProperties", createValue(context, systemProperties));
String updateStrategy = element.getAttribute(UPDATE_STRATEGY_ATTRIBUTE);
if (updateStrategy != null) {
metadata.addProperty("updateStrategy", createValue(context, updateStrategy));
}
metadata.addProperty("managedObjectManager", createRef(context, MANAGED_OBJECT_MANAGER_NAME));
// Parse elements
List<String> locations = new ArrayList<String>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isCmNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, DEFAULT_PROPERTIES_ELEMENT)) {
if (defaultsRef != null) {
throw new ComponentDefinitionException("Only one of " + DEFAULTS_REF_ATTRIBUTE + " attribute or " + DEFAULT_PROPERTIES_ELEMENT + " element is allowed");
}
Metadata props = parseDefaultProperties(context, metadata, e);
metadata.addProperty("defaultProperties", props);
}
} else if (isExtNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, LOCATION_ELEMENT)) {
locations.add(getTextValue(e));
}
}
}
}
if (!locations.isEmpty()) {
metadata.addProperty("locations", createList(context, locations));
}
PlaceholdersUtils.validatePlaceholder(metadata, context.getComponentDefinitionRegistry());
return metadata;
}
private String extractSystemPropertiesAttribute(Element element) {
for (String uri : EXT_URIS) {
if (element.hasAttributeNS(uri, SYSTEM_PROPERTIES_ATTRIBUTE)) {
return element.getAttributeNS(uri, SYSTEM_PROPERTIES_ATTRIBUTE);
}
}
return null;
}
private String extractIgnoreMissingLocations(Element element) {
for (String uri : EXT_URIS) {
if (element.hasAttributeNS(uri, IGNORE_MISSING_LOCATIONS_ATTRIBUTE)) {
return element.getAttributeNS(uri, IGNORE_MISSING_LOCATIONS_ATTRIBUTE);
}
}
return null;
}
private Metadata parseDefaultProperties(ParserContext context, MutableBeanMetadata enclosingComponent, Element element) {
MutableMapMetadata props = context.createMetadata(MutableMapMetadata.class);
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isCmNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, PROPERTY_ELEMENT)) {
BeanProperty prop = context.parseElement(BeanProperty.class, enclosingComponent, e);
props.addEntry(createValue(context, prop.getName(), String.class.getName()), prop.getValue());
}
}
}
}
return props;
}
private ComponentMetadata parseManagedServiceFactory(ParserContext context, Element element) {
String id = getId(context, element);
MutableBeanMetadata factoryMetadata = context.createMetadata(MutableBeanMetadata.class);
generateIdIfNeeded(context, factoryMetadata);
factoryMetadata.addProperty("id", createValue(context, factoryMetadata.getId()));
factoryMetadata.setScope(BeanMetadata.SCOPE_SINGLETON);
factoryMetadata.setRuntimeClass(CmManagedServiceFactory.class);
factoryMetadata.setInitMethod("init");
factoryMetadata.setDestroyMethod("destroy");
factoryMetadata.addArgument(createRef(context, "blueprintContainer"), null, 0);
factoryMetadata.addProperty("factoryPid", createValue(context, element.getAttribute(FACTORY_PID_ATTRIBUTE)));
String autoExport = element.hasAttribute(AUTO_EXPORT_ATTRIBUTE) ? element.getAttribute(AUTO_EXPORT_ATTRIBUTE) : AUTO_EXPORT_DEFAULT;
if (AUTO_EXPORT_DISABLED.equals(autoExport)) {
autoExport = Integer.toString(ServiceMetadata.AUTO_EXPORT_DISABLED);
} else if (AUTO_EXPORT_INTERFACES.equals(autoExport)) {
autoExport = Integer.toString(ServiceMetadata.AUTO_EXPORT_INTERFACES);
} else if (AUTO_EXPORT_CLASS_HIERARCHY.equals(autoExport)) {
autoExport = Integer.toString(ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY);
} else if (AUTO_EXPORT_ALL.equals(autoExport)) {
autoExport = Integer.toString(ServiceMetadata.AUTO_EXPORT_ALL_CLASSES);
} else {
throw new ComponentDefinitionException("Illegal value (" + autoExport + ") for " + AUTO_EXPORT_ATTRIBUTE + " attribute");
}
factoryMetadata.addProperty("autoExport", createValue(context, autoExport));
String ranking = element.hasAttribute(RANKING_ATTRIBUTE) ? element.getAttribute(RANKING_ATTRIBUTE) : RANKING_DEFAULT;
factoryMetadata.addProperty("ranking", createValue(context, ranking));
List<String> interfaces = null;
if (element.hasAttribute(INTERFACE_ATTRIBUTE)) {
interfaces = Collections.singletonList(element.getAttribute(INTERFACE_ATTRIBUTE));
factoryMetadata.addProperty("interfaces", createList(context, interfaces));
}
// Parse elements
List<RegistrationListener> listeners = new ArrayList<RegistrationListener>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, INTERFACES_ELEMENT)) {
if (interfaces != null) {
throw new ComponentDefinitionException("Only one of " + INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must be used");
}
interfaces = parseInterfaceNames(e);
factoryMetadata.addProperty("interfaces", createList(context, interfaces));
} else if (nodeNameEquals(e, SERVICE_PROPERTIES_ELEMENT)) {
MapMetadata map = context.parseElement(MapMetadata.class,
factoryMetadata, e);
factoryMetadata.addProperty("serviceProperties", map);
NodeList enl = e.getChildNodes();
for (int j = 0; j < enl.getLength(); j++) {
Node enode = enl.item(j);
if (enode instanceof Element) {
if (isCmNamespace(enode.getNamespaceURI()) && nodeNameEquals(enode, CM_PROPERTIES_ELEMENT)) {
decorateCmProperties(context, (Element) enode, factoryMetadata);
}
}
}
} else if (nodeNameEquals(e, REGISTRATION_LISTENER_ELEMENT)) {
listeners.add(context.parseElement(RegistrationListener.class,
factoryMetadata, e));
}
} else if (isCmNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, MANAGED_COMPONENT_ELEMENT)) {
MutableBeanMetadata managedComponent = context.parseElement(MutableBeanMetadata.class, null, e);
generateIdIfNeeded(context, managedComponent);
managedComponent.setScope(BeanMetadata.SCOPE_PROTOTYPE);
// destroy-method on managed-component has different signature than on regular beans
// so we'll handle it differently
String destroyMethod = managedComponent.getDestroyMethod();
if (destroyMethod != null) {
factoryMetadata.addProperty("componentDestroyMethod", createValue(context, destroyMethod));
managedComponent.setDestroyMethod(null);
}
context.getComponentDefinitionRegistry().registerComponentDefinition(managedComponent);
factoryMetadata.addProperty("managedComponentName", createIdRef(context, managedComponent.getId()));
}
}
}
}
MutableCollectionMetadata listenerCollection = context.createMetadata(MutableCollectionMetadata.class);
listenerCollection.setCollectionClass(List.class);
for (RegistrationListener listener : listeners) {
MutableBeanMetadata bean = context.createMetadata(MutableBeanMetadata.class);
bean.setRuntimeClass(ServiceListener.class);
bean.addProperty("listener", listener.getListenerComponent());
bean.addProperty("registerMethod", createValue(context, listener.getRegistrationMethod()));
bean.addProperty("unregisterMethod", createValue(context, listener.getUnregistrationMethod()));
listenerCollection.addValue(bean);
}
factoryMetadata.addProperty("listeners", listenerCollection);
context.getComponentDefinitionRegistry().registerComponentDefinition(factoryMetadata);
MutableBeanMetadata mapMetadata = context.createMetadata(MutableBeanMetadata.class);
mapMetadata.setScope(BeanMetadata.SCOPE_SINGLETON);
mapMetadata.setId(id);
mapMetadata.setFactoryComponent(createRef(context, factoryMetadata.getId()));
mapMetadata.setFactoryMethod("getServiceMap");
return mapMetadata;
}
private ComponentMetadata decorateCmProperties(ParserContext context, Element element, ComponentMetadata component) {
generateIdIfNeeded(context, ((MutableComponentMetadata) component));
MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
metadata.setProcessor(true);
metadata.setId(getId(context, element));
metadata.setRuntimeClass(CmProperties.class);
String persistentId = element.getAttribute(PERSISTENT_ID_ATTRIBUTE);
// if persistentId is "" the cm-properties element in nested in managed-service-factory
// and the configuration object will come from the factory. So we only really need to register
// ManagedService if the persistentId is not an empty string.
if (persistentId.length() > 0) {
metadata.setInitMethod("init");
metadata.setDestroyMethod("destroy");
}
metadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
metadata.addProperty("configAdmin", createConfigurationAdminRef(context));
metadata.addProperty("managedObjectManager", createRef(context, MANAGED_OBJECT_MANAGER_NAME));
metadata.addProperty("persistentId", createValue(context, persistentId));
if (element.hasAttribute(UPDATE_ATTRIBUTE)) {
metadata.addProperty("update", createValue(context, element.getAttribute(UPDATE_ATTRIBUTE)));
}
metadata.addProperty("serviceId", createIdRef(context, component.getId()));
context.getComponentDefinitionRegistry().registerComponentDefinition(metadata);
return component;
}
private ComponentMetadata decorateManagedProperties(ParserContext context, Element element, ComponentMetadata component) {
if (!(component instanceof MutableBeanMetadata)) {
throw new ComponentDefinitionException("Element " + MANAGED_PROPERTIES_ELEMENT + " must be used inside a <bp:bean> element");
}
generateIdIfNeeded(context, ((MutableBeanMetadata) component));
MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
metadata.setProcessor(true);
metadata.setId(getId(context, element));
metadata.setRuntimeClass(CmManagedProperties.class);
String persistentId = element.getAttribute(PERSISTENT_ID_ATTRIBUTE);
// if persistentId is "" the managed properties element in nested in managed-service-factory
// and the configuration object will come from the factory. So we only really need to register
// ManagedService if the persistentId is not an empty string.
if (persistentId.length() > 0) {
metadata.setInitMethod("init");
metadata.setDestroyMethod("destroy");
}
metadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
metadata.addProperty("configAdmin", createConfigurationAdminRef(context));
metadata.addProperty("managedObjectManager", createRef(context, MANAGED_OBJECT_MANAGER_NAME));
metadata.addProperty("persistentId", createValue(context, persistentId));
String updateStrategy = element.getAttribute(UPDATE_STRATEGY_ATTRIBUTE);
if (updateStrategy != null) {
metadata.addProperty("updateStrategy", createValue(context, updateStrategy));
}
if (element.hasAttribute(UPDATE_METHOD_ATTRIBUTE)) {
metadata.addProperty("updateMethod", createValue(context, element.getAttribute(UPDATE_METHOD_ATTRIBUTE)));
} else if ("component-managed".equals(updateStrategy)) {
throw new ComponentDefinitionException(UPDATE_METHOD_ATTRIBUTE + " attribute must be set when " + UPDATE_STRATEGY_ATTRIBUTE + " is set to 'component-managed'");
}
metadata.addProperty("beanName", createIdRef(context, component.getId()));
context.getComponentDefinitionRegistry().registerComponentDefinition(metadata);
return component;
}
private void registerManagedObjectManager(ParserContext context, ComponentDefinitionRegistry registry) {
if (registry.getComponentDefinition(MANAGED_OBJECT_MANAGER_NAME) == null) {
MutableBeanMetadata beanMetadata = context.createMetadata(MutableBeanMetadata.class);
beanMetadata.setScope(BeanMetadata.SCOPE_SINGLETON);
beanMetadata.setId(MANAGED_OBJECT_MANAGER_NAME);
beanMetadata.setRuntimeClass(ManagedObjectManager.class);
registry.registerComponentDefinition(beanMetadata);
}
}
private MutableReferenceMetadata createConfigurationAdminRef(ParserContext context) {
return createServiceRef(context, ConfigurationAdmin.class, null);
}
private static ValueMetadata createValue(ParserContext context, String value) {
return createValue(context, value, null);
}
private static ValueMetadata createValue(ParserContext context, String value, String type) {
MutableValueMetadata m = context.createMetadata(MutableValueMetadata.class);
m.setStringValue(value);
m.setType(type);
return m;
}
private static RefMetadata createRef(ParserContext context, String value) {
MutableRefMetadata m = context.createMetadata(MutableRefMetadata.class);
m.setComponentId(value);
return m;
}
private MutableReferenceMetadata createServiceRef(ParserContext context, Class<?> cls, String filter) {
MutableReferenceMetadata m = context.createMetadata(MutableReferenceMetadata.class);
m.setRuntimeInterface(cls);
m.setInterface(cls.getName());
m.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
m.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
if (filter != null) {
m.setFilter(filter);
}
return m;
}
private static IdRefMetadata createIdRef(ParserContext context, String value) {
MutableIdRefMetadata m = context.createMetadata(MutableIdRefMetadata.class);
m.setComponentId(value);
return m;
}
private static CollectionMetadata createList(ParserContext context, List<String> list) {
MutableCollectionMetadata m = context.createMetadata(MutableCollectionMetadata.class);
m.setCollectionClass(List.class);
m.setValueType(String.class.getName());
for (String v : list) {
m.addValue(createValue(context, v, String.class.getName()));
}
return m;
}
private static String getTextValue(Element element) {
StringBuffer value = new StringBuffer();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
value.append(item.getNodeValue());
}
}
return value.toString();
}
private static boolean nodeNameEquals(Node node, String name) {
return (name.equals(node.getNodeName()) || name.equals(node.getLocalName()));
}
public static boolean isBlueprintNamespace(String ns) {
return BLUEPRINT_NAMESPACE.equals(ns);
}
public static boolean isCmNamespace(String uri) {
return CM_URIS.contains(uri);
}
public static boolean isExtNamespace(String uri) {
return EXT_URIS.contains(uri);
}
public String getId(ParserContext context, Element element) {
if (element.hasAttribute(ID_ATTRIBUTE)) {
return element.getAttribute(ID_ATTRIBUTE);
} else {
return generateId(context);
}
}
public void generateIdIfNeeded(ParserContext context, MutableComponentMetadata metadata) {
if (metadata.getId() == null) {
metadata.setId(generateId(context));
}
}
private String generateId(ParserContext context) {
String id;
do {
id = ".cm-" + ++idCounter;
} while (context.getComponentDefinitionRegistry().containsComponentDefinition(id));
return id;
}
public List<String> parseInterfaceNames(Element element) {
List<String> interfaceNames = new ArrayList<String>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, VALUE_ELEMENT)) {
String v = getTextValue(e).trim();
if (interfaceNames.contains(v)) {
throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice");
}
interfaceNames.add(getTextValue(e));
} else {
throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element");
}
}
}
return interfaceNames;
}
}
| 9,619 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/ManagedObjectManager.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.blueprint.compendium.cm;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Since persistence id can only be associated with one ManagedService in a bundle
* this class ensures only one ManagedService is registered per persistence id.
*/
public class ManagedObjectManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ManagedObjectManager.class);
private HashMap<String, ConfigurationWatcher> map = new HashMap<String, ConfigurationWatcher>();
public synchronized void register(ManagedObject cm, Properties props) {
String key = cm.getPersistentId();
ConfigurationWatcher reg = map.get(key);
if (reg == null) {
reg = new ConfigurationWatcher();
ServiceRegistration registration = cm.getBundle().getBundleContext().registerService(ManagedService.class.getName(), reg, (Dictionary) props);
reg.setRegistration(registration);
map.put(key, reg);
}
reg.add(cm);
try {
Dictionary<String, Object> config = CmUtils.getProperties(reg.getRegistration().getReference(), key);
cm.updated(config);
} catch (Throwable t) {
// Ignore
}
}
public synchronized void unregister(ManagedObject cm) {
String key = cm.getPersistentId();
ConfigurationWatcher reg = map.get(key);
if (reg != null) {
reg.remove(cm);
if (reg.isEmpty()) {
map.remove(key);
ServiceUtil.safeUnregister(reg.getRegistration());
}
}
}
private static class ConfigurationWatcher implements ManagedService {
private ServiceRegistration registration;
private List<ManagedObject> list = new CopyOnWriteArrayList<ManagedObject>();
public ConfigurationWatcher() {
}
public void updated(final Dictionary props) throws ConfigurationException {
// Run in a separate thread to avoid re-entrance
new Thread() {
public void run() {
for (ManagedObject cm : list) {
cm.updated(props);
}
}
}.start();
}
private void setRegistration(ServiceRegistration registration) {
this.registration = registration;
}
private ServiceRegistration getRegistration() {
return registration;
}
private void add(ManagedObject cm) {
list.add(cm);
}
private void remove(ManagedObject cm) {
list.remove(cm);
}
private boolean isEmpty() {
return list.isEmpty();
}
}
}
| 9,620 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/CmManagedServiceFactory.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.blueprint.compendium.cm;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.ServiceProcessor;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.JavaUtils;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.apache.aries.blueprint.utils.ServiceListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.cm.ManagedServiceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO: if we need to make those exported services tied to their references as for other <service/> elements
* TODO: it becomes a problem as currently we would have to create a specific recipe or something like that
*
* @version $Rev$, $Date$
*/
public class CmManagedServiceFactory extends BaseManagedServiceFactory<Object> {
private static final Logger LOGGER = LoggerFactory.getLogger(CmManagedServiceFactory.class);
private ExtendedBlueprintContainer blueprintContainer;
private String id;
private String factoryPid;
private List<String> interfaces;
private int autoExport;
private int ranking;
private Map<Object, Object> serviceProperties;
private String managedComponentName;
private String componentDestroyMethod;
private List<ServiceListener> listeners;
private ServiceRegistration registration;
public CmManagedServiceFactory(ExtendedBlueprintContainer blueprintContainer) {
super(blueprintContainer.getBundleContext(), null);
this.blueprintContainer = blueprintContainer;
}
public void init() throws Exception {
LOGGER.debug("Initializing CmManagedServiceFactory for factoryPid={}", factoryPid);
Properties props = new Properties();
props.put(Constants.SERVICE_PID, factoryPid);
Bundle bundle = blueprintContainer.getBundleContext().getBundle();
props.put(Constants.BUNDLE_SYMBOLICNAME, bundle.getSymbolicName());
props.put(Constants.BUNDLE_VERSION, bundle.getHeaders().get(Constants.BUNDLE_VERSION));
registration = blueprintContainer.getBundleContext().registerService(ManagedServiceFactory.class.getName(), this, (Dictionary) props);
}
public void destroy() {
ServiceUtil.safeUnregister(registration);
super.destroy();
}
public Map<ServiceRegistration, Object> getServiceMap() {
return Collections.unmodifiableMap(getServices());
}
public void setListeners(List<ServiceListener> listeners) {
this.listeners = listeners;
}
public void setId(String id) {
this.id = id;
}
public void setFactoryPid(String factoryPid) {
this.factoryPid = factoryPid;
}
public void setInterfaces(List<String> interfaces) {
this.interfaces = interfaces;
}
public void setAutoExport(int autoExport) {
this.autoExport = autoExport;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public void setServiceProperties(Map serviceProperties) {
this.serviceProperties = serviceProperties;
}
public void setManagedComponentName(String managedComponentName) {
this.managedComponentName = managedComponentName;
}
public void setComponentDestroyMethod(String componentDestroyMethod) {
this.componentDestroyMethod = componentDestroyMethod;
}
private void getRegistrationProperties(Dictionary properties, boolean update) {
String pid = (String) properties.get(Constants.SERVICE_PID);
CmProperties cm = findServiceProcessor();
if (cm == null) {
while (!properties.isEmpty()) {
properties.remove(properties.keys().nextElement());
}
} else {
if (!cm.getUpdate()) {
if (update) {
while (!properties.isEmpty()) {
properties.remove(properties.keys().nextElement());
}
for (Map.Entry entry : cm.getProperties().entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
} else {
cm.updated(properties);
}
}
}
if (serviceProperties != null) {
for (Map.Entry entry : serviceProperties.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
}
properties.put(Constants.SERVICE_RANKING, ranking);
properties.put(Constants.SERVICE_PID, pid);
}
private void updateComponentProperties(Object bean, Dictionary props) {
CmManagedProperties cm = findBeanProcessor();
if (cm != null) {
cm.updated(bean, props);
}
}
private CmManagedProperties findBeanProcessor() {
for (BeanProcessor beanProcessor : blueprintContainer.getProcessors(BeanProcessor.class)) {
if (beanProcessor instanceof CmManagedProperties) {
CmManagedProperties cm = (CmManagedProperties) beanProcessor;
if (managedComponentName.equals(cm.getBeanName()) && "".equals(cm.getPersistentId())) {
return cm;
}
}
}
return null;
}
private CmProperties findServiceProcessor() {
for (ServiceProcessor processor : blueprintContainer.getProcessors(ServiceProcessor.class)) {
if (processor instanceof CmProperties) {
CmProperties cm = (CmProperties) processor;
if (id.equals(cm.getServiceId())) {
return cm;
}
}
}
return null;
}
private Method findDestroyMethod(Class clazz, Class... args) {
Method method = null;
if (componentDestroyMethod != null && componentDestroyMethod.length() > 0) {
List<Method> methods = ReflectionUtils.findCompatibleMethods(clazz, componentDestroyMethod, args);
if (methods != null && !methods.isEmpty()) {
method = methods.get(0);
}
}
return method;
}
protected Object doCreate(Dictionary properties) throws Exception {
updateComponentProperties(null, copy(properties));
Object component = blueprintContainer.getComponentInstance(managedComponentName);
getRegistrationProperties(properties, false);
return component;
}
protected Object doUpdate(Object service, Dictionary properties) throws Exception {
updateComponentProperties(service, copy(properties));
getRegistrationProperties(properties, true);
return service;
}
protected void doDestroy(Object service, Dictionary properties, int code) throws Exception {
Method method = findDestroyMethod(service.getClass(), int.class);
if (method != null) {
try {
method.invoke(service, code);
} catch (Exception e) {
LOGGER.info("Error destroying component", e);
}
} else {
method = findDestroyMethod(service.getClass());
if (method != null) {
try {
method.invoke(service);
} catch (Exception e) {
LOGGER.info("Error destroying component", e);
}
}
}
}
protected void postRegister(Object service, Dictionary properties, ServiceRegistration registration) {
if (listeners != null && !listeners.isEmpty()) {
Hashtable props = new Hashtable();
JavaUtils.copy(properties, props);
for (ServiceListener listener : listeners) {
listener.register(service, props);
}
}
}
protected void preUnregister(Object service, Dictionary properties, ServiceRegistration registration) {
if (listeners != null && !listeners.isEmpty()) {
Hashtable props = new Hashtable();
JavaUtils.copy(properties, props);
for (ServiceListener listener : listeners) {
listener.unregister(service, props);
}
}
}
protected String[] getExposedClasses(Object service) {
Class serviceClass = service.getClass();
Set<String> classes;
switch (autoExport) {
case ServiceMetadata.AUTO_EXPORT_INTERFACES:
classes = ReflectionUtils.getImplementedInterfaces(new HashSet<String>(), serviceClass);
break;
case ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY:
classes = ReflectionUtils.getSuperClasses(new HashSet<String>(), serviceClass);
break;
case ServiceMetadata.AUTO_EXPORT_ALL_CLASSES:
classes = ReflectionUtils.getSuperClasses(new HashSet<String>(), serviceClass);
classes = ReflectionUtils.getImplementedInterfaces(classes, serviceClass);
break;
default:
classes = new HashSet<String>(interfaces);
break;
}
return classes.toArray(new String[classes.size()]);
}
private Hashtable copy(Dictionary source) {
Hashtable ht = new Hashtable();
JavaUtils.copy(ht, source);
return ht;
}
}
| 9,621 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/CmManagedProperties.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.blueprint.compendium.cm;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO
*
* @version $Rev$, $Date$
*/
public class CmManagedProperties implements ManagedObject, BeanProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(CmManagedProperties.class);
private ExtendedBlueprintContainer blueprintContainer;
private ConfigurationAdmin configAdmin;
private ManagedObjectManager managedObjectManager;
private String persistentId;
private String updateStrategy;
private String updateMethod;
private String beanName;
private final Object lock = new Object();
private final Set<Object> beans = new HashSet<Object>();
private Dictionary<String, Object> properties;
private boolean initialized;
public ExtendedBlueprintContainer getBlueprintContainer() {
return blueprintContainer;
}
public void setBlueprintContainer(ExtendedBlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public ConfigurationAdmin getConfigAdmin() {
return configAdmin;
}
public void setConfigAdmin(ConfigurationAdmin configAdmin) {
this.configAdmin = configAdmin;
}
public void setManagedObjectManager(ManagedObjectManager managedObjectManager) {
this.managedObjectManager = managedObjectManager;
}
public ManagedObjectManager getManagedObjectManager() {
return managedObjectManager;
}
public Bundle getBundle() {
return blueprintContainer.getBundleContext().getBundle();
}
public String getPersistentId() {
return persistentId;
}
public void setPersistentId(String persistentId) {
this.persistentId = persistentId;
}
public String getUpdateStrategy() {
return updateStrategy;
}
public void setUpdateStrategy(String updateStrategy) {
this.updateStrategy = updateStrategy;
}
public String getUpdateMethod() {
return updateMethod;
}
public void setUpdateMethod(String updateMethod) {
this.updateMethod = updateMethod;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public void init() throws Exception {
LOGGER.debug("Initializing CmManagedProperties for bean={} / pid={}", beanName, persistentId);
Properties props = new Properties();
props.put(Constants.SERVICE_PID, persistentId);
Bundle bundle = blueprintContainer.getBundleContext().getBundle();
props.put(Constants.BUNDLE_SYMBOLICNAME, bundle.getSymbolicName());
props.put(Constants.BUNDLE_VERSION, bundle.getHeaders().get(Constants.BUNDLE_VERSION));
synchronized (lock) {
managedObjectManager.register(this, props);
}
}
public void destroy() {
managedObjectManager.unregister(this);
}
public void updated(final Dictionary props) {
if (!initialized) {
properties = props;
initialized = true;
return;
}
LOGGER.debug("Configuration updated for bean={} / pid={}", beanName, persistentId);
synchronized (lock) {
properties = props;
for (Object bean : beans) {
updated(bean, properties);
}
}
}
public void updated(Object bean, final Dictionary props) {
LOGGER.debug("Configuration updated for bean={} / pid={}", beanName, persistentId);
synchronized (lock) {
properties = props;
if (bean != null) {
inject(bean, false);
}
}
}
public Object beforeInit(Object bean, String beanName, BeanCreator beanCreator, BeanMetadata beanData) {
if (beanName != null && beanName.equals(this.beanName)) {
LOGGER.debug("Adding bean for bean={} / pid={}", beanName, persistentId);
synchronized (lock) {
beans.add(bean);
inject(bean, true);
}
}
return bean;
}
public Object afterInit(Object bean, String beanName, BeanCreator beanCreator, BeanMetadata beanData) {
return bean;
}
public void beforeDestroy(Object bean, String beanName) {
if (beanName.equals(this.beanName)) {
LOGGER.debug("Removing bean for bean={} / pid={}", beanName, persistentId);
synchronized (lock) {
beans.remove(bean);
}
}
}
public void afterDestroy(Object bean, String beanName) {
}
private void inject(Object bean, boolean initial) {
LOGGER.debug("Injecting bean for bean={} / pid={}", beanName, persistentId);
LOGGER.debug("Configuration: {}", properties);
if (initial || "container-managed".equals(updateStrategy)) {
if (properties != null) {
for (Enumeration<String> e = properties.keys(); e.hasMoreElements();) {
String key = e.nextElement();
Object val = properties.get(key);
String setterName = "set" + Character.toUpperCase(key.charAt(0));
if (key.length() > 0) {
setterName += key.substring(1);
}
Set<Method> validSetters = new LinkedHashSet<Method>();
List<Method> methods = new ArrayList<Method>(Arrays.asList(bean.getClass().getMethods()));
methods.addAll(Arrays.asList(bean.getClass().getDeclaredMethods()));
for (Method method : methods) {
if (method.getName().equals(setterName)) {
if (shouldSkip(method)) {
continue;
}
Class methodParameterType = method.getParameterTypes()[0];
Object propertyValue;
try {
propertyValue = blueprintContainer.getConverter().convert(val, new ReifiedType(methodParameterType));
} catch (Throwable t) {
LOGGER.debug("Unable to convert value for setter: " + method, t);
continue;
}
if (methodParameterType.isPrimitive() && propertyValue == null) {
LOGGER.debug("Null can not be assigned to {}: {}", methodParameterType.getName(), method);
continue;
}
if (validSetters.add(method)) {
try {
method.invoke(bean, propertyValue);
} catch (Exception t) {
LOGGER.debug("Setter can not be invoked: " + method, getRealCause(t));
}
}
}
}
if (validSetters.isEmpty()) {
LOGGER.debug("Unable to find a valid setter method for property {} and value {}", key, val);
}
}
}
} else if ("component-managed".equals(updateStrategy) && updateMethod != null) {
List<Method> methods = ReflectionUtils.findCompatibleMethods(bean.getClass(), updateMethod, new Class[] { Map.class });
Map map = null;
if (properties != null) {
map = new HashMap();
for (Enumeration<String> e = properties.keys(); e.hasMoreElements();) {
String key = e.nextElement();
Object val = properties.get(key);
map.put(key, val);
}
}
for (Method method : methods) {
try {
method.invoke(bean, map);
} catch (Throwable t) {
LOGGER.warn("Unable to call method " + method + " on bean " + beanName, getRealCause(t));
}
}
}
}
private boolean shouldSkip(Method method) {
String msg = null;
if (method.getParameterTypes().length == 0) {
msg = "takes no parameters";
} else if (method.getParameterTypes().length > 1) {
msg = "takes more than one parameter";
} else if (method.getReturnType() != Void.TYPE) {
msg = "returns a value";
} else if (Modifier.isAbstract(method.getModifiers())) {
msg = "is abstract";
} else if (!Modifier.isPublic(method.getModifiers())) {
msg = "is not public";
} else if (Modifier.isStatic(method.getModifiers())) {
msg = "is static";
}
if (msg != null) {
LOGGER.debug("Skipping setter {} because it " + msg, method);
return true;
} else {
return false;
}
}
private static Throwable getRealCause(Throwable t) {
if (t instanceof InvocationTargetException && t.getCause() != null) {
return t.getCause();
}
return t;
}
}
| 9,622 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/CmProperties.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.blueprint.compendium.cm;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apache.aries.blueprint.ServiceProcessor;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.JavaUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @version $Rev$, $Date$
*/
public class CmProperties implements ManagedObject, ServiceProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(CmProperties.class);
private ExtendedBlueprintContainer blueprintContainer;
private ConfigurationAdmin configAdmin;
private ManagedObjectManager managedObjectManager;
private String persistentId;
private boolean update;
private String serviceId;
private final Object lock = new Object();
private final Set<ServicePropertiesUpdater> services = new HashSet<ServicePropertiesUpdater>();
private final Properties properties = new Properties();
private boolean initialized;
public ExtendedBlueprintContainer getBlueprintContainer() {
return blueprintContainer;
}
public void setBlueprintContainer(ExtendedBlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public ConfigurationAdmin getConfigAdmin() {
return configAdmin;
}
public void setConfigAdmin(ConfigurationAdmin configAdmin) {
this.configAdmin = configAdmin;
}
public void setManagedObjectManager(ManagedObjectManager managedObjectManager) {
this.managedObjectManager = managedObjectManager;
}
public ManagedObjectManager getManagedObjectManager() {
return managedObjectManager;
}
public Bundle getBundle() {
return blueprintContainer.getBundleContext().getBundle();
}
public String getPersistentId() {
return persistentId;
}
public void setPersistentId(String persistentId) {
this.persistentId = persistentId;
}
public boolean getUpdate() {
return update;
}
public void setUpdate(boolean update) {
this.update = update;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public void init() throws Exception {
if (serviceId != null) {
LOGGER.debug("Initializing CmProperties for service={} / pid={}", serviceId, persistentId);
} else {
LOGGER.debug("Initializing CmProperties for pid={}", persistentId);
}
Properties props = new Properties();
props.put(Constants.SERVICE_PID, persistentId);
Bundle bundle = blueprintContainer.getBundleContext().getBundle();
props.put(Constants.BUNDLE_SYMBOLICNAME, bundle.getSymbolicName());
props.put(Constants.BUNDLE_VERSION, bundle.getHeaders().get(Constants.BUNDLE_VERSION));
synchronized (lock) {
managedObjectManager.register(this, props);
}
}
public void destroy() {
managedObjectManager.unregister(this);
}
public Properties getProperties() {
return properties;
}
public void updated(Dictionary props) {
if (initialized) {
if (serviceId != null) {
LOGGER.debug("Service properties updated for service={} / pid={}, {}", new Object[]{serviceId, persistentId, props});
} else {
LOGGER.debug("Service properties updated for pid={}, {}", new Object[]{persistentId, props});
}
}
synchronized (lock) {
properties.clear();
if (props != null) {
JavaUtils.copy(properties, props);
}
if (!initialized) {
initialized = true;
} else if (update) {
for (ServicePropertiesUpdater service : services) {
service.updateProperties(props);
}
}
}
}
public void updateProperties(ServicePropertiesUpdater service, Dictionary props) {
if (this.serviceId == null || !this.serviceId.equals(service.getId())) {
return;
}
LOGGER.debug("Service properties initialized for service={} / pid={}, {}", new Object[] {serviceId, persistentId, props});
synchronized (lock) {
services.add(service);
JavaUtils.copy(props, properties);
}
}
}
| 9,623 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/ManagedObject.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.blueprint.compendium.cm;
import java.util.Dictionary;
import org.osgi.framework.Bundle;
public interface ManagedObject {
Bundle getBundle();
String getPersistentId();
void updated(Dictionary props);
}
| 9,624 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/CmPropertyPlaceholder.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.blueprint.compendium.cm;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.aries.blueprint.ext.PropertyPlaceholderExt;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
public class CmPropertyPlaceholder extends PropertyPlaceholderExt implements ManagedObject {
private static final Logger LOGGER = LoggerFactory.getLogger(CmPropertyPlaceholder.class);
private ExtendedBlueprintContainer blueprintContainer;
private ConfigurationAdmin configAdmin;
private String persistentId;
private String updateStrategy;
private ManagedObjectManager managedObjectManager;
private Dictionary<String, Object> properties;
private boolean initialized;
public ExtendedBlueprintContainer getBlueprintContainer() {
return blueprintContainer;
}
public void setBlueprintContainer(ExtendedBlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public ConfigurationAdmin getConfigAdmin() {
return configAdmin;
}
public void setConfigAdmin(ConfigurationAdmin configAdmin) {
this.configAdmin = configAdmin;
}
public String getPersistentId() {
return persistentId;
}
public void setPersistentId(String persistentId) {
this.persistentId = persistentId;
}
public String getUpdateStrategy() {
return updateStrategy;
}
public void setUpdateStrategy(String updateStrategy) {
this.updateStrategy = updateStrategy;
}
public ManagedObjectManager getManagedObjectManager() {
return managedObjectManager;
}
public void setManagedObjectManager(ManagedObjectManager managedObjectManager) {
this.managedObjectManager = managedObjectManager;
}
public void init() throws Exception {
LOGGER.debug("Initializing CmPropertyPlaceholder");
Properties props = new Properties();
props.put(Constants.SERVICE_PID, persistentId);
Bundle bundle = blueprintContainer.getBundleContext().getBundle();
props.put(Constants.BUNDLE_SYMBOLICNAME, bundle.getSymbolicName());
props.put(Constants.BUNDLE_VERSION, bundle.getHeaders().get(Constants.BUNDLE_VERSION));
managedObjectManager.register(this, props);
}
public void destroy() {
LOGGER.debug("Destroying CmPropertyPlaceholder");
managedObjectManager.unregister(this);
}
protected Object getProperty(String val) {
LOGGER.debug("Retrieving property value {} from configuration with pid {}", val, persistentId);
Object v = null;
if (properties != null) {
v = properties.get(val);
if (v != null) {
LOGGER.debug("Found property value {}", v);
} else {
LOGGER.debug("Property not found in configuration");
}
}
if (v == null) {
v = super.getProperty(val);
}
return v;
}
public Bundle getBundle() {
return blueprintContainer.getBundleContext().getBundle();
}
public void updated(Dictionary props) {
if (!initialized) {
properties = props;
initialized = true;
return;
}
if ("reload".equalsIgnoreCase(updateStrategy) && !equals(properties, props)) {
LOGGER.debug("Configuration updated for pid={}", persistentId);
// Run in a separate thread to avoid re-entrance
new Thread() {
public void run() {
blueprintContainer.reload();
}
}.start();
}
}
private <T, U> boolean equals(Dictionary<T, U> d1, Dictionary<T, U> d2) {
if (d1 == null || d1.isEmpty()) {
return d2 == null || d2.isEmpty();
} else if (d2 == null || d1.size() != d2.size()) {
return false;
} else {
for (Enumeration<T> e = d1.keys(); e.hasMoreElements();) {
T k = e.nextElement();
U v1 = d1.get(k);
U v2 = d2.get(k);
if (v1 == null) {
if (v2 != null) {
return false;
}
} else if (v1 instanceof Object[] && v2 instanceof Object[]) {
if (!Arrays.deepEquals((Object[]) v1, (Object[]) v2)) {
return false;
}
} else if (!v1.equals(v2)) {
return false;
}
}
return true;
}
}
}
| 9,625 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/ServiceUtil.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.blueprint.compendium.cm;
import org.osgi.framework.ServiceRegistration;
public final class ServiceUtil {
private ServiceUtil() {
}
public static void safeUnregister(ServiceRegistration<?> sreg) {
if (sreg != null) {
try {
sreg.unregister();
} catch (Exception e) {
// Ignore
}
}
}
}
| 9,626 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/BaseManagedServiceFactory.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.blueprint.compendium.cm;
import java.util.Dictionary;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.blueprint.utils.JavaUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedServiceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("rawtypes")
public abstract class BaseManagedServiceFactory<T> implements ManagedServiceFactory {
public static final long DEFAULT_TIMEOUT_BEFORE_INTERRUPT = 30000;
public static final int CONFIGURATION_ADMIN_OBJECT_DELETED = 1;
public static final int BUNDLE_STOPPING = 2;
public static final int INTERNAL_ERROR = 4;
protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
private final BundleContext context;
private final String name;
private final long timeoutBeforeInterrupt;
private final AtomicBoolean destroyed;
private final ExecutorService executor;
private final Map<String, Pair<T, ServiceRegistration>> services;
private final Map<ServiceRegistration, T> registrations;
public BaseManagedServiceFactory(BundleContext context, String name) {
this(context, name, DEFAULT_TIMEOUT_BEFORE_INTERRUPT);
}
public BaseManagedServiceFactory(BundleContext context, String name, long timeoutBeforeInterrupt) {
this.context = context;
this.name = name;
this.timeoutBeforeInterrupt = timeoutBeforeInterrupt;
this.destroyed = new AtomicBoolean(false);
this.executor = Executors.newSingleThreadExecutor();
this.services = new ConcurrentHashMap<String, Pair<T, ServiceRegistration>>();
this.registrations = new ConcurrentHashMap<ServiceRegistration, T>();
}
public String getName() {
return name;
}
public Map<ServiceRegistration, T> getServices() {
return registrations;
}
public void updated(final String pid, final Dictionary properties) throws ConfigurationException {
if (destroyed.get()) {
return;
}
checkConfiguration(pid, properties);
executor.submit(new Runnable() {
public void run() {
try {
internalUpdate(pid, properties);
} catch (Throwable t) {
LOGGER.warn("Error destroying service for ManagedServiceFactory " + getName(), t);
}
}
});
}
public void deleted(final String pid) {
if (destroyed.get()) {
return;
}
executor.submit(new Runnable() {
public void run() {
try {
internalDelete(pid, CONFIGURATION_ADMIN_OBJECT_DELETED);
} catch (Throwable throwable) {
LOGGER.warn("Error destroying service for ManagedServiceFactory " + getName(), throwable);
}
}
});
}
protected void checkConfiguration(String pid, Dictionary properties) throws ConfigurationException {
// Do nothing
}
protected abstract T doCreate(Dictionary properties) throws Exception;
protected abstract T doUpdate(T t, Dictionary properties) throws Exception;
protected abstract void doDestroy(T t, Dictionary properties, int code) throws Exception;
protected abstract String[] getExposedClasses(T t);
private void internalUpdate(String pid, Dictionary properties) {
Pair<T, ServiceRegistration> pair = services.get(pid);
if (pair != null) {
try {
T t = doUpdate(pair.getFirst(), properties);
pair.setFirst(t);
pair.getSecond().setProperties(properties);
} catch (Throwable throwable) {
internalDelete(pid, INTERNAL_ERROR);
LOGGER.warn("Error updating service for ManagedServiceFactory " + getName(), throwable);
}
} else {
if (destroyed.get()) {
return;
}
try {
T t = doCreate(properties);
try {
if (destroyed.get()) {
throw new IllegalStateException("ManagedServiceFactory has been destroyed");
}
ServiceRegistration registration = context.registerService(getExposedClasses(t), t, properties);
services.put(pid, new Pair<T, ServiceRegistration>(t, registration));
registrations.put(registration, t);
postRegister(t, properties, registration);
} catch (Throwable throwable1) {
try {
doDestroy(t, properties, INTERNAL_ERROR);
} catch (Throwable throwable2) {
// Ignore
}
throw throwable1;
}
} catch (Throwable throwable) {
LOGGER.warn("Error creating service for ManagedServiceFactory " + getName(), throwable);
}
}
}
protected void postRegister(T t, Dictionary properties, ServiceRegistration registration) {
// Place holder
}
protected void preUnregister(T t, Dictionary properties, ServiceRegistration registration) {
// Place holder
}
private void internalDelete(String pid, int code) {
Pair<T, ServiceRegistration> pair = services.remove(pid);
if (pair != null) {
registrations.remove(pair.getSecond());
Dictionary properties = JavaUtils.getProperties(pair.getSecond().getReference());
try {
preUnregister(pair.getFirst(), properties, pair.getSecond());
pair.getSecond().unregister();
} catch (Throwable t) {
LOGGER.info("Error unregistering service", t);
}
try {
doDestroy(pair.getFirst(), properties, code);
} catch (Throwable t) {
LOGGER.info("Error destroying service", t);
}
}
}
public void destroy() {
if (destroyed.compareAndSet(false, true)) {
executor.shutdown();
try {
executor.awaitTermination(timeoutBeforeInterrupt, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Shutdown interrupted");
}
if (!executor.isTerminated()) {
executor.shutdownNow();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Shutdown interrupted");
}
}
while (!services.isEmpty()) {
String pid = services.keySet().iterator().next();
internalDelete(pid, BUNDLE_STOPPING);
}
}
}
static class Pair<U, V> {
private U first;
private V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public U getFirst() {
return first;
}
public V getSecond() {
return second;
}
public void setFirst(U first) {
this.first = first;
}
public void setSecond(V second) {
this.second = second;
}
}
}
| 9,627 |
0 | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium | Create_ds/aries/blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/CmUtils.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.blueprint.compendium.cm;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationPlugin;
public class CmUtils {
private CmUtils() {
}
public static Configuration getConfiguration(ConfigurationAdmin configAdmin, String persistentId) throws IOException {
String filter = '(' + Constants.SERVICE_PID + '=' + persistentId + ')';
Configuration[] configs;
try {
configs = configAdmin.listConfigurations(filter);
} catch (InvalidSyntaxException e) {
// this should not happen
throw new RuntimeException("Invalid filter: " + filter);
}
if (configs != null && configs.length > 0) {
return configs[0];
} else {
// TODO: what should we do?
// throw new RuntimeException("No configuration object for pid=" + persistentId);
return null;
}
}
public static Dictionary<String, Object> getProperties(ServiceReference service, String persistentId) throws IOException {
BundleContext bc = service.getBundle().getBundleContext();
ServiceReference<ConfigurationAdmin> caRef = bc.getServiceReference(ConfigurationAdmin.class);
try {
ConfigurationAdmin ca = bc.getService(caRef);
Configuration config = getConfiguration(ca, persistentId);
if (config != null) {
Dictionary<String, Object> props = new CaseInsensitiveDictionary(config.getProperties());
Bundle bundle = caRef.getBundle();
if (bundle != null) {
BundleContext caBc = bundle.getBundleContext();
if (caBc != null) {
try {
callPlugins(caBc, props, service, persistentId, null);
} catch (IllegalStateException ise) {
// we don't care it doesn't exist so, shrug.
}
}
}
return props;
} else {
return null;
}
} finally {
bc.ungetService(caRef);
}
}
private static void callPlugins(final BundleContext bundleContext,
final Dictionary<String, Object> props,
final ServiceReference sr,
final String configPid,
final String factoryPid) {
ServiceReference[] plugins = null;
try {
final String targetPid = (factoryPid == null) ? configPid : factoryPid;
String filter = "(|(!(cm.target=*))(cm.target=" + targetPid + "))";
plugins = bundleContext.getServiceReferences(ConfigurationPlugin.class.getName(), filter);
} catch (InvalidSyntaxException ise) {
// no filter, no exception ...
}
// abort early if there are no plugins
if (plugins == null || plugins.length == 0) {
return;
}
// sort the plugins by their service.cmRanking
if (plugins.length > 1) {
Arrays.sort(plugins, CM_RANKING);
}
// call the plugins in order
for (ServiceReference pluginRef : plugins) {
ConfigurationPlugin plugin = (ConfigurationPlugin) bundleContext.getService(pluginRef);
if (plugin != null) {
try {
plugin.modifyConfiguration(sr, props);
} catch (Throwable t) {
// Ignore
} finally {
// ensure ungetting the plugin
bundleContext.ungetService(pluginRef);
}
setAutoProperties(props, configPid, factoryPid);
}
}
}
private static void setAutoProperties( Dictionary<String, Object> properties, String pid, String factoryPid )
{
replaceProperty(properties, Constants.SERVICE_PID, pid);
replaceProperty(properties, ConfigurationAdmin.SERVICE_FACTORYPID, factoryPid);
properties.remove(ConfigurationAdmin.SERVICE_BUNDLELOCATION);
}
private static void replaceProperty(Dictionary<String, Object> properties, String key, String value) {
if (value == null) {
properties.remove(key);
} else {
properties.put(key, value);
}
}
private static Comparator<ServiceReference> CM_RANKING = new Comparator<ServiceReference>() {
@Override
public int compare(ServiceReference sr1, ServiceReference sr2) {
final long rank1 = getLong(sr1, ConfigurationPlugin.CM_RANKING);
final long rank2 = getLong(sr2, ConfigurationPlugin.CM_RANKING);
if (rank1 == rank2) {
return 0;
}
return (rank1 < rank2) ? -1 : 1;
}
protected long getLong(ServiceReference sr, String property) {
Object rankObj = sr.getProperty(property);
if (rankObj instanceof Number) {
return ((Number) rankObj).longValue();
}
return 0;
}
};
private static class CaseInsensitiveDictionary extends Dictionary<String, Object> {
private final Hashtable<String, Object> internalMap = new Hashtable<String, Object>();
private final Hashtable<String, String> originalKeys = new Hashtable<String, String>();
public CaseInsensitiveDictionary(Dictionary<String, Object> props) {
if (props != null) {
Enumeration<String> keys = props.keys();
while (keys.hasMoreElements()) {
// check the correct syntax of the key
String key = checkKey(keys.nextElement());
// check uniqueness of key
String lowerCase = key.toLowerCase();
if (internalMap.containsKey(lowerCase)) {
throw new IllegalArgumentException("Key [" + key + "] already present in different case");
}
// check the value
Object value = props.get(key);
checkValue(value);
// add the key/value pair
internalMap.put(lowerCase, value);
originalKeys.put(lowerCase, key);
}
}
}
public Enumeration<Object> elements() {
return Collections.enumeration(internalMap.values());
}
public Object get(Object keyObj) {
String lowerCase = checkKey(keyObj == null ? null : keyObj.toString()).toLowerCase();
return internalMap.get(lowerCase);
}
public boolean isEmpty() {
return internalMap.isEmpty();
}
public Enumeration<String> keys() {
return Collections.enumeration(originalKeys.values());
}
public Object put(String key, Object value) {
String lowerCase = checkKey(key).toLowerCase();
checkValue(value);
originalKeys.put(lowerCase, key);
return internalMap.put(lowerCase, value);
}
public Object remove(Object keyObj) {
String lowerCase = checkKey(keyObj == null ? null : keyObj.toString()).toLowerCase();
originalKeys.remove(lowerCase);
return internalMap.remove(lowerCase);
}
public int size() {
return internalMap.size();
}
static String checkKey(String key) {
if (key == null || key.length() == 0) {
throw new IllegalArgumentException("Key must not be null nor an empty string");
}
return key;
}
static Object checkValue(Object value) {
if (value == null) {
throw new IllegalArgumentException("Value must not be null");
}
return value;
}
public String toString() {
return internalMap.toString();
}
}
}
| 9,628 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint/BlueprintContainerTest.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.blueprint;
import org.apache.aries.blueprint.container.BlueprintContainerImpl;
import org.apache.aries.blueprint.sample.Foo;
import org.junit.Test;
import java.net.URL;
import java.util.Arrays;
import static org.junit.Assert.*;
public class BlueprintContainerTest {
@Test
public void testSimple() throws Exception {
URL url = getClass().getClassLoader().getResource("test.xml");
BlueprintContainerImpl container = new BlueprintContainerImpl(getClass().getClassLoader(), Arrays.asList(url));
Foo foo = (Foo) container.getComponentInstance("foo");
System.out.println(foo);
assertNotNull(foo);
assertEquals(5, foo.getA());
assertEquals(1, foo.getB());
container.destroy();
}
@Test
public void testPlaceholders() throws Exception {
URL url1 = getClass().getClassLoader().getResource("test.xml");
URL url2 = getClass().getClassLoader().getResource("test2.xml");
BlueprintContainerImpl container = new BlueprintContainerImpl(getClass().getClassLoader(), Arrays.asList(url1, url2));
Foo foo = (Foo) container.getComponentInstance("foo");
System.out.println(foo);
assertNotNull(foo);
assertEquals(5, foo.getA());
assertEquals(1, foo.getB());
container.destroy();
}
public static void main(String[] args) throws Exception {
URL url = BlueprintContainerTest.class.getClassLoader().getResource("test.xml");
BlueprintContainerImpl container = new BlueprintContainerImpl(BlueprintContainerTest.class.getClassLoader(), Arrays.asList(url));
System.out.println(container.getComponentInstance("foo"));
container.destroy();
}
}
| 9,629 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint/ext/PropertyPlaceholderTest.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.blueprint.ext;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.osgi.service.blueprint.reflect.ValueMetadata;
public class PropertyPlaceholderTest extends PropertyPlaceholder {
private final Map<String,Object> values = new HashMap<String,Object>();
private LateBindingValueMetadata sut;
@Before
public void setup() {
values.clear();
bind("prop1","hello");
bind("prop2","world");
bind("prop3","10");
bind("prop4","20");
bind("prop5","nested");
bind("prop-nested","hello nested world!");
bind("prop-recursive-1","${prop-recursive-2}");
bind("prop-recursive-2","${prop-recursive-3}");
bind("prop-recursive-3","recursive-3");
bind("animal", "quick brown fox");
bind("target", "lazy dog");
bind("animal.1", "fox");
bind("animal.2", "mouse");
bind("species", "2");
}
@Test
public void singleProp() {
sut = makeProperty("${prop1}");
assertEquals("hello", sut.getStringValue());
}
@Test
public void multipleProps() {
sut = makeProperty("say ${prop1} ${prop2}");
assertEquals("say hello world", sut.getStringValue());
}
@Test
public void nestedProps() {
sut = makeProperty("${prop-${prop5}}");
assertEquals("hello nested world!", sut.getStringValue());
}
@Test
public void nestedProps2() {
sut = makeProperty("The ${animal.${species}} jumps over the ${target}.");
assertEquals("The mouse jumps over the lazy dog.", sut.getStringValue());
}
@Test
public void nestedProps3() {
sut = makeProperty("The ${animal.${species}} jumps over the ${target}.");
bind("species", "1");
assertEquals("The fox jumps over the lazy dog.", sut.getStringValue());
}
@Test
public void recursiveProps() {
sut = makeProperty("${prop-recursive-1}");
assertEquals("recursive-3", sut.getStringValue());
}
@Test
public void plainText() {
sut = makeProperty("plain text");
assertEquals("plain text", sut.getStringValue());
}
// @Test
// public void evaluateStringProps() {
// sut = makeProperty("${prop1+prop2}");
// assertEquals("helloworld", sut.getStringValue());
// }
//
// @Test
// public void evaluateIntProps() {
// sut = makeProperty("${prop3+prop4}");
// assertEquals("30", sut.getStringValue());
// }
/*
* Test helper methods
*/
// Override to simulate actual property retrieval
protected Object getProperty(String prop) {
return values.get(prop);
}
private void bind(String prop, String val) {
values.put(prop, val);
}
private LateBindingValueMetadata makeProperty(final String prop) {
return new LateBindingValueMetadata(new ValueMetadata() {
public String getType() {
return null;
}
public String getStringValue() {
return prop;
}
});
}
}
| 9,630 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint/sample/Bar.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.blueprint.sample;
import java.util.List;
public class Bar {
private String value;
private List list;
public String getValue() {
return value;
}
public void setValue(String s) {
value = s;
}
public List getList() {
return list;
}
public void setList(List l) {
list = l;
}
public String toString() {
return hashCode() + ": " + value + " " + list;
}
}
| 9,631 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint/sample/Foo.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.blueprint.sample;
import java.io.Serializable;
import java.util.Currency;
import java.util.Date;
import java.util.Map;
public class Foo implements Serializable {
private int a;
private int b;
private Bar bar;
private Currency currency;
private Date date;
public boolean initialized;
public boolean destroyed;
private Map<String, Object> props;
public int getA() {
return a;
}
public void setA(int i) {
a = i;
}
public int getB() {
return b;
}
public void setB(int i) {
b = i;
}
public Bar getBar() {
return bar;
}
public void setBar(Bar b) {
bar = b;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency c) {
currency = c;
}
public Date getDate() {
return date;
}
public void setDate(Date d) {
date = d;
}
public String toString() {
return a + " " + b + " " + bar + " " + currency + " " + date;
}
public void init() {
System.out.println("======== Initializing Foo =========");
initialized = true;
}
public void destroy() {
System.out.println("======== Destroying Foo =========");
destroyed = true;
}
public boolean isInitialized() {
return initialized;
}
public boolean isDestroyed() {
return destroyed;
}
public void update(Map<String,Object> props) {
this.props = props;
}
public Map<String, Object> getProps() {
return props;
}
}
| 9,632 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint/sample/DateTypeConverter.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.blueprint.sample;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.ReifiedType;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTypeConverter implements Converter {
DateFormat dateFormat;
public void setFormat(String format) {
dateFormat = new SimpleDateFormat(format);
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return dateFormat.parse(source.toString());
}
public boolean canConvert(Object fromValue, ReifiedType toType) {
return Date.class.isAssignableFrom(toType.getRawClass());
}
}
| 9,633 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/test/java/org/apache/aries/blueprint/sample/CurrencyTypeConverter.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.blueprint.sample;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.ReifiedType;
import java.util.Currency;
public class CurrencyTypeConverter implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return Currency.class.isAssignableFrom(toType.getRawClass());
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return Currency.getInstance(source.toString());
}
}
| 9,634 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/ext/AbstractPropertyPlaceholder.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.blueprint.ext;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.ComponentDefinitionRegistryProcessor;
import org.apache.aries.blueprint.ExtendedValueMetadata;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanArgument;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanProperty;
import org.apache.aries.blueprint.mutable.MutableCollectionMetadata;
import org.apache.aries.blueprint.mutable.MutableMapEntry;
import org.apache.aries.blueprint.mutable.MutableMapMetadata;
import org.apache.aries.blueprint.mutable.MutablePropsMetadata;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.osgi.service.blueprint.reflect.ValueMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract class for property placeholders.
*
* @version $Rev: 1211548 $, $Date: 2011-12-07 17:26:22 +0000 (Wed, 07 Dec 2011) $
*/
public abstract class AbstractPropertyPlaceholder implements ComponentDefinitionRegistryProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPropertyPlaceholder.class);
private ExtendedBlueprintContainer blueprintContainer;
private String placeholderPrefix = "${";
private String placeholderSuffix = "}";
private String nullValue = null;
private Pattern pattern;
private LinkedList<String> processingStack = new LinkedList<String>();
public String getPlaceholderPrefix() {
return placeholderPrefix;
}
public void setPlaceholderPrefix(String placeholderPrefix) {
this.placeholderPrefix = placeholderPrefix;
}
public String getPlaceholderSuffix() {
return placeholderSuffix;
}
public void setPlaceholderSuffix(String placeholderSuffix) {
this.placeholderSuffix = placeholderSuffix;
}
public String getNullValue() {
return nullValue;
}
public void setNullValue(String nullValue) {
this.nullValue = nullValue;
}
public ExtendedBlueprintContainer getBlueprintContainer() {
return blueprintContainer;
}
public void setBlueprintContainer(ExtendedBlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public void process(ComponentDefinitionRegistry registry) throws ComponentDefinitionException {
try {
for (String name : registry.getComponentDefinitionNames()) {
processMetadata(registry.getComponentDefinition(name));
}
} finally {
processingStack.clear();
}
}
protected Metadata processMetadata(Metadata metadata) {
try {
if (metadata instanceof BeanMetadata) {
BeanMetadata bmd = (BeanMetadata) metadata;
processingStack.add("Bean named " + bmd.getId() + "->");
return processBeanMetadata(bmd);
} else if (metadata instanceof CollectionMetadata) {
CollectionMetadata cmd = (CollectionMetadata) metadata;
processingStack.add("Collection of type " + cmd.getCollectionClass() + "->");
return processCollectionMetadata(cmd);
} else if (metadata instanceof MapMetadata) {
processingStack.add("Map->");
return processMapMetadata((MapMetadata) metadata);
} else if (metadata instanceof PropsMetadata) {
processingStack.add("Properties->");
return processPropsMetadata((PropsMetadata) metadata);
} else if (metadata instanceof ValueMetadata) {
processingStack.add("Value->");
return processValueMetadata((ValueMetadata) metadata);
} else {
processingStack.add("Unknown Metadata " + metadata + "->");
return metadata;
}
} finally {
processingStack.removeLast();
}
}
protected Metadata processBeanMetadata(BeanMetadata component) {
for (BeanArgument arg : component.getArguments()) {
try {
processingStack.add(
"Argument index " + arg.getIndex() + " and value type " + arg.getValueType() + "->");
if(arg instanceof MutableBeanArgument) {
((MutableBeanArgument) arg).setValue(processMetadata(arg.getValue()));
} else {
//Say that we can't change this argument, but continue processing
//If the value is mutable then we may be ok!
printWarning(arg, "Constructor Argument");
processMetadata(arg.getValue());
}
} finally {
processingStack.removeLast();
}
}
for (BeanProperty prop : component.getProperties()) {
try {
processingStack.add("Property named " + prop.getName() + "->");
if(prop instanceof MutableBeanProperty) {
((MutableBeanProperty) prop).setValue(processMetadata(prop.getValue()));
} else {
//Say that we can't change this property, but continue processing
//If the value is mutable then we may be ok!
printWarning(prop, "Injection Property");
processMetadata(prop.getValue());
}
} finally {
processingStack.removeLast();
}
}
Target factoryComponent = component.getFactoryComponent();
if(factoryComponent != null) {
try {
if(component instanceof MutableBeanMetadata) {
processingStack.add("Factory Component->");
((MutableBeanMetadata) component).setFactoryComponent(
(Target) processMetadata(factoryComponent));
} else {
printWarning(component, "Factory Component");
processingStack.add("Factory Component->");
processMetadata(factoryComponent);
}
} finally {
processingStack.removeLast();
}
}
return component;
}
protected Metadata processPropsMetadata(PropsMetadata metadata) {
List<MapEntry> entries = new ArrayList<MapEntry>(metadata.getEntries());
if(!!! entries.isEmpty()) {
try {
if(metadata instanceof MutablePropsMetadata) {
processingStack.add("Properties->");
MutablePropsMetadata mpm = (MutablePropsMetadata) metadata;
for (MapEntry entry : entries) {
mpm.removeEntry(entry);
}
for (MapEntry entry : processMapEntries(entries)) {
mpm.addEntry(entry);
}
} else {
printWarning(metadata, "Properties");
processingStack.add("Properties->");
processMapEntries(entries);
}
} finally {
processingStack.removeLast();
}
}
return metadata;
}
protected Metadata processMapMetadata(MapMetadata metadata) {
List<MapEntry> entries = new ArrayList<MapEntry>(metadata.getEntries());
if(!!! entries.isEmpty()) {
try {
if(metadata instanceof MutableMapMetadata) {
processingStack.add("Map->");
MutableMapMetadata mmm = (MutableMapMetadata) metadata;
for (MapEntry entry : entries) {
mmm.removeEntry(entry);
}
for (MapEntry entry : processMapEntries(entries)) {
mmm.addEntry(entry);
}
} else {
printWarning(metadata, "Map");
processingStack.add("Map->");
processMapEntries(entries);
}
} finally {
processingStack.removeLast();
}
}
return metadata;
}
protected List<MapEntry> processMapEntries(List<MapEntry> entries) {
for (MapEntry entry : entries) {
try {
processingStack.add("Map Entry Key: " + entry.getKey() + " Value: " + entry.getValue() + "->" );
if(entry instanceof MutableMapEntry) {
((MutableMapEntry) entry).setKey((NonNullMetadata) processMetadata(entry.getKey()));
((MutableMapEntry) entry).setValue(processMetadata(entry.getValue()));
} else {
printWarning(entry, "Map Entry");
processMetadata(entry.getKey());
processMetadata(entry.getValue());
}
} finally {
processingStack.removeLast();
}
}
return entries;
}
protected Metadata processCollectionMetadata(CollectionMetadata metadata) {
List<Metadata> values = new ArrayList<Metadata>(metadata.getValues());
if(!!! values.isEmpty()) {
try {
if(metadata instanceof MutableCollectionMetadata) {
processingStack.add("Collection type: " + metadata.getValueType() + "->");
MutableCollectionMetadata mcm = (MutableCollectionMetadata) metadata;
for (Metadata value : values) {
mcm.removeValue(value);
}
for (Metadata value : values) {
mcm.addValue(processMetadata(value));
}
} else {
printWarning(metadata, "Collection type: " + metadata.getValueType());
processingStack.add("Collection type: " + metadata.getValueType() + "->");
for (Metadata value : values) {
processMetadata(value);
}
}
} finally {
processingStack.removeLast();
}
}
return metadata;
}
protected Metadata processValueMetadata(ValueMetadata metadata) {
return new LateBindingValueMetadata(metadata);
}
private void printWarning(Object immutable, String processingType) {
StringBuilder sb = new StringBuilder("The property placeholder processor for ");
sb.append(placeholderPrefix).append(',').append(" ").append(placeholderSuffix)
.append(" found an immutable ").append(processingType)
.append(" at location ");
for(String s : processingStack) {
sb.append(s);
}
sb.append(". This may prevent properties, beans, or other items referenced by this component from being properly processed.");
LOGGER.info(sb.toString());
}
protected Object retrieveValue(String expression) {
return getProperty(expression);
}
protected Object processString(String str) {
// TODO: we need to handle escapes on the prefix / suffix
Matcher matcher = getPattern().matcher(str);
while (matcher.find()) {
String n = matcher.group(1);
int idx = n.indexOf(placeholderPrefix);
if (idx >= 0) {
matcher.region(matcher.start(1) + idx, str.length());
continue;
}
Object rep = retrieveValue(matcher.group(1));
if (rep != null) {
if (rep instanceof String || !matcher.group(0).equals(str)) {
str = str.replace(matcher.group(0), rep.toString());
matcher.reset(str);
} else {
return rep;
}
}
}
if (nullValue != null && nullValue.equals(str)) {
return null;
}
return str;
}
protected Object getProperty(String val) {
return null;
}
protected Pattern getPattern() {
if (pattern == null) {
pattern = Pattern.compile("\\Q" + placeholderPrefix + "\\E(.+?)\\Q" + placeholderSuffix + "\\E");
}
return pattern;
}
public class LateBindingValueMetadata implements ExtendedValueMetadata {
private final ValueMetadata metadata;
private boolean retrieved;
private Object retrievedValue;
public LateBindingValueMetadata(ValueMetadata metadata) {
this.metadata = metadata;
}
public String getStringValue() {
retrieve();
return retrievedValue instanceof String ? (String) retrievedValue : null;
}
public String getType() {
return metadata.getType();
}
public Object getValue() {
retrieve();
return retrievedValue instanceof String ? null : retrievedValue;
}
private void retrieve() {
if (!retrieved) {
Object o = null;
if (metadata instanceof ExtendedValueMetadata) {
o = ((ExtendedValueMetadata) metadata).getValue();
}
if (o == null) {
String v = metadata.getStringValue();
LOGGER.debug("Before process: {}", v);
retrievedValue = processString(v);
LOGGER.debug("After process: {}", retrievedValue);
} else {
LOGGER.debug("Skipping non string value: {}", o);
}
retrieved = true;
}
}
}
}
| 9,635 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/ext/PropertyPlaceholder.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.blueprint.ext;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.aries.blueprint.ext.evaluator.PropertyEvaluator;
import org.apache.aries.blueprint.ext.evaluator.PropertyEvaluatorExt;
import org.apache.felix.utils.properties.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Property placeholder that looks for properties in the System properties.
*
* @version $Rev$, $Date$
*/
public class PropertyPlaceholder extends AbstractPropertyPlaceholder {
public enum SystemProperties {
never,
fallback,
override
}
private static final Logger LOGGER = LoggerFactory.getLogger(PropertyPlaceholder.class);
private Map<String, Object> defaultProperties;
private Properties properties;
private List<String> locations;
private boolean ignoreMissingLocations;
private SystemProperties systemProperties = SystemProperties.override;
private PropertyEvaluatorExt evaluator = null;
public Map getDefaultProperties() {
return defaultProperties;
}
public void setDefaultProperties(Map defaultProperties) {
this.defaultProperties = defaultProperties;
}
public List<String> getLocations() {
return locations;
}
public void setLocations(List<String> locations) {
this.locations = locations;
}
public boolean isIgnoreMissingLocations() {
return ignoreMissingLocations;
}
public void setIgnoreMissingLocations(boolean ignoreMissingLocations) {
this.ignoreMissingLocations = ignoreMissingLocations;
}
public SystemProperties getSystemProperties() {
return systemProperties;
}
public void setSystemProperties(SystemProperties systemProperties) {
this.systemProperties = systemProperties;
}
public PropertyEvaluatorExt getEvaluator() {
return evaluator;
}
public void setEvaluator(PropertyEvaluatorExt evaluator) {
this.evaluator = evaluator;
}
public void init() throws Exception {
properties = new Properties();
if (locations != null) {
for (String url : locations) {
InputStream is = null;
try {
if (url.startsWith("classpath:")) {
is = getBlueprintContainer().getResource(url.substring("classpath:".length())).openStream();
} else {
is = new URL(url).openStream();
}
} catch (IOException e) {
if (ignoreMissingLocations) {
LOGGER.debug("Unable to load properties from url " + url + " while ignoreMissingLocations is set to true");
} else {
throw e;
}
}
if (is != null) {
try {
properties.load(is);
} finally {
is.close();
}
}
}
}
}
protected Object getProperty(String val) {
LOGGER.debug("Retrieving property {}", val);
Object v = null;
if (v == null && systemProperties == SystemProperties.override) {
v = getBlueprintContainer().getProperty(val);
if (v != null) {
LOGGER.debug("Found system property {} with value {}", val, v);
}
}
if (v == null && properties != null) {
v = properties.getProperty(val);
if (v != null) {
LOGGER.debug("Found property {} from locations with value {}", val, v);
}
}
if (v == null && systemProperties == SystemProperties.fallback) {
v = getBlueprintContainer().getProperty(val);
if (v != null) {
LOGGER.debug("Found system property {} with value {}", val, v);
}
}
if (v == null && defaultProperties != null) {
v = defaultProperties.get(val);
if (v != null) {
LOGGER.debug("Retrieved property {} value from defaults {}", val, v);
}
}
if (v == null) {
LOGGER.debug("Property {} not found", val);
}
return v;
}
@Override
protected Object retrieveValue(String expression) {
LOGGER.debug("Retrieving Value from expression: {}", expression);
if (evaluator == null) {
return super.retrieveValue(expression);
} else {
return evaluator.evaluate(expression, new AbstractMap<String, Object>() {
@Override
public Object get(Object key) {
return getProperty((String) key);
}
@Override
public Set<Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException();
}
});
}
}
}
| 9,636 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/ext | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/ext/impl/ExtNamespaceHandler.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.blueprint.ext.impl;
import java.net.URL;
import java.util.*;
import org.apache.aries.blueprint.*;
import org.apache.aries.blueprint.container.NullProxy;
import org.apache.aries.blueprint.ext.AbstractPropertyPlaceholder;
import org.apache.aries.blueprint.ext.PropertyPlaceholder;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.apache.aries.blueprint.mutable.MutableCollectionMetadata;
import org.apache.aries.blueprint.mutable.MutableComponentMetadata;
import org.apache.aries.blueprint.mutable.MutableIdRefMetadata;
import org.apache.aries.blueprint.mutable.MutableMapMetadata;
import org.apache.aries.blueprint.mutable.MutableRefMetadata;
import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
import org.apache.aries.blueprint.mutable.MutableValueMetadata;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A namespace handler for Aries blueprint extensions
*
* @version $Rev$, $Date$
*/
public class ExtNamespaceHandler implements org.apache.aries.blueprint.NamespaceHandler {
public static final String BLUEPRINT_NAMESPACE = "http://www.osgi.org/xmlns/blueprint/v1.0.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_0 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_1 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.1.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_2 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.2.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_3 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.3.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_4 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.4.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_5 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.5.0";
public static final String BLUEPRINT_EXT_NAMESPACE_V1_6 = "http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.6.0";
public static final String PROPERTY_PLACEHOLDER_ELEMENT = "property-placeholder";
public static final String DEFAULT_PROPERTIES_ELEMENT = "default-properties";
public static final String PROPERTY_ELEMENT = "property";
public static final String VALUE_ELEMENT = "value";
public static final String LOCATION_ELEMENT = "location";
public static final String ID_ATTRIBUTE = "id";
public static final String PLACEHOLDER_PREFIX_ATTRIBUTE = "placeholder-prefix";
public static final String PLACEHOLDER_SUFFIX_ATTRIBUTE = "placeholder-suffix";
public static final String PLACEHOLDER_NULL_VALUE_ATTRIBUTE = "null-value";
public static final String DEFAULTS_REF_ATTRIBUTE = "defaults-ref";
public static final String IGNORE_MISSING_LOCATIONS_ATTRIBUTE = "ignore-missing-locations";
public static final String EVALUATOR_ATTRIBUTE = "evaluator";
public static final String SYSTEM_PROPERTIES_ATTRIBUTE = "system-properties";
public static final String SYSTEM_PROPERTIES_NEVER = "never";
public static final String SYSTEM_PROPERTIES_FALLBACK = "fallback";
public static final String SYSTEM_PROPERTIES_OVERRIDE = "override";
public static final String PROXY_METHOD_ATTRIBUTE = "proxy-method";
public static final String PROXY_METHOD_DEFAULT = "default";
public static final String PROXY_METHOD_CLASSES = "classes";
public static final String PROXY_METHOD_GREEDY = "greedy";
public static final String ROLE_ATTRIBUTE = "role";
public static final String ROLE_PROCESSOR = "processor";
public static final String FIELD_INJECTION_ATTRIBUTE = "field-injection";
public static final String NON_STANDARD_SETTERS_ATTRIBUTE = "non-standard-setters";
public static final String DEFAULT_REFERENCE_BEAN = "default";
public static final String FILTER_ATTRIBUTE = "filter";
public static final String ADDITIONAL_INTERFACES = "additional-interfaces";
public static final String INTERFACE_VALUE = "value";
public static final String BEAN = "bean";
public static final String REFERENCE = "reference";
public static final String ARGUMENT = "argument";
public static final String DAMPING_ATTRIBUTE = "damping";
public static final String DAMPING_RELUCTANT = "reluctant";
public static final String DAMPING_GREEDY = "greedy";
public static final String LIFECYCLE_ATTRIBUTE = "lifecycle";
public static final String LIFECYCLE_DYNAMIC = "dynamic";
public static final String LIFECYCLE_STATIC = "static";
public static final String RAW_CONVERSION_ATTRIBUTE = "raw-conversion";
public static final String NULL_PROXY_ELEMENT = "null-proxy";
public static final Set<String> EXT_URIS = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(
BLUEPRINT_EXT_NAMESPACE_V1_0,
BLUEPRINT_EXT_NAMESPACE_V1_1,
BLUEPRINT_EXT_NAMESPACE_V1_2,
BLUEPRINT_EXT_NAMESPACE_V1_3,
BLUEPRINT_EXT_NAMESPACE_V1_4,
BLUEPRINT_EXT_NAMESPACE_V1_5,
BLUEPRINT_EXT_NAMESPACE_V1_6)));
private static final Logger LOGGER = LoggerFactory.getLogger(ExtNamespaceHandler.class);
private int idCounter;
public URL getSchemaLocation(String namespace) {
if (isExtNamespace(namespace)) {
String v = namespace.substring("http://aries.apache.org/blueprint/xmlns/blueprint-ext/v".length());
return getClass().getResource("blueprint-ext-" + v + ".xsd");
} else if ("http://www.w3.org/XML/1998/namespace".equals(namespace)) {
return getClass().getResource("xml.xsd");
}
return null;
}
public static boolean isExtNamespace(String e) {
return EXT_URIS.contains(e);
}
public Set<Class> getManagedClasses() {
return new HashSet<Class>(Arrays.asList(
PropertyPlaceholder.class
));
}
public Metadata parse(Element element, ParserContext context) {
LOGGER.debug("Parsing element {{}}{}", element.getNamespaceURI(), element.getLocalName());
if (nodeNameEquals(element, PROPERTY_PLACEHOLDER_ELEMENT)) {
return parsePropertyPlaceholder(context, element);
} else if (nodeNameEquals(element, BEAN)) {
return context.parseElement(BeanMetadata.class, context.getEnclosingComponent(), element);
} else if (nodeNameEquals(element, NULL_PROXY_ELEMENT)) {
return parseNullProxy(element, context);
} else {
throw new ComponentDefinitionException("Unsupported element: " + element.getNodeName());
}
}
public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
if (node instanceof Attr && nodeNameEquals(node, PROXY_METHOD_ATTRIBUTE)) {
return decorateProxyMethod(node, component, context);
} else if (node instanceof Attr && nodeNameEquals(node, ROLE_ATTRIBUTE)) {
return decorateRole(node, component, context);
} else if (node instanceof Attr && nodeNameEquals(node, FIELD_INJECTION_ATTRIBUTE)) {
return decorateFieldInjection(node, component, context);
} else if (node instanceof Attr && nodeNameEquals(node, NON_STANDARD_SETTERS_ATTRIBUTE)) {
return decorateNonStandardSetters(node, component, context);
} else if (node instanceof Attr && nodeNameEquals(node, DEFAULT_REFERENCE_BEAN)) {
return decorateDefaultBean(node, component, context);
} else if (node instanceof Attr && nodeNameEquals(node, FILTER_ATTRIBUTE)) {
return decorateFilter(node, component, context);
} else if (node instanceof Element && nodeNameEquals(node, ADDITIONAL_INTERFACES)) {
return decorateAdditionalInterfaces(node, component, context);
} else if (node instanceof Element && nodeNameEquals(node, BEAN)) {
return context.parseElement(BeanMetadata.class, component, (Element) node);
} else if (node instanceof Attr && nodeNameEquals(node, DAMPING_ATTRIBUTE)) {
return decorateDamping(node, component, context);
} else if (node instanceof Attr && nodeNameEquals(node, LIFECYCLE_ATTRIBUTE)) {
return decorateLifecycle(node, component, context);
} else if (node instanceof Attr && nodeNameEquals(node, RAW_CONVERSION_ATTRIBUTE)) {
return decorateRawConversion(node, component, context);
} else if (node instanceof Element && nodeNameEquals(node, ARGUMENT)) {
return parseBeanArgument(context, (Element) node);
} else {
throw new ComponentDefinitionException("Unsupported node: " + node.getNodeName());
}
}
private ComponentMetadata parseNullProxy(Element element, ParserContext context) {
MutableBeanMetadata mb = context.createMetadata(MutableBeanMetadata.class);
mb.setRuntimeClass(NullProxy.class);
mb.addArgument(createRef(context, "blueprintContainer"), null, -1);
mb.setId(element.hasAttribute(ID_ATTRIBUTE) ? element.getAttribute(ID_ATTRIBUTE) : "null-proxy");
return mb;
}
private ComponentMetadata decorateAdditionalInterfaces(Node node, ComponentMetadata component,
ParserContext context) {
if (!(component instanceof MutableReferenceMetadata)) {
throw new ComponentDefinitionException("Expected an instanceof MutableReferenceMetadata");
}
MutableReferenceMetadata mrm = (MutableReferenceMetadata) component;
List<String> list = new ArrayList<String>();
Node nd = node.getFirstChild();
while (nd != null) {
if (nd instanceof Element && nodeNameEquals(nd, INTERFACE_VALUE)) {
list.add(((Element) nd).getTextContent());
}
nd = nd.getNextSibling();
}
mrm.setExtraInterfaces(list);
return component;
}
private ComponentMetadata decorateDefaultBean(Node node,
ComponentMetadata component, ParserContext context)
{
if (!(component instanceof ReferenceMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <reference> element");
}
if (!(component instanceof MutableReferenceMetadata)) {
throw new ComponentDefinitionException("Expected an instanceof MutableReferenceMetadata");
}
String value = ((Attr) node).getValue();
((MutableReferenceMetadata) component).setDefaultBean(value);
return component;
}
private ComponentMetadata decorateFieldInjection(Node node, ComponentMetadata component, ParserContext context) {
if (!(component instanceof BeanMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <bean> element");
}
if (!(component instanceof MutableBeanMetadata)) {
throw new ComponentDefinitionException("Expected an instanceof MutableBeanMetadata");
}
String value = ((Attr) node).getValue();
((MutableBeanMetadata) component).setFieldInjection("true".equals(value) || "1".equals(value));
return component;
}
private ComponentMetadata decorateNonStandardSetters(Node node, ComponentMetadata component, ParserContext context) {
if (!(component instanceof BeanMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <bean> element");
}
if (!(component instanceof MutableBeanMetadata)) {
throw new ComponentDefinitionException("Expected an instanceof MutableBeanMetadata");
}
String value = ((Attr) node).getValue();
((MutableBeanMetadata) component).setNonStandardSetters("true".equals(value) || "1".equals(value));
return component;
}
private ComponentMetadata decorateRole(Node node, ComponentMetadata component, ParserContext context) {
if (!(component instanceof BeanMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <bean> element");
}
if (!(component instanceof MutableBeanMetadata)) {
throw new ComponentDefinitionException("Expected an instance of MutableBeanMetadata");
}
boolean processor = false;
String value = ((Attr) node).getValue();
String[] flags = value.trim().split(" ");
for (String flag : flags) {
if (ROLE_PROCESSOR.equals(flag)) {
processor = true;
} else {
throw new ComponentDefinitionException("Unknown proxy method: " + flag);
}
}
((MutableBeanMetadata) component).setProcessor(processor);
return component;
}
private ComponentMetadata decorateProxyMethod(Node node, ComponentMetadata component, ParserContext context) {
if (!(component instanceof ServiceReferenceMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <reference> or <reference-list> element");
}
if (!(component instanceof MutableServiceReferenceMetadata)) {
throw new ComponentDefinitionException("Expected an instance of MutableServiceReferenceMetadata");
}
int method = 0;
String value = ((Attr) node).getValue();
String[] flags = value.trim().split(" ");
for (String flag : flags) {
if (PROXY_METHOD_DEFAULT.equals(flag)) {
method += ExtendedReferenceListMetadata.PROXY_METHOD_DEFAULT;
} else if (PROXY_METHOD_CLASSES.equals(flag)) {
method += ExtendedReferenceListMetadata.PROXY_METHOD_CLASSES;
} else if (PROXY_METHOD_GREEDY.equals(flag)) {
method += ExtendedReferenceListMetadata.PROXY_METHOD_GREEDY;
} else {
throw new ComponentDefinitionException("Unknown proxy method: " + flag);
}
}
if ((method & ExtendedReferenceListMetadata.PROXY_METHOD_GREEDY) != 0 && !(component instanceof ReferenceListMetadata)) {
throw new ComponentDefinitionException("Greedy proxying is only available for <reference-list> element");
}
((MutableServiceReferenceMetadata) component).setProxyMethod(method);
return component;
}
private ComponentMetadata decorateFilter(Node node,
ComponentMetadata component, ParserContext context)
{
if (!(component instanceof ServiceReferenceMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <reference> or <reference-list> element");
}
if (!(component instanceof MutableServiceReferenceMetadata)) {
throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
}
String value = ((Attr) node).getValue();
((MutableServiceReferenceMetadata) component).setExtendedFilter(createValue(context, value));
return component;
}
private ComponentMetadata decorateDamping(Node node, ComponentMetadata component, ParserContext context) {
if (!(component instanceof ReferenceMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <reference> element");
}
if (!(component instanceof MutableReferenceMetadata)) {
throw new ComponentDefinitionException("Expected an instance of MutableReferenceMetadata");
}
int damping = ExtendedReferenceMetadata.DAMPING_GREEDY;
String value = ((Attr) node).getValue();
if (DAMPING_RELUCTANT.equals(value)) {
damping = ExtendedReferenceMetadata.DAMPING_RELUCTANT;
} else if (!DAMPING_GREEDY.equals(value)) {
throw new ComponentDefinitionException("Unknown damping method: " + value);
}
((MutableReferenceMetadata) component).setDamping(damping);
return component;
}
private ComponentMetadata decorateLifecycle(Node node, ComponentMetadata component, ParserContext context) {
if (!(component instanceof ReferenceMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <reference> element");
}
if (!(component instanceof MutableReferenceMetadata)) {
throw new ComponentDefinitionException("Expected an instance of MutableReferenceMetadata");
}
int lifecycle = ExtendedReferenceMetadata.LIFECYCLE_DYNAMIC;
String value = ((Attr) node).getValue();
if (LIFECYCLE_STATIC.equals(value)) {
lifecycle = ExtendedReferenceMetadata.LIFECYCLE_STATIC;
} else if (!LIFECYCLE_DYNAMIC.equals(value)) {
throw new ComponentDefinitionException("Unknown lifecycle method: " + value);
}
((MutableReferenceMetadata) component).setLifecycle(lifecycle);
return component;
}
private ComponentMetadata decorateRawConversion(Node node, ComponentMetadata component, ParserContext context) {
if (!(component instanceof BeanMetadata)) {
throw new ComponentDefinitionException("Attribute " + node.getNodeName() + " can only be used on a <bean> element");
}
if (!(component instanceof MutableBeanMetadata)) {
throw new ComponentDefinitionException("Expected an instanceof MutableBeanMetadata");
}
String value = ((Attr) node).getValue();
((MutableBeanMetadata) component).setRawConversion("true".equals(value) || "1".equals(value));
return component;
}
private ComponentMetadata parseBeanArgument(ParserContext context, Element element) {
MutableBeanMetadata mbm = (MutableBeanMetadata) context.getEnclosingComponent();
BeanArgument arg = context.parseElement(BeanArgument.class, mbm, element);
int index = 0;
for (Node node = element.getPreviousSibling(); node != null; node = node.getPreviousSibling()) {
if (nodeNameEquals(node, ARGUMENT)) {
index++;
}
}
List<BeanArgument> args = new ArrayList<BeanArgument>(mbm.getArguments());
if (index == args.size()) {
mbm.addArgument(arg);
} else {
for (BeanArgument ba : args) {
mbm.removeArgument(ba);
}
args.add(index, arg);
for (BeanArgument ba : args) {
mbm.addArgument(ba);
}
}
return mbm;
}
private Metadata parsePropertyPlaceholder(ParserContext context, Element element) {
MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
metadata.setProcessor(true);
metadata.setId(getId(context, element));
metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
metadata.setRuntimeClass(PropertyPlaceholder.class);
metadata.setInitMethod("init");
String prefix = element.hasAttribute(PLACEHOLDER_PREFIX_ATTRIBUTE)
? element.getAttribute(PLACEHOLDER_PREFIX_ATTRIBUTE)
: "${";
metadata.addProperty("placeholderPrefix", createValue(context, prefix));
String suffix = element.hasAttribute(PLACEHOLDER_SUFFIX_ATTRIBUTE)
? element.getAttribute(PLACEHOLDER_SUFFIX_ATTRIBUTE)
: "}";
metadata.addProperty("placeholderSuffix", createValue(context, suffix));
metadata.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
String nullValue = element.hasAttribute(PLACEHOLDER_NULL_VALUE_ATTRIBUTE)
? element.getAttribute(PLACEHOLDER_NULL_VALUE_ATTRIBUTE)
: null;
if (nullValue != null) {
metadata.addProperty("nullValue", createValue(context, nullValue));
}
String defaultsRef = element.hasAttribute(DEFAULTS_REF_ATTRIBUTE) ? element.getAttribute(DEFAULTS_REF_ATTRIBUTE) : null;
if (defaultsRef != null) {
metadata.addProperty("defaultProperties", createRef(context, defaultsRef));
}
String ignoreMissingLocations = element.hasAttribute(IGNORE_MISSING_LOCATIONS_ATTRIBUTE) ? element.getAttribute(IGNORE_MISSING_LOCATIONS_ATTRIBUTE) : null;
if (ignoreMissingLocations != null) {
metadata.addProperty("ignoreMissingLocations", createValue(context, ignoreMissingLocations));
}
String systemProperties = element.hasAttribute(SYSTEM_PROPERTIES_ATTRIBUTE) ? element.getAttribute(SYSTEM_PROPERTIES_ATTRIBUTE) : null;
if (systemProperties != null) {
metadata.addProperty("systemProperties", createValue(context, systemProperties));
}
String evaluator = element.hasAttribute(EVALUATOR_ATTRIBUTE) ? element.getAttribute(EVALUATOR_ATTRIBUTE) : null;
if (evaluator != null) {
throw new IllegalStateException("Evaluators are not supported outside OSGi");
}
// Parse elements
List<String> locations = new ArrayList<String>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isExtNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, DEFAULT_PROPERTIES_ELEMENT)) {
if (defaultsRef != null) {
throw new ComponentDefinitionException("Only one of " + DEFAULTS_REF_ATTRIBUTE + " attribute or " + DEFAULT_PROPERTIES_ELEMENT + " element is allowed");
}
Metadata props = parseDefaultProperties(context, metadata, e);
metadata.addProperty("defaultProperties", props);
} else if (nodeNameEquals(e, LOCATION_ELEMENT)) {
locations.add(getTextValue(e));
}
}
}
}
if (!locations.isEmpty()) {
metadata.addProperty("locations", createList(context, locations));
}
validatePlaceholder(metadata, context.getComponentDefinitionRegistry());
return metadata;
}
private boolean validatePlaceholder(MutableBeanMetadata metadata, ComponentDefinitionRegistry registry) {
for (String id : registry.getComponentDefinitionNames()) {
ComponentMetadata component = registry.getComponentDefinition(id);
if (component instanceof ExtendedBeanMetadata) {
ExtendedBeanMetadata bean = (ExtendedBeanMetadata) component;
if (bean.getRuntimeClass() != null && AbstractPropertyPlaceholder.class.isAssignableFrom(bean.getRuntimeClass())) {
if (arePropertiesEquals(bean, metadata, "placeholderPrefix")
&& arePropertiesEquals(bean, metadata, "placeholderSuffix")) {
if (!arePropertiesEquals(bean, metadata, "systemProperties")
|| !arePropertiesEquals(bean, metadata, "ignoreMissingLocations")) {
throw new ComponentDefinitionException("Multiple incompatible placeholders found");
}
// Merge both placeholders
mergeList(bean, metadata, "locations");
mergeMap(bean, metadata, "defaultProperties");
return false;
}
}
}
}
return true;
}
private void mergeList(ExtendedBeanMetadata bean1, MutableBeanMetadata bean2, String name) {
Metadata m1 = getProperty(bean1, name);
Metadata m2 = getProperty(bean2, name);
if (m1 == null && m2 != null) {
((MutableBeanMetadata) bean1).addProperty(name, m2);
} else if (m1 != null && m2 != null) {
if (!(m1 instanceof MutableCollectionMetadata) || !(m2 instanceof MutableCollectionMetadata)) {
throw new ComponentDefinitionException("Unable to merge " + name + " list properties");
}
MutableCollectionMetadata c1 = (MutableCollectionMetadata) m1;
MutableCollectionMetadata c2 = (MutableCollectionMetadata) m2;
for (Metadata v : c2.getValues()) {
c1.addValue(v);
}
}
}
private void mergeMap(ExtendedBeanMetadata bean1, MutableBeanMetadata bean2, String name) {
Metadata m1 = getProperty(bean1, name);
Metadata m2 = getProperty(bean2, name);
if (m1 == null && m2 != null) {
((MutableBeanMetadata) bean1).addProperty(name, m2);
} else if (m1 != null && m2 != null) {
if (!(m1 instanceof MutableMapMetadata) || !(m2 instanceof MutableMapMetadata)) {
throw new ComponentDefinitionException("Unable to merge " + name + " list properties");
}
MutableMapMetadata c1 = (MutableMapMetadata) m1;
MutableMapMetadata c2 = (MutableMapMetadata) m2;
for (MapEntry e : c2.getEntries()) {
c1.addEntry(e);
}
}
}
private boolean arePropertiesEquals(BeanMetadata bean1, BeanMetadata bean2, String name) {
String v1 = getPlaceholderProperty(bean1, name);
String v2 = getPlaceholderProperty(bean2, name);
return v1 == null ? v2 == null : v1.equals(v2);
}
private String getPlaceholderProperty(BeanMetadata bean, String name) {
Metadata metadata = getProperty(bean, name);
if (metadata instanceof ValueMetadata) {
return ((ValueMetadata) metadata).getStringValue();
}
return null;
}
private Metadata getProperty(BeanMetadata bean, String name) {
for (BeanProperty property : bean.getProperties()) {
if (name.equals(property.getName())) {
return property.getValue();
}
}
return null;
}
private Metadata parseDefaultProperties(ParserContext context, MutableBeanMetadata enclosingComponent, Element element) {
MutableMapMetadata props = context.createMetadata(MutableMapMetadata.class);
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isExtNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, PROPERTY_ELEMENT)) {
BeanProperty prop = context.parseElement(BeanProperty.class, enclosingComponent, e);
props.addEntry(createValue(context, prop.getName(), String.class.getName()), prop.getValue());
}
}
}
}
return props;
}
public String getId(ParserContext context, Element element) {
if (element.hasAttribute(ID_ATTRIBUTE)) {
return element.getAttribute(ID_ATTRIBUTE);
} else {
return generateId(context);
}
}
public void generateIdIfNeeded(ParserContext context, MutableComponentMetadata metadata) {
if (metadata.getId() == null) {
metadata.setId(generateId(context));
}
}
private String generateId(ParserContext context) {
String id;
do {
id = ".ext-" + ++idCounter;
} while (context.getComponentDefinitionRegistry().containsComponentDefinition(id));
return id;
}
private static ValueMetadata createValue(ParserContext context, String value) {
return createValue(context, value, null);
}
private static ValueMetadata createValue(ParserContext context, String value, String type) {
MutableValueMetadata m = context.createMetadata(MutableValueMetadata.class);
m.setStringValue(value);
m.setType(type);
return m;
}
private static RefMetadata createRef(ParserContext context, String value) {
MutableRefMetadata m = context.createMetadata(MutableRefMetadata.class);
m.setComponentId(value);
return m;
}
private static IdRefMetadata createIdRef(ParserContext context, String value) {
MutableIdRefMetadata m = context.createMetadata(MutableIdRefMetadata.class);
m.setComponentId(value);
return m;
}
private static CollectionMetadata createList(ParserContext context, List<String> list) {
MutableCollectionMetadata m = context.createMetadata(MutableCollectionMetadata.class);
m.setCollectionClass(List.class);
m.setValueType(String.class.getName());
for (String v : list) {
m.addValue(createValue(context, v, String.class.getName()));
}
return m;
}
private static String getTextValue(Element element) {
StringBuffer value = new StringBuffer();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
value.append(item.getNodeValue());
}
}
return value.toString();
}
private static boolean nodeNameEquals(Node node, String name) {
return (name.equals(node.getNodeName()) || name.equals(node.getLocalName()));
}
public static boolean isBlueprintNamespace(String ns) {
return BLUEPRINT_NAMESPACE.equals(ns);
}
}
| 9,637 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/container/NoOsgiRecipeBuilder.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.blueprint.container;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.ExtendedBeanMetadata;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.di.*;
import org.apache.aries.blueprint.ext.ComponentFactoryMetadata;
import org.apache.aries.blueprint.ext.DependentComponentFactoryMetadata;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.apache.aries.blueprint.utils.ServiceListener;
import org.osgi.service.blueprint.reflect.*;
import java.util.*;
public class NoOsgiRecipeBuilder {
private final Set<String> names = new HashSet<String>();
private final BlueprintContainerImpl blueprintContainer;
private final ComponentDefinitionRegistry registry;
private final IdSpace recipeIdSpace;
public NoOsgiRecipeBuilder(BlueprintContainerImpl blueprintContainer, IdSpace recipeIdSpace) {
this.recipeIdSpace = recipeIdSpace;
this.blueprintContainer = blueprintContainer;
this.registry = blueprintContainer.getComponentDefinitionRegistry();
}
public BlueprintRepository createRepository() {
BlueprintRepository repository = new NoOsgiBlueprintRepository(blueprintContainer);
// Create component recipes
for (String name : registry.getComponentDefinitionNames()) {
ComponentMetadata component = registry.getComponentDefinition(name);
Recipe recipe = createRecipe(component);
repository.putRecipe(recipe.getName(), recipe);
}
repository.validate();
return repository;
}
public Recipe createRecipe(ComponentMetadata component) {
// Custom components should be handled before built-in ones
// in case we have a custom component that also implements a built-in metadata
if (component instanceof DependentComponentFactoryMetadata) {
return createDependentComponentFactoryMetadata((DependentComponentFactoryMetadata) component);
} else if (component instanceof ComponentFactoryMetadata) {
return createComponentFactoryMetadata((ComponentFactoryMetadata) component);
} else if (component instanceof BeanMetadata) {
return createBeanRecipe((BeanMetadata) component);
} else if (component instanceof ServiceMetadata) {
throw new IllegalArgumentException("OSGi services are not supported");
} else if (component instanceof ReferenceMetadata) {
throw new IllegalArgumentException("OSGi references are not supported");
} else if (component instanceof ReferenceListMetadata) {
throw new IllegalArgumentException("OSGi references are not supported");
} else if (component instanceof PassThroughMetadata) {
return createPassThroughRecipe((PassThroughMetadata) component);
} else {
throw new IllegalStateException("Unsupported component type " + component.getClass());
}
}
private Recipe createComponentFactoryMetadata(ComponentFactoryMetadata metadata) {
return new ComponentFactoryRecipe<ComponentFactoryMetadata>(
metadata.getId(), metadata, blueprintContainer, getDependencies(metadata));
}
private Recipe createDependentComponentFactoryMetadata(DependentComponentFactoryMetadata metadata) {
return new DependentComponentFactoryRecipe(
metadata.getId(), metadata, blueprintContainer, getDependencies(metadata));
}
private List<Recipe> getDependencies(ComponentMetadata metadata) {
List<Recipe> deps = new ArrayList<Recipe>();
for (String name : metadata.getDependsOn()) {
deps.add(new RefRecipe(getName(null), name));
}
return deps;
}
private Recipe createPassThroughRecipe(PassThroughMetadata passThroughMetadata) {
return new PassThroughRecipe(getName(passThroughMetadata.getId()),
passThroughMetadata.getObject());
}
private Object getBeanClass(BeanMetadata beanMetadata) {
if (beanMetadata instanceof ExtendedBeanMetadata) {
ExtendedBeanMetadata extBeanMetadata = (ExtendedBeanMetadata) beanMetadata;
if (extBeanMetadata.getRuntimeClass() != null) {
return extBeanMetadata.getRuntimeClass();
}
}
return beanMetadata.getClassName();
}
private boolean allowsFieldInjection(BeanMetadata beanMetadata) {
if (beanMetadata instanceof ExtendedBeanMetadata) {
return ((ExtendedBeanMetadata) beanMetadata).getFieldInjection();
}
return false;
}
private BeanRecipe createBeanRecipe(BeanMetadata beanMetadata) {
BeanRecipe recipe = new BeanRecipe(
getName(beanMetadata.getId()),
blueprintContainer,
getBeanClass(beanMetadata),
allowsFieldInjection(beanMetadata));
// Create refs for explicit dependencies
recipe.setExplicitDependencies(getDependencies(beanMetadata));
recipe.setPrototype(MetadataUtil.isPrototypeScope(beanMetadata) || MetadataUtil.isCustomScope(beanMetadata));
recipe.setInitMethod(beanMetadata.getInitMethod());
recipe.setDestroyMethod(beanMetadata.getDestroyMethod());
recipe.setInterceptorLookupKey(beanMetadata);
List<BeanArgument> beanArguments = beanMetadata.getArguments();
if (beanArguments != null && !beanArguments.isEmpty()) {
boolean hasIndex = (beanArguments.get(0).getIndex() >= 0);
if (hasIndex) {
List<BeanArgument> beanArgumentsCopy = new ArrayList<BeanArgument>(beanArguments);
Collections.sort(beanArgumentsCopy, MetadataUtil.BEAN_COMPARATOR);
beanArguments = beanArgumentsCopy;
}
List<Object> arguments = new ArrayList<Object>();
List<String> argTypes = new ArrayList<String>();
for (BeanArgument argument : beanArguments) {
Recipe value = getValue(argument.getValue(), null);
arguments.add(value);
argTypes.add(argument.getValueType());
}
recipe.setArguments(arguments);
recipe.setArgTypes(argTypes);
recipe.setReorderArguments(!hasIndex);
}
recipe.setFactoryMethod(beanMetadata.getFactoryMethod());
if (beanMetadata.getFactoryComponent() != null) {
recipe.setFactoryComponent(getValue(beanMetadata.getFactoryComponent(), null));
}
for (BeanProperty property : beanMetadata.getProperties()) {
Recipe value = getValue(property.getValue(), null);
recipe.setProperty(property.getName(), value);
}
return recipe;
}
private Recipe createRecipe(RegistrationListener listener) {
BeanRecipe recipe = new BeanRecipe(getName(null), blueprintContainer, ServiceListener.class, false);
recipe.setProperty("listener", getValue(listener.getListenerComponent(), null));
if (listener.getRegistrationMethod() != null) {
recipe.setProperty("registerMethod", listener.getRegistrationMethod());
}
if (listener.getUnregistrationMethod() != null) {
recipe.setProperty("unregisterMethod", listener.getUnregistrationMethod());
}
recipe.setProperty("blueprintContainer", blueprintContainer);
return recipe;
}
private Recipe createRecipe(ReferenceListener listener) {
BeanRecipe recipe = new BeanRecipe(getName(null), blueprintContainer, AbstractServiceReferenceRecipe.Listener.class, false);
recipe.setProperty("listener", getValue(listener.getListenerComponent(), null));
recipe.setProperty("metadata", listener);
recipe.setProperty("blueprintContainer", blueprintContainer);
return recipe;
}
private Recipe getValue(Metadata v, Object groupingType) {
if (v instanceof NullMetadata) {
return null;
} else if (v instanceof ComponentMetadata) {
return createRecipe((ComponentMetadata) v);
} else if (v instanceof ValueMetadata) {
ValueMetadata stringValue = (ValueMetadata) v;
Object type = stringValue.getType();
type = (type == null) ? groupingType : type;
ValueRecipe vr = new ValueRecipe(getName(null), stringValue, type);
return vr;
} else if (v instanceof RefMetadata) {
// TODO: make it work with property-placeholders?
String componentName = ((RefMetadata) v).getComponentId();
RefRecipe rr = new RefRecipe(getName(null), componentName);
return rr;
} else if (v instanceof CollectionMetadata) {
CollectionMetadata collectionMetadata = (CollectionMetadata) v;
Class<?> cl = collectionMetadata.getCollectionClass();
String type = collectionMetadata.getValueType();
if (cl == Object[].class) {
ArrayRecipe ar = new ArrayRecipe(getName(null), type);
for (Metadata lv : collectionMetadata.getValues()) {
ar.add(getValue(lv, type));
}
return ar;
} else {
CollectionRecipe cr = new CollectionRecipe(getName(null), cl != null ? cl : ArrayList.class, type);
for (Metadata lv : collectionMetadata.getValues()) {
cr.add(getValue(lv, type));
}
return cr;
}
} else if (v instanceof MapMetadata) {
return createMapRecipe((MapMetadata) v);
} else if (v instanceof PropsMetadata) {
PropsMetadata mapValue = (PropsMetadata) v;
MapRecipe mr = new MapRecipe(getName(null), Properties.class, String.class, String.class);
for (MapEntry entry : mapValue.getEntries()) {
Recipe key = getValue(entry.getKey(), String.class);
Recipe val = getValue(entry.getValue(), String.class);
mr.put(key, val);
}
return mr;
} else if (v instanceof IdRefMetadata) {
// TODO: make it work with property-placeholders?
String componentName = ((IdRefMetadata) v).getComponentId();
IdRefRecipe rnr = new IdRefRecipe(getName(null), componentName);
return rnr;
} else {
throw new IllegalStateException("Unsupported value: " + (v != null ? v.getClass().getName() : "null"));
}
}
private MapRecipe createMapRecipe(MapMetadata mapValue) {
String keyType = mapValue.getKeyType();
String valueType = mapValue.getValueType();
MapRecipe mr = new MapRecipe(getName(null), HashMap.class, keyType, valueType);
for (MapEntry entry : mapValue.getEntries()) {
Recipe key = getValue(entry.getKey(), keyType);
Recipe val = getValue(entry.getValue(), valueType);
mr.put(key, val);
}
return mr;
}
private String getName(String name) {
if (name == null) {
do {
name = "#recipe-" + recipeIdSpace.nextId();
} while (names.contains(name) || registry.containsComponentDefinition(name));
}
names.add(name);
return name;
}
}
| 9,638 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/container/BlueprintContainerImpl.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.blueprint.container;
import java.net.URI;
import java.net.URL;
import java.security.AccessControlContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.blueprint.ComponentDefinitionRegistryProcessor;
import org.apache.aries.blueprint.ExtendedBeanMetadata;
import org.apache.aries.blueprint.Processor;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.Repository;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.apache.aries.blueprint.parser.Parser;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.apache.aries.blueprint.reflect.PassThroughMetadataImpl;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.NoSuchComponentException;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BlueprintContainerImpl implements ExtendedBlueprintContainer {
private static final Logger LOGGER = LoggerFactory.getLogger(BlueprintContainerImpl.class);
private final ClassLoader loader;
private final List<URL> resources;
private final AggregateConverter converter;
private final ComponentDefinitionRegistryImpl componentDefinitionRegistry;
private final AtomicBoolean destroyed = new AtomicBoolean(false);
private final IdSpace tempRecipeIdSpace = new IdSpace();
private BlueprintRepository repository;
private List<Processor> processors = new ArrayList<Processor>();
private Map<String, String> properties;
private NamespaceHandlerSet nsHandlerSet;
public BlueprintContainerImpl(ClassLoader loader, List<URL> resources) throws Exception {
this(loader, resources, null, true);
}
public BlueprintContainerImpl(ClassLoader loader, List<URL> resources, boolean init) throws Exception {
this(loader, resources, null, init);
}
public BlueprintContainerImpl(ClassLoader loader, List<URL> resources, Map<String, String> properties, boolean init) throws Exception {
this(loader, resources, properties, null, init);
}
public BlueprintContainerImpl(ClassLoader loader, List<URL> resources, Map<String, String> properties,
NamespaceHandlerSet nsHandlerSet, boolean init) throws Exception {
this.loader = loader;
this.converter = new AggregateConverter(this);
this.componentDefinitionRegistry = new ComponentDefinitionRegistryImpl();
this.resources = resources;
this.properties = properties;
this.nsHandlerSet = nsHandlerSet;
if (init) {
init();
}
}
public String getProperty(String key) {
if (properties != null && properties.containsKey(key)) {
return properties.get(key);
}
return System.getProperty(key);
}
protected NamespaceHandlerSet createNamespaceHandlerSet(Set<URI> namespaces) {
NamespaceHandlerSet handlerSet = createNamespaceHandlerSet();
// Check namespaces
Set<URI> unsupported = new LinkedHashSet<URI>();
for (URI ns : namespaces) {
if (!handlerSet.getNamespaces().contains(ns)) {
unsupported.add(ns);
}
}
if (unsupported.size() > 0) {
throw new IllegalArgumentException("Unsupported namespaces: " + unsupported.toString());
}
return handlerSet;
}
protected NamespaceHandlerSet createNamespaceHandlerSet() {
return nsHandlerSet == null ? new SimpleNamespaceHandlerSet() : nsHandlerSet;
}
public void init() throws Exception {
init(true);
}
public void init(boolean validate) throws Exception {
// Parse xml resources
Parser parser = new Parser();
parser.parse(getResources());
// Check namespaces
Set<URI> namespaces = parser.getNamespaces();
// Create handler set
NamespaceHandlerSet handlerSet = createNamespaceHandlerSet(namespaces);
// Add predefined beans
componentDefinitionRegistry.registerComponentDefinition(new PassThroughMetadataImpl("blueprintContainer", this));
if (validate) {
// Validate
parser.validate(handlerSet.getSchema());
}
// Populate
parser.populate(handlerSet, componentDefinitionRegistry);
// Create repository
repository = new NoOsgiRecipeBuilder(this, tempRecipeIdSpace).createRepository();
// Processors handling
processTypeConverters();
processProcessors();
// Instantiate eager singletons
instantiateEagerComponents();
}
public void destroy() {
repository.destroy();
}
public List<URL> getResources() {
return resources;
}
public Converter getConverter() {
return converter;
}
public Class loadClass(String name) throws ClassNotFoundException {
return loader.loadClass(name);
}
public URL getResource(String name) {
return loader.getResource(name);
}
public AccessControlContext getAccessControlContext() {
return null;
}
public ComponentDefinitionRegistryImpl getComponentDefinitionRegistry() {
return componentDefinitionRegistry;
}
public <T extends Processor> List<T> getProcessors(Class<T> clazz) {
List<T> p = new ArrayList<T>();
for (Processor processor : processors) {
if (clazz.isInstance(processor)) {
p.add(clazz.cast(processor));
}
}
return p;
}
public Set<String> getComponentIds() {
return new LinkedHashSet<String>(componentDefinitionRegistry.getComponentDefinitionNames());
}
public Object getComponentInstance(String id) {
if (repository == null || destroyed.get()) {
throw new NoSuchComponentException(id);
}
try {
LOGGER.debug("Instantiating component {}", id);
return repository.create(id);
} catch (NoSuchComponentException e) {
throw e;
} catch (ComponentDefinitionException e) {
throw e;
} catch (Throwable t) {
throw new ComponentDefinitionException("Cound not create component instance for " + id, t);
}
}
public ComponentMetadata getComponentMetadata(String id) {
ComponentMetadata metadata = componentDefinitionRegistry.getComponentDefinition(id);
if (metadata == null) {
throw new NoSuchComponentException(id);
}
return metadata;
}
public <T extends ComponentMetadata> Collection<T> getMetadata(Class<T> clazz) {
Collection<T> metadatas = new ArrayList<T>();
for (String name : componentDefinitionRegistry.getComponentDefinitionNames()) {
ComponentMetadata component = componentDefinitionRegistry.getComponentDefinition(name);
getMetadata(clazz, component, metadatas);
}
metadatas = Collections.unmodifiableCollection(metadatas);
return metadatas;
}
public BlueprintRepository getRepository() {
return repository;
}
private <T extends ComponentMetadata> void getMetadata(Class<T> clazz, Metadata component, Collection<T> metadatas) {
if (component == null) {
return;
}
if (clazz.isInstance(component)) {
metadatas.add(clazz.cast(component));
}
if (component instanceof BeanMetadata) {
getMetadata(clazz, ((BeanMetadata) component).getFactoryComponent(), metadatas);
for (BeanArgument arg : ((BeanMetadata) component).getArguments()) {
getMetadata(clazz, arg.getValue(), metadatas);
}
for (BeanProperty prop : ((BeanMetadata) component).getProperties()) {
getMetadata(clazz, prop.getValue(), metadatas);
}
}
if (component instanceof CollectionMetadata) {
for (Metadata m : ((CollectionMetadata) component).getValues()) {
getMetadata(clazz, m, metadatas);
}
}
if (component instanceof MapMetadata) {
for (MapEntry m : ((MapMetadata) component).getEntries()) {
getMetadata(clazz, m.getKey(), metadatas);
getMetadata(clazz, m.getValue(), metadatas);
}
}
if (component instanceof PropsMetadata) {
for (MapEntry m : ((PropsMetadata) component).getEntries()) {
getMetadata(clazz, m.getKey(), metadatas);
getMetadata(clazz, m.getValue(), metadatas);
}
}
if (component instanceof ServiceReferenceMetadata) {
for (ReferenceListener l : ((ServiceReferenceMetadata) component).getReferenceListeners()) {
getMetadata(clazz, l.getListenerComponent(), metadatas);
}
}
if (component instanceof ServiceMetadata) {
getMetadata(clazz, ((ServiceMetadata) component).getServiceComponent(), metadatas);
for (MapEntry m : ((ServiceMetadata) component).getServiceProperties()) {
getMetadata(clazz, m.getKey(), metadatas);
getMetadata(clazz, m.getValue(), metadatas);
}
for (RegistrationListener l : ((ServiceMetadata) component).getRegistrationListeners()) {
getMetadata(clazz, l.getListenerComponent(), metadatas);
}
}
}
private void processTypeConverters() throws Exception {
List<String> typeConverters = new ArrayList<String>();
for (Target target : componentDefinitionRegistry.getTypeConverters()) {
if (target instanceof ComponentMetadata) {
typeConverters.add(((ComponentMetadata) target).getId());
} else if (target instanceof RefMetadata) {
typeConverters.add(((RefMetadata) target).getComponentId());
} else {
throw new ComponentDefinitionException("Unexpected metadata for type converter: " + target);
}
}
Map<String, Object> objects = repository.createAll(typeConverters, Arrays.<Class<?>>asList(Converter.class));
for (String name : typeConverters) {
Object obj = objects.get(name);
if (obj instanceof Converter) {
converter.registerConverter((Converter) obj);
} else {
throw new ComponentDefinitionException("Type converter " + obj + " does not implement the " + Converter.class.getName() + " interface");
}
}
}
private void processProcessors() throws Exception {
// Instantiate ComponentDefinitionRegistryProcessor and BeanProcessor
for (BeanMetadata bean : getMetadata(BeanMetadata.class)) {
if (bean instanceof ExtendedBeanMetadata && !((ExtendedBeanMetadata) bean).isProcessor()) {
continue;
}
Class clazz = null;
if (bean instanceof ExtendedBeanMetadata) {
clazz = ((ExtendedBeanMetadata) bean).getRuntimeClass();
}
if (clazz == null && bean.getClassName() != null) {
clazz = loadClass(bean.getClassName());
}
if (clazz == null) {
continue;
}
if (ComponentDefinitionRegistryProcessor.class.isAssignableFrom(clazz)) {
Object obj = repository.create(bean.getId(), Arrays.<Class<?>>asList(ComponentDefinitionRegistryProcessor.class));
((ComponentDefinitionRegistryProcessor) obj).process(componentDefinitionRegistry);
} else if (Processor.class.isAssignableFrom(clazz)) {
Object obj = repository.create(bean.getId(), Arrays.<Class<?>>asList(Processor.class));
this.processors.add((Processor) obj);
} else {
continue;
}
updateUninstantiatedRecipes();
}
}
private void updateUninstantiatedRecipes() {
Repository tmpRepo = new NoOsgiRecipeBuilder(this, tempRecipeIdSpace).createRepository();
LOGGER.debug("Updating blueprint repository");
for (String name : repository.getNames()) {
if (repository.getInstance(name) == null) {
LOGGER.debug("Removing uninstantiated recipe {}", new Object[] { name });
repository.removeRecipe(name);
} else {
LOGGER.debug("Recipe {} is already instantiated", new Object[] { name });
}
}
for (String name : tmpRepo.getNames()) {
if (repository.getInstance(name) == null) {
LOGGER.debug("Adding new recipe {}", new Object[] { name });
Recipe r = tmpRepo.getRecipe(name);
if (r != null) {
repository.putRecipe(name, r);
}
} else {
LOGGER.debug("Recipe {} is already instantiated and cannot be updated", new Object[] { name });
}
}
}
protected void instantiateEagerComponents() {
List<String> components = new ArrayList<String>();
for (String name : componentDefinitionRegistry.getComponentDefinitionNames()) {
ComponentMetadata component = componentDefinitionRegistry.getComponentDefinition(name);
boolean eager = component.getActivation() == ComponentMetadata.ACTIVATION_EAGER;
if (component instanceof BeanMetadata) {
BeanMetadata local = (BeanMetadata) component;
eager &= MetadataUtil.isSingletonScope(local);
}
if (eager) {
components.add(name);
}
}
LOGGER.debug("Instantiating components: {}", components);
try {
repository.createAll(components);
} catch (ComponentDefinitionException e) {
throw e;
} catch (Throwable t) {
throw new ComponentDefinitionException("Unable to instantiate components", t);
}
}
}
| 9,639 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/container/BeanRecipe.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.blueprint.container;
import static org.apache.aries.blueprint.utils.ReflectionUtils.getRealCause;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.Interceptor;
import org.apache.aries.blueprint.di.AbstractRecipe;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.proxy.Collaborator;
import org.apache.aries.blueprint.proxy.ProxyUtils;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.apache.aries.blueprint.utils.ReflectionUtils.PropertyDescriptor;
import org.apache.aries.proxy.UnableToProxyException;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A <code>Recipe</code> to create POJOs.
*
* @version $Rev$, $Date$
*/
public class BeanRecipe extends AbstractRecipe {
static class UnwrapperedBeanHolder {
final Object unwrapperedBean;
final BeanRecipe recipe;
public UnwrapperedBeanHolder(Object unwrapperedBean, BeanRecipe recipe) {
this.unwrapperedBean = unwrapperedBean;
this.recipe = recipe;
}
}
public class VoidableCallable implements Callable<Object>, Voidable {
private final AtomicReference<Object> ref = new AtomicReference<Object>();
private final Semaphore sem = new Semaphore(1);
private final ThreadLocal<Object> deadlockDetector = new ThreadLocal<Object>();
public void voidReference() {
ref.set(null);
}
public Object call() throws ComponentDefinitionException {
Object o = ref.get();
if (o == null) {
if(deadlockDetector.get() != null) {
deadlockDetector.remove();
throw new ComponentDefinitionException("Construction cycle detected for bean " + name);
}
sem.acquireUninterruptibly();
try {
o = ref.get();
if (o == null) {
deadlockDetector.set(this);
try {
o = internalCreate2();
ref.set(o);
} finally {
deadlockDetector.remove();
}
}
} finally {
sem.release();
}
}
return o;
}
}
private static final Logger LOGGER = LoggerFactory.getLogger(BeanRecipe.class);
private final ExtendedBlueprintContainer blueprintContainer;
private final LinkedHashMap<String,Object> properties = new LinkedHashMap<String,Object>();
private final Object type;
private String initMethod;
private String destroyMethod;
private List<Recipe> explicitDependencies;
private Recipe factory;
private String factoryMethod;
private List<Object> arguments;
private List<String> argTypes;
private boolean reorderArguments;
private final boolean allowsFieldInjection;
private BeanMetadata interceptorLookupKey;
public BeanRecipe(String name, ExtendedBlueprintContainer blueprintContainer, Object type, boolean allowsFieldInjection) {
super(name);
this.blueprintContainer = blueprintContainer;
this.type = type;
this.allowsFieldInjection = allowsFieldInjection;
}
public Object getProperty(String name) {
return properties.get(name);
}
public Map<String, Object> getProperties() {
return new LinkedHashMap<String, Object>(properties);
}
public void setProperty(String name, Object value) {
properties.put(name, value);
}
public void setFactoryMethod(String method) {
this.factoryMethod = method;
}
public void setFactoryComponent(Recipe factory) {
this.factory = factory;
}
public void setArgTypes(List<String> argTypes) {
this.argTypes = argTypes;
}
public void setArguments(List<Object> arguments) {
this.arguments = arguments;
}
public void setReorderArguments(boolean reorder) {
this.reorderArguments = reorder;
}
public void setInitMethod(String initMethod) {
this.initMethod = initMethod;
}
public String getInitMethod() {
return initMethod;
}
public void setDestroyMethod(String destroyMethod) {
this.destroyMethod = destroyMethod;
}
public String getDestroyMethod() {
return destroyMethod;
}
public List<Recipe> getExplicitDependencies() {
return explicitDependencies;
}
public void setExplicitDependencies(List<Recipe> explicitDependencies) {
this.explicitDependencies = explicitDependencies;
}
public void setInterceptorLookupKey(BeanMetadata metadata) {
interceptorLookupKey = metadata;
}
@Override
public List<Recipe> getConstructorDependencies() {
List<Recipe> recipes = new ArrayList<Recipe>();
if (explicitDependencies != null) {
recipes.addAll(explicitDependencies);
}
if (arguments != null) {
for (Object argument : arguments) {
if (argument instanceof Recipe) {
recipes.add((Recipe)argument);
}
}
}
return recipes;
}
public List<Recipe> getDependencies() {
List<Recipe> recipes = new ArrayList<Recipe>();
for (Object o : properties.values()) {
if (o instanceof Recipe) {
Recipe recipe = (Recipe) o;
recipes.add(recipe);
}
}
recipes.addAll(getConstructorDependencies());
return recipes;
}
private void instantiateExplicitDependencies() {
if (explicitDependencies != null) {
for (Recipe recipe : explicitDependencies) {
recipe.create();
}
}
}
@Override
protected Class loadClass(String className) {
ClassLoader loader = type instanceof Class ? ((Class) type).getClassLoader() : null;
ReifiedType t = loadType(className, loader);
return t != null ? t.getRawClass() : null;
}
@Override
protected ReifiedType loadType(String className) {
return loadType(className, type instanceof Class ? ((Class) type).getClassLoader() : null);
}
private Object getInstance() throws ComponentDefinitionException {
Object instance;
// Instanciate arguments
List<Object> args = new ArrayList<Object>();
List<ReifiedType> argTypes = new ArrayList<ReifiedType>();
if (arguments != null) {
for (int i = 0; i < arguments.size(); i++) {
Object arg = arguments.get(i);
if (arg instanceof Recipe) {
args.add(((Recipe) arg).create());
} else {
args.add(arg);
}
if (this.argTypes != null) {
argTypes.add(this.argTypes.get(i) != null ? loadType(this.argTypes.get(i)) : null);
}
}
}
if (factory != null) {
// look for instance method on factory object
Object factoryObj = factory.create();
// If the factory is a service reference, we need to get hold of the actual proxy for the service
/* BLUEPRINT-NOOSGI
if (factoryObj instanceof ReferenceRecipe.ServiceProxyWrapper) {
try {
factoryObj = ((ReferenceRecipe.ServiceProxyWrapper) factoryObj).convert(new ReifiedType(Object.class));
} catch (Exception e) {
throw new ComponentDefinitionException("Error when instantiating bean " + getName() + " of class " + getType(), getRealCause(e));
}
} else*/ if (factoryObj instanceof UnwrapperedBeanHolder) {
factoryObj = wrap((UnwrapperedBeanHolder) factoryObj, Object.class);
}
// Map of matching methods
Map<Method, List<Object>> matches = findMatchingMethods(factoryObj.getClass(), factoryMethod, true, args, argTypes);
if (matches.size() == 1) {
try {
Map.Entry<Method, List<Object>> match = matches.entrySet().iterator().next();
instance = invoke(match.getKey(), factoryObj, match.getValue().toArray());
} catch (Throwable e) {
throw new ComponentDefinitionException("Error when instantiating bean " + getName() + " of class " + getType(), getRealCause(e));
}
} else if (matches.size() == 0) {
throw new ComponentDefinitionException("Unable to find a matching factory method " + factoryMethod + " on class " + factoryObj.getClass().getName() + " for arguments " + args + " when instanciating bean " + getName());
} else {
throw new ComponentDefinitionException("Multiple matching factory methods " + factoryMethod + " found on class " + factoryObj.getClass().getName() + " for arguments " + args + " when instanciating bean " + getName() + ": " + matches.keySet());
}
} else if (factoryMethod != null) {
// Map of matching methods
Map<Method, List<Object>> matches = findMatchingMethods(getType(), factoryMethod, false, args, argTypes);
if (matches.size() == 1) {
try {
Map.Entry<Method, List<Object>> match = matches.entrySet().iterator().next();
instance = invoke(match.getKey(), null, match.getValue().toArray());
} catch (Throwable e) {
throw new ComponentDefinitionException("Error when instanciating bean " + getName() + " of class " + getType(), getRealCause(e));
}
} else if (matches.size() == 0) {
throw new ComponentDefinitionException("Unable to find a matching factory method " + factoryMethod + " on class " + getType().getName() + " for arguments " + args + " when instanciating bean " + getName());
} else {
throw new ComponentDefinitionException("Multiple matching factory methods " + factoryMethod + " found on class " + getType().getName() + " for arguments " + args + " when instanciating bean " + getName() + ": " + matches.keySet());
}
} else {
if (getType() == null) {
throw new ComponentDefinitionException("No factoryMethod nor class is defined for this bean");
}
// Map of matching constructors
Map<Constructor, List<Object>> matches = findMatchingConstructors(getType(), args, argTypes);
if (matches.size() == 1) {
try {
Map.Entry<Constructor, List<Object>> match = matches.entrySet().iterator().next();
instance = newInstance(match.getKey(), match.getValue().toArray());
} catch (Throwable e) {
throw new ComponentDefinitionException("Error when instanciating bean " + getName() + " of class " + getType(), getRealCause(e));
}
} else if (matches.size() == 0) {
throw new ComponentDefinitionException("Unable to find a matching constructor on class " + getType().getName() + " for arguments " + args + " when instanciating bean " + getName());
} else {
throw new ComponentDefinitionException("Multiple matching constructors found on class " + getType().getName() + " for arguments " + args + " when instanciating bean " + getName() + ": " + matches.keySet());
}
}
return instance;
}
private Map<Method, List<Object>> findMatchingMethods(Class type, String name, boolean instance, List<Object> args, List<ReifiedType> types) {
Map<Method, List<Object>> matches = new HashMap<Method, List<Object>>();
// Get constructors
List<Method> methods = new ArrayList<Method>(Arrays.asList(type.getMethods()));
// Discard any signature with wrong cardinality
for (Iterator<Method> it = methods.iterator(); it.hasNext();) {
Method mth = it.next();
if (!mth.getName().equals(name)) {
it.remove();
} else if (mth.getParameterTypes().length != args.size()) {
it.remove();
} else if (instance ^ !Modifier.isStatic(mth.getModifiers())) {
it.remove();
} else if (mth.isBridge()) {
it.remove();
}
}
// on some JVMs (J9) hidden static methods are returned by Class.getMethods so we need to weed them out
// to reduce ambiguity
if (!instance) {
methods = applyStaticHidingRules(methods);
}
// Find a direct match with assignment
if (matches.size() != 1) {
Map<Method, List<Object>> nmatches = new HashMap<Method, List<Object>>();
for (Method mth : methods) {
boolean found = true;
List<Object> match = new ArrayList<Object>();
for (int i = 0; i < args.size(); i++) {
ReifiedType argType = new GenericType(mth.getGenericParameterTypes()[i]);
if (types.get(i) != null && !argType.getRawClass().equals(types.get(i).getRawClass())) {
found = false;
break;
}
//If the arg is an Unwrappered bean then we need to do the assignment check against the
//unwrappered bean itself.
Object arg = args.get(i);
Object argToTest = arg;
if(arg instanceof UnwrapperedBeanHolder)
argToTest = ((UnwrapperedBeanHolder)arg).unwrapperedBean;
if (!AggregateConverter.isAssignable(argToTest, argType)) {
found = false;
break;
}
try {
match.add(convert(arg, mth.getGenericParameterTypes()[i]));
} catch (Throwable t) {
found = false;
break;
}
}
if (found) {
nmatches.put(mth, match);
}
}
if (nmatches.size() > 0) {
matches = nmatches;
}
}
// Find a direct match with conversion
if (matches.size() != 1) {
Map<Method, List<Object>> nmatches = new HashMap<Method, List<Object>>();
for (Method mth : methods) {
boolean found = true;
List<Object> match = new ArrayList<Object>();
for (int i = 0; i < args.size(); i++) {
ReifiedType argType = new GenericType(mth.getGenericParameterTypes()[i]);
if (types.get(i) != null && !argType.getRawClass().equals(types.get(i).getRawClass())) {
found = false;
break;
}
try {
Object val = convert(args.get(i), argType);
match.add(val);
} catch (Throwable t) {
found = false;
break;
}
}
if (found) {
nmatches.put(mth, match);
}
}
if (nmatches.size() > 0) {
matches = nmatches;
}
}
// Start reordering with assignment
if (matches.size() != 1 && reorderArguments && args.size() > 1) {
Map<Method, List<Object>> nmatches = new HashMap<Method, List<Object>>();
for (Method mth : methods) {
ArgumentMatcher matcher = new ArgumentMatcher(mth.getGenericParameterTypes(), false);
List<Object> match = matcher.match(args, types);
if (match != null) {
nmatches.put(mth, match);
}
}
if (nmatches.size() > 0) {
matches = nmatches;
}
}
// Start reordering with conversion
if (matches.size() != 1 && reorderArguments && args.size() > 1) {
Map<Method, List<Object>> nmatches = new HashMap<Method, List<Object>>();
for (Method mth : methods) {
ArgumentMatcher matcher = new ArgumentMatcher(mth.getGenericParameterTypes(), true);
List<Object> match = matcher.match(args, types);
if (match != null) {
nmatches.put(mth, match);
}
}
if (nmatches.size() > 0) {
matches = nmatches;
}
}
return matches;
}
private static List<Method> applyStaticHidingRules(Collection<Method> methods) {
List<Method> result = new ArrayList<Method>(methods.size());
for (Method m : methods) {
boolean toBeAdded = true;
Iterator<Method> it = result.iterator();
inner: while (it.hasNext()) {
Method other = it.next();
if (hasIdenticalParameters(m, other)) {
Class<?> mClass = m.getDeclaringClass();
Class<?> otherClass = other.getDeclaringClass();
if (mClass.isAssignableFrom(otherClass)) {
toBeAdded = false;
break inner;
} else if (otherClass.isAssignableFrom(mClass)) {
it.remove();
}
}
}
if (toBeAdded) result.add(m);
}
return result;
}
private static boolean hasIdenticalParameters(Method one, Method two) {
Class<?>[] oneTypes = one.getParameterTypes();
Class<?>[] twoTypes = two.getParameterTypes();
if (oneTypes.length != twoTypes.length) return false;
for (int i=0; i<oneTypes.length; i++) {
if (!oneTypes[i].equals(twoTypes[i])) return false;
}
return true;
}
private Map<Constructor, List<Object>> findMatchingConstructors(Class type, List<Object> args, List<ReifiedType> types) {
Map<Constructor, List<Object>> matches = new HashMap<Constructor, List<Object>>();
// Get constructors
List<Constructor> constructors = new ArrayList<Constructor>(Arrays.asList(type.getConstructors()));
// Discard any signature with wrong cardinality
for (Iterator<Constructor> it = constructors.iterator(); it.hasNext();) {
if (it.next().getParameterTypes().length != args.size()) {
it.remove();
}
}
// Find a direct match with assignment
if (matches.size() != 1) {
Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
for (Constructor cns : constructors) {
boolean found = true;
List<Object> match = new ArrayList<Object>();
for (int i = 0; i < args.size(); i++) {
ReifiedType argType = new GenericType(cns.getGenericParameterTypes()[i]);
if (types.get(i) != null && !argType.getRawClass().equals(types.get(i).getRawClass())) {
found = false;
break;
}
//If the arg is an Unwrappered bean then we need to do the assignment check against the
//unwrappered bean itself.
Object arg = args.get(i);
Object argToTest = arg;
if(arg instanceof UnwrapperedBeanHolder)
argToTest = ((UnwrapperedBeanHolder)arg).unwrapperedBean;
if (!AggregateConverter.isAssignable(argToTest, argType)) {
found = false;
break;
}
try {
match.add(convert(arg, cns.getGenericParameterTypes()[i]));
} catch (Throwable t) {
found = false;
break;
}
}
if (found) {
nmatches.put(cns, match);
}
}
if (nmatches.size() > 0) {
matches = nmatches;
}
}
// Find a direct match with conversion
if (matches.size() != 1) {
Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
for (Constructor cns : constructors) {
boolean found = true;
List<Object> match = new ArrayList<Object>();
for (int i = 0; i < args.size(); i++) {
ReifiedType argType = new GenericType(cns.getGenericParameterTypes()[i]);
if (types.get(i) != null && !argType.getRawClass().equals(types.get(i).getRawClass())) {
found = false;
break;
}
try {
Object val = convert(args.get(i), argType);
match.add(val);
} catch (Throwable t) {
found = false;
break;
}
}
if (found) {
nmatches.put(cns, match);
}
}
if (nmatches.size() > 0) {
matches = nmatches;
}
}
// Start reordering with assignment
if (matches.size() != 1 && reorderArguments && arguments.size() > 1) {
Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
for (Constructor cns : constructors) {
ArgumentMatcher matcher = new ArgumentMatcher(cns.getGenericParameterTypes(), false);
List<Object> match = matcher.match(args, types);
if (match != null) {
nmatches.put(cns, match);
}
}
if (nmatches.size() > 0) {
matches = nmatches;
}
}
// Start reordering with conversion
if (matches.size() != 1 && reorderArguments && arguments.size() > 1) {
Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
for (Constructor cns : constructors) {
ArgumentMatcher matcher = new ArgumentMatcher(cns.getGenericParameterTypes(), true);
List<Object> match = matcher.match(args, types);
if (match != null) {
nmatches.put(cns, match);
}
}
if (nmatches.size() > 0) {
matches = nmatches;
}
}
return matches;
}
/**
* Returns init method (if any). Throws exception if the init-method was set explicitly on the bean
* and the method is not found on the instance.
*/
protected Method getInitMethod(Object instance) throws ComponentDefinitionException {
Method method = null;
if (initMethod != null && initMethod.length() > 0) {
method = ReflectionUtils.getLifecycleMethod(instance.getClass(), initMethod);
if (method == null) {
throw new ComponentDefinitionException("Component '" + getName() + "' does not have init-method: " + initMethod);
}
}
return method;
}
/**
* Returns destroy method (if any). Throws exception if the destroy-method was set explicitly on the bean
* and the method is not found on the instance.
*/
public Method getDestroyMethod(Object instance) throws ComponentDefinitionException {
Method method = null;
if (instance != null && destroyMethod != null && destroyMethod.length() > 0) {
method = ReflectionUtils.getLifecycleMethod(instance.getClass(), destroyMethod);
if (method == null) {
throw new ComponentDefinitionException("Component '" + getName() + "' does not have destroy-method: " + destroyMethod);
}
}
return method;
}
/**
* Small helper class, to construct a chain of BeanCreators.
* <br>
* Each bean creator in the chain will return a bean that has been
* processed by every BeanProcessor in the chain before it.
*/
private static class BeanCreatorChain implements BeanProcessor.BeanCreator {
public enum ChainType{Before,After};
private final BeanProcessor.BeanCreator parentBeanCreator;
private final BeanProcessor parentBeanProcessor;
private final BeanMetadata beanData;
private final String beanName;
private final ChainType when;
public BeanCreatorChain(BeanProcessor.BeanCreator parentBeanCreator,
BeanProcessor parentBeanProcessor,
BeanMetadata beanData,
String beanName,
ChainType when){
this.parentBeanCreator = parentBeanCreator;
this.parentBeanProcessor = parentBeanProcessor;
this.beanData = beanData;
this.beanName = beanName;
this.when = when;
}
public Object getBean() {
Object previousBean = parentBeanCreator.getBean();
Object processed = null;
switch(when){
case Before :
processed = parentBeanProcessor.beforeInit(previousBean, beanName, parentBeanCreator, beanData);
break;
case After:
processed = parentBeanProcessor.afterInit(previousBean, beanName, parentBeanCreator, beanData);
break;
}
return processed;
}
}
private Object runBeanProcPreInit(Object obj){
String beanName = getName();
BeanMetadata beanData = (BeanMetadata) blueprintContainer
.getComponentDefinitionRegistry().getComponentDefinition(beanName);
List<BeanProcessor> processors = blueprintContainer.getProcessors(BeanProcessor.class);
//The start link of the chain, that provides the
//original, unprocessed bean to the head of the chain.
BeanProcessor.BeanCreator initialBeanCreator = new BeanProcessor.BeanCreator() {
public Object getBean() {
Object obj = getInstance();
//getinit, getdestroy, addpartial object don't need calling again.
//however, property injection does.
setProperties(obj);
return obj;
}
};
BeanProcessor.BeanCreator currentCreator = initialBeanCreator;
for(BeanProcessor processor : processors){
obj = processor.beforeInit(obj, getName(), currentCreator, beanData);
currentCreator = new BeanCreatorChain(currentCreator, processor, beanData, beanName, BeanCreatorChain.ChainType.Before);
}
return obj;
}
private void runBeanProcInit(Method initMethod, Object obj){
// call init method
if (initMethod != null) {
try {
invoke(initMethod, obj, (Object[]) null);
} catch (Throwable t) {
throw new ComponentDefinitionException("Unable to intialize bean " + getName(), getRealCause(t));
}
}
}
private Object runBeanProcPostInit(Object obj){
String beanName = getName();
BeanMetadata beanData = (BeanMetadata) blueprintContainer
.getComponentDefinitionRegistry().getComponentDefinition(beanName);
List<BeanProcessor> processors = blueprintContainer.getProcessors(BeanProcessor.class);
//The start link of the chain, that provides the
//original, unprocessed bean to the head of the chain.
BeanProcessor.BeanCreator initialBeanCreator = new BeanProcessor.BeanCreator() {
public Object getBean() {
Object obj = getInstance();
//getinit, getdestroy, addpartial object don't need calling again.
//however, property injection does.
setProperties(obj);
//as this is the post init chain, new beans need to go thru
//the pre-init chain, and then have init called, before
//being passed along the post-init chain.
obj = runBeanProcPreInit(obj);
runBeanProcInit(getInitMethod(obj), obj);
return obj;
}
};
BeanProcessor.BeanCreator currentCreator = initialBeanCreator;
for(BeanProcessor processor : processors){
obj = processor.afterInit(obj, getName(), currentCreator, beanData);
currentCreator = new BeanCreatorChain(currentCreator, processor, beanData, beanName, BeanCreatorChain.ChainType.After);
}
return obj;
}
private Object addInterceptors(final Object original, Collection<Class<?>> requiredInterfaces)
throws ComponentDefinitionException {
Object intercepted = null;
if(requiredInterfaces.isEmpty())
requiredInterfaces.add(original.getClass());
ComponentDefinitionRegistry reg = blueprintContainer
.getComponentDefinitionRegistry();
List<Interceptor> interceptors = reg.getInterceptors(interceptorLookupKey);
if (interceptors != null && interceptors.size() > 0) {
/* BLUEPRINT-NOOSGI
try {
Bundle b = FrameworkUtil.getBundle(original.getClass());
if (b == null) {
// we have a class from the framework parent, so use our bundle for proxying.
b = blueprintContainer.getBundleContext().getBundle();
}
intercepted = blueprintContainer.getProxyManager().createInterceptingProxy(b,
requiredInterfaces, original, new Collaborator(interceptorLookupKey, interceptors));
} catch (org.apache.aries.proxy.UnableToProxyException e) {
Bundle b = blueprintContainer.getBundleContext().getBundle();
throw new ComponentDefinitionException("Unable to create proxy for bean " + name + " in bundle " + b.getSymbolicName() + " version " + b.getVersion(), e);
}
*/
throw new ComponentDefinitionException("Unable to create proxy for bean " + name + ". Not supported in blueprint-noosgi");
} else {
intercepted = original;
}
return intercepted;
}
@Override
protected Object internalCreate() throws ComponentDefinitionException {
/* BLUEPRINT-NOOSGI
if (factory instanceof ReferenceRecipe) {
ReferenceRecipe rr = (ReferenceRecipe) factory;
if (rr.getProxyChildBeanClasses() != null) {
return createProxyBean(rr);
}
}
*/
return new UnwrapperedBeanHolder(internalCreate2(), this);
}
/* BLUEPRINT-NOOSGI
private Object createProxyBean(ReferenceRecipe rr) {
try {
VoidableCallable vc = new VoidableCallable();
rr.addVoidableChild(vc);
return blueprintContainer.getProxyManager().createDelegatingProxy(
blueprintContainer.getBundleContext().getBundle(), rr.getProxyChildBeanClasses(),
vc, vc.call());
} catch (UnableToProxyException e) {
throw new ComponentDefinitionException(e);
}
}
*/
private Object internalCreate2() throws ComponentDefinitionException {
instantiateExplicitDependencies();
Object obj = getInstance();
// check for init lifecycle method (if any)
Method initMethod = getInitMethod(obj);
// check for destroy lifecycle method (if any)
getDestroyMethod(obj);
// Add partially created object to the container
// if (initMethod == null) {
addPartialObject(obj);
// }
// inject properties
setProperties(obj);
obj = runBeanProcPreInit(obj);
runBeanProcInit(initMethod, obj);
obj = runBeanProcPostInit(obj);
//Replaced by calling wrap on the UnwrapperedBeanHolder
// obj = addInterceptors(obj);
return obj;
}
static Object wrap(UnwrapperedBeanHolder holder, Collection<Class<?>> requiredViews) {
return holder.recipe.addInterceptors(holder.unwrapperedBean, requiredViews);
}
static Object wrap(UnwrapperedBeanHolder holder, Class<?> requiredView) {
if(requiredView == Object.class) {
//We don't know what we need so we have to do everything
return holder.recipe.addInterceptors(holder.unwrapperedBean, new ArrayList<Class<?>>(1));
} else {
return holder.recipe.addInterceptors(holder.unwrapperedBean, ProxyUtils.asList(requiredView));
}
}
@Override
public void destroy(Object obj) {
if (!(obj instanceof UnwrapperedBeanHolder)) {
LOGGER.warn("Object to be destroyed is not an instance of UnwrapperedBeanHolder, type: " + obj);
return;
}
obj = ((UnwrapperedBeanHolder)obj).unwrapperedBean;
for (BeanProcessor processor : blueprintContainer.getProcessors(BeanProcessor.class)) {
processor.beforeDestroy(obj, getName());
}
try {
Method method = getDestroyMethod(obj);
if (method != null) {
invoke(method, obj, (Object[]) null);
}
} catch (ComponentDefinitionException e) {
// This exception occurs if the destroy method does not exist, so we just output the exception message.
LOGGER.error(e.getMessage());
} catch (InvocationTargetException ite) {
/* BLUEPRINT-OSGI
Throwable t = ite.getTargetException();
BundleContext ctx = blueprintContainer.getBundleContext();
Bundle b = ctx.getBundle();
String bundleIdentifier = b.getSymbolicName() + '/' + b.getVersion();
LOGGER.error("The blueprint bean " + getName() + " in bundle " + bundleIdentifier + " incorrectly threw an exception from its destroy method.", t);
*/
Throwable t = ite.getTargetException();
LOGGER.error("The blueprint bean " + getName() + " in incorrectly threw an exception from its destroy method.", t);
} catch (Exception e) {
/* BLUEPRINT-OSGI
BundleContext ctx = blueprintContainer.getBundleContext();
Bundle b = ctx.getBundle();
String bundleIdentifier = b.getSymbolicName() + '/' + b.getVersion();
LOGGER.error("An exception occurred while calling the destroy method of the blueprint bean " + getName() + " in bundle " + bundleIdentifier + ".", getRealCause(e));
*/
LOGGER.error("An exception occurred while calling the destroy method of the blueprint bean " + getName() + ".", getRealCause(e));
}
for (BeanProcessor processor : blueprintContainer.getProcessors(BeanProcessor.class)) {
processor.afterDestroy(obj, getName());
}
}
public void setProperties(Object instance) throws ComponentDefinitionException {
// clone the properties so they can be used again
Map<String,Object> propertyValues = new LinkedHashMap<String,Object>(properties);
setProperties(propertyValues, instance, instance.getClass());
}
public Class getType() {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof String) {
return loadClass((String) type);
} else {
return null;
}
}
private void setProperties(Map<String, Object> propertyValues, Object instance, Class clazz) {
// set remaining properties
for (Map.Entry<String, Object> entry : propertyValues.entrySet()) {
String propertyName = entry.getKey();
Object propertyValue = entry.getValue();
setProperty(instance, clazz, propertyName, propertyValue);
}
}
private void setProperty(Object instance, Class clazz, String propertyName, Object propertyValue) {
String[] names = propertyName.split("\\.");
for (int i = 0; i < names.length - 1; i++) {
PropertyDescriptor pd = getPropertyDescriptor(clazz, names[i]);
if (pd.allowsGet()) {
try {
instance = pd.get(instance, blueprintContainer);
} catch (Exception e) {
throw new ComponentDefinitionException("Error getting property: " + names[i] + " on bean " + getName() + " when setting property " + propertyName + " on class " + clazz.getName(), getRealCause(e));
}
if (instance == null) {
throw new ComponentDefinitionException("Error setting compound property " + propertyName + " on bean " + getName() + ". Property " + names[i] + " is null");
}
clazz = instance.getClass();
} else {
throw new ComponentDefinitionException("No getter for " + names[i] + " property on bean " + getName() + " when setting property " + propertyName + " on class " + clazz.getName());
}
}
// Instantiate value
if (propertyValue instanceof Recipe) {
propertyValue = ((Recipe) propertyValue).create();
}
final PropertyDescriptor pd = getPropertyDescriptor(clazz, names[names.length - 1]);
if (pd.allowsSet()) {
try {
pd.set(instance, propertyValue, blueprintContainer);
} catch (Exception e) {
throw new ComponentDefinitionException("Error setting property: " + pd, getRealCause(e));
}
} else {
throw new ComponentDefinitionException("No setter for " + names[names.length - 1] + " property");
}
}
private ReflectionUtils.PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String name) {
for (ReflectionUtils.PropertyDescriptor pd : ReflectionUtils.getPropertyDescriptors(clazz, allowsFieldInjection)) {
if (pd.getName().equals(name)) {
return pd;
}
}
throw new ComponentDefinitionException("Unable to find property descriptor " + name + " on class " + clazz.getName());
}
private Object invoke(Method method, Object instance, Object... args) throws Exception {
return ReflectionUtils.invoke(blueprintContainer.getAccessControlContext(), method, instance, args);
}
private Object newInstance(Constructor constructor, Object... args) throws Exception {
return ReflectionUtils.newInstance(blueprintContainer.getAccessControlContext(), constructor, args);
}
private static Object UNMATCHED = new Object();
private class ArgumentMatcher {
private final List<TypeEntry> entries;
private final boolean convert;
public ArgumentMatcher(Type[] types, boolean convert) {
entries = new ArrayList<TypeEntry>();
for (Type type : types) {
entries.add(new TypeEntry(new GenericType(type)));
}
this.convert = convert;
}
public List<Object> match(List<Object> arguments, List<ReifiedType> forcedTypes) {
if (find(arguments, forcedTypes)) {
return getArguments();
}
return null;
}
private List<Object> getArguments() {
List<Object> list = new ArrayList<Object>();
for (TypeEntry entry : entries) {
if (entry.argument == UNMATCHED) {
throw new RuntimeException("There are unmatched types");
} else {
list.add(entry.argument);
}
}
return list;
}
private boolean find(List<Object> arguments, List<ReifiedType> forcedTypes) {
if (entries.size() == arguments.size()) {
boolean matched = true;
for (int i = 0; i < arguments.size() && matched; i++) {
matched = find(arguments.get(i), forcedTypes.get(i));
}
return matched;
}
return false;
}
private boolean find(Object arg, ReifiedType forcedType) {
for (TypeEntry entry : entries) {
Object val = arg;
if (entry.argument != UNMATCHED) {
continue;
}
if (forcedType != null) {
if (!forcedType.equals(entry.type)) {
continue;
}
} else if (arg != null) {
if (convert) {
if(canConvert(arg, entry.type)) {
try {
val = convert(arg, entry.type);
} catch (Exception e) {
throw new ComponentDefinitionException(e);
}
} else {
continue;
}
} else {
UnwrapperedBeanHolder holder = null;
if(arg instanceof UnwrapperedBeanHolder) {
holder = (UnwrapperedBeanHolder)arg;
arg = holder.unwrapperedBean;
}
if (!AggregateConverter.isAssignable(arg, entry.type)) {
continue;
} else if (holder != null) {
val = wrap(holder, entry.type.getRawClass());
}
}
}
entry.argument = val;
return true;
}
return false;
}
}
private static class TypeEntry {
private final ReifiedType type;
private Object argument;
public TypeEntry(ReifiedType type) {
this.type = type;
this.argument = UNMATCHED;
}
}
}
| 9,640 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/container/GenericType.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.blueprint.container;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.ReifiedType;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
/**
* XXXX: Currently, in case of arrays getActualTypeArgument(0) returns something similar to what
* Class.getComponentType() does for arrays. I don't think this is quite right since getActualTypeArgument()
* should return the given parameterized type not the component type. Need to check this behavior with the spec.
*/
public class GenericType extends ReifiedType {
private static final GenericType[] EMPTY = new GenericType[0];
private static final Map<String, Class> primitiveClasses = new HashMap<String, Class>();
static {
primitiveClasses.put("int", int.class);
primitiveClasses.put("short", short.class);
primitiveClasses.put("long", long.class);
primitiveClasses.put("byte", byte.class);
primitiveClasses.put("char", char.class);
primitiveClasses.put("float", float.class);
primitiveClasses.put("double", double.class);
primitiveClasses.put("boolean", boolean.class);
}
private GenericType[] parameters;
public GenericType(Type type) {
this(getConcreteClass(type), parametersOf(type));
}
public GenericType(Class clazz, GenericType... parameters) {
super(clazz);
this.parameters = parameters;
}
public static GenericType parse(String rawType, final Object loader) throws ClassNotFoundException, IllegalArgumentException {
final String type = rawType.trim();
// Check if this is an array
if (type.endsWith("[]")) {
GenericType t = parse(type.substring(0, type.length() - 2), loader);
return new GenericType(Array.newInstance(t.getRawClass(), 0).getClass(), t);
}
// Check if this is a generic
int genericIndex = type.indexOf('<');
if (genericIndex > 0) {
if (!type.endsWith(">")) {
throw new IllegalArgumentException("Can not load type: " + type);
}
GenericType base = parse(type.substring(0, genericIndex), loader);
String[] params = type.substring(genericIndex + 1, type.length() - 1).split(",");
GenericType[] types = new GenericType[params.length];
for (int i = 0; i < params.length; i++) {
types[i] = parse(params[i], loader);
}
return new GenericType(base.getRawClass(), types);
}
// Primitive
if (primitiveClasses.containsKey(type)) {
return new GenericType(primitiveClasses.get(type));
}
// Class
if (loader instanceof ClassLoader) {
return new GenericType(((ClassLoader) loader).loadClass(type));
} else if (loader instanceof ExecutionContext) {
return new GenericType(((ExecutionContext) loader).loadClass(type));
} else if (loader instanceof ExtendedBlueprintContainer) {
return new GenericType(((ExtendedBlueprintContainer) loader).loadClass(type));
} else {
throw new IllegalArgumentException("Unsupported loader: " + loader);
}
}
@Override
public ReifiedType getActualTypeArgument(int i) {
if (parameters.length == 0) {
return super.getActualTypeArgument(i);
}
return parameters[i];
}
@Override
public int size() {
return parameters.length;
}
@Override
public String toString() {
Class cl = getRawClass();
if (cl.isArray()) {
if (parameters.length > 0) {
return parameters[0].toString() + "[]";
} else {
return cl.getComponentType().getName() + "[]";
}
}
if (parameters.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append(cl.getName());
sb.append("<");
for (int i = 0; i < parameters.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append(parameters[i].toString());
}
sb.append(">");
return sb.toString();
}
return cl.getName();
}
public boolean equals(Object object) {
if (!(object instanceof GenericType)) {
return false;
}
GenericType other = (GenericType) object;
if (getRawClass() != other.getRawClass()) {
return false;
}
if (parameters == null) {
return (other.parameters == null);
} else {
if (other.parameters == null) {
return false;
}
if (parameters.length != other.parameters.length) {
return false;
}
for (int i = 0; i < parameters.length; i++) {
if (!parameters[i].equals(other.parameters[i])) {
return false;
}
}
return true;
}
}
static GenericType[] parametersOf(Type type) {
if (type instanceof Class) {
Class clazz = (Class) type;
if (clazz.isArray()) {
GenericType t = new GenericType(clazz.getComponentType());
if (t.size() > 0) {
return new GenericType[] { t };
} else {
return EMPTY;
}
} else {
return EMPTY;
}
}
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type [] parameters = pt.getActualTypeArguments();
GenericType[] gts = new GenericType[parameters.length];
for ( int i =0; i<gts.length; i++) {
gts[i] = new GenericType(parameters[i]);
}
return gts;
}
if (type instanceof GenericArrayType) {
return new GenericType[] { new GenericType(((GenericArrayType) type).getGenericComponentType()) };
}
if (type instanceof WildcardType) {
return EMPTY;
}
if (type instanceof TypeVariable) {
return EMPTY;
}
throw new IllegalStateException();
}
static Class<?> getConcreteClass(Type type) {
Type ntype = collapse(type);
if ( ntype instanceof Class )
return (Class<?>) ntype;
if ( ntype instanceof ParameterizedType )
return getConcreteClass(collapse(((ParameterizedType)ntype).getRawType()));
throw new RuntimeException("Unknown type " + type );
}
static Type collapse(Type target) {
if (target instanceof Class || target instanceof ParameterizedType ) {
return target;
} else if (target instanceof TypeVariable) {
return collapse(((TypeVariable<?>) target).getBounds()[0]);
} else if (target instanceof GenericArrayType) {
Type t = collapse(((GenericArrayType) target)
.getGenericComponentType());
while ( t instanceof ParameterizedType )
t = collapse(((ParameterizedType)t).getRawType());
return Array.newInstance((Class<?>)t, 0).getClass();
} else if (target instanceof WildcardType) {
WildcardType wct = (WildcardType) target;
if (wct.getLowerBounds().length == 0)
return collapse(wct.getUpperBounds()[0]);
else
return collapse(wct.getLowerBounds()[0]);
}
throw new RuntimeException("Huh? " + target);
}
}
| 9,641 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/container/NoOsgiBlueprintRepository.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.blueprint.container;
import org.apache.aries.blueprint.di.CollectionRecipe;
import org.apache.aries.blueprint.di.IdRefRecipe;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.RefRecipe;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
public class NoOsgiBlueprintRepository extends BlueprintRepository {
public NoOsgiBlueprintRepository(ExtendedBlueprintContainer container) {
super(container);
}
@Override
public void validate() {
for (Recipe recipe : getAllRecipes()) {
// Check that references are satisfied
String ref = null;
if (recipe instanceof RefRecipe) {
ref = ((RefRecipe) recipe).getIdRef();
} else if (recipe instanceof IdRefRecipe) {
ref = ((IdRefRecipe) recipe).getIdRef();
}
if (ref != null && getRecipe(ref) == null) {
throw new ComponentDefinitionException("Unresolved ref/idref to component: " + ref);
}
}
}
}
| 9,642 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/container/SimpleNamespaceHandlerSet.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.blueprint.container;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ext.impl.ExtNamespaceHandler;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.SAXException;
public class SimpleNamespaceHandlerSet implements NamespaceHandlerSet {
private Map<URI, URL> namespaces;
private Map<URI, NamespaceHandler> handlers;
private Schema schema;
public SimpleNamespaceHandlerSet() {
this.namespaces = new LinkedHashMap<URI, URL>();
this.handlers = new LinkedHashMap<URI, NamespaceHandler>();
ExtNamespaceHandler ext = new ExtNamespaceHandler();
for (String uri : ExtNamespaceHandler.EXT_URIS) {
addNamespace(URI.create(uri), ext.getSchemaLocation(uri), ext);
}
}
public Set<URI> getNamespaces() {
return Collections.unmodifiableSet(namespaces.keySet());
}
public void addNamespace(URI namespace, URL schema, NamespaceHandler handler) {
namespaces.put(namespace, schema);
handlers.put(namespace, handler);
}
public boolean isComplete() {
return true;
}
public NamespaceHandler getNamespaceHandler(URI uri) {
return handlers.get(uri);
}
@Override
public Schema getSchema(Map<String, String> locations) throws SAXException, IOException {
return getSchema();
}
public Schema getSchema() throws SAXException, IOException {
if (schema == null) {
final List<StreamSource> schemaSources = new ArrayList<StreamSource>();
final List<InputStream> streams = new ArrayList<InputStream>();
try {
InputStream is = getClass().getResourceAsStream("/org/osgi/service/blueprint/blueprint.xsd");
streams.add(is);
schemaSources.add(new StreamSource(is));
for (URI uri : namespaces.keySet()) {
is = namespaces.get(uri).openStream();
streams.add(is);
schemaSources.add(new StreamSource(is));
}
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setResourceResolver(new LSResourceResolver() {
public LSInput resolveResource(String type, String namespace, String publicId,
String systemId, String baseURI) {
try {
URL namespaceURL = namespaces.get(URI.create(namespace));
if (systemId != null && namespaceURL != null) {
URI systemIdUri = namespaceURL.toURI();
if (!URI.create(systemId).isAbsolute()) {
systemIdUri = systemIdUri.resolve(systemId);
}
if (!systemIdUri.isAbsolute() && "jar".equals(namespaceURL.getProtocol())) {
String urlString = namespaceURL.toString();
int jarFragmentIndex = urlString.lastIndexOf('!');
if (jarFragmentIndex > 0 && jarFragmentIndex < urlString.length() - 1) {
String jarUrlOnly = urlString.substring(0, jarFragmentIndex);
String oldFragment = urlString.substring(jarFragmentIndex + 1);
String newFragment = URI.create(oldFragment).resolve(systemId).toString();
String newJarUri = jarUrlOnly + '!' + newFragment;
systemIdUri = URI.create(newJarUri);
}
}
InputStream resourceStream = systemIdUri.toURL().openStream();
return new LSInputImpl(publicId, systemId, resourceStream);
}
} catch (Exception ex) {
// ignore
}
return null;
}
});
schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
} finally {
for (InputStream is : streams) {
is.close();
}
}
}
return schema;
}
public void addListener(Listener listener) {
throw new IllegalStateException();
}
public void removeListener(Listener listener) {
throw new IllegalStateException();
}
public void destroy() {
schema = null;
}
private static class LSInputImpl implements LSInput {
protected String fPublicId;
protected String fSystemId;
protected String fBaseSystemId;
protected InputStream fByteStream;
protected Reader fCharStream;
protected String fData;
protected String fEncoding;
protected boolean fCertifiedText;
LSInputImpl(String publicId, String systemId, InputStream byteStream) {
fPublicId = publicId;
fSystemId = systemId;
fByteStream = byteStream;
}
public InputStream getByteStream() {
return fByteStream;
}
public void setByteStream(InputStream byteStream) {
fByteStream = byteStream;
}
public Reader getCharacterStream() {
return fCharStream;
}
public void setCharacterStream(Reader characterStream) {
fCharStream = characterStream;
}
public String getStringData() {
return fData;
}
public void setStringData(String stringData) {
fData = stringData;
}
public String getEncoding() {
return fEncoding;
}
public void setEncoding(String encoding) {
fEncoding = encoding;
}
public String getPublicId() {
return fPublicId;
}
public void setPublicId(String publicId) {
fPublicId = publicId;
}
public String getSystemId() {
return fSystemId;
}
public void setSystemId(String systemId) {
fSystemId = systemId;
}
public String getBaseURI() {
return fBaseSystemId;
}
public void setBaseURI(String baseURI) {
fBaseSystemId = baseURI;
}
public boolean getCertifiedText() {
return fCertifiedText;
}
public void setCertifiedText(boolean certifiedText) {
fCertifiedText = certifiedText;
}
}
}
| 9,643 |
0 | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-noosgi/src/main/java/org/apache/aries/blueprint/services/ExtendedBlueprintContainer.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.blueprint.services;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.Processor;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.Converter;
import java.net.URL;
import java.security.AccessControlContext;
import java.util.List;
public interface ExtendedBlueprintContainer extends BlueprintContainer {
Converter getConverter();
Class loadClass(String name) throws ClassNotFoundException;
URL getResource(String name);
AccessControlContext getAccessControlContext();
ComponentDefinitionRegistry getComponentDefinitionRegistry();
<T extends Processor> List<T> getProcessors(Class<T> type);
String getProperty(String key);
}
| 9,644 |
0 | Create_ds/aries/blueprint/blueprint-web/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-web/src/main/java/org/apache/aries/blueprint/web/BlueprintContextListener.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.blueprint.web;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.Namespaces;
import org.apache.aries.blueprint.container.BlueprintContainerImpl;
import org.apache.aries.blueprint.container.SimpleNamespaceHandlerSet;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
/**
* Initialises all the blueprint XML files called <code>META-INF/blueprint.xml</code> on the classpath
*/
public class BlueprintContextListener implements ServletContextListener {
public static final String CONTAINER_ATTRIBUTE = "org.apache.aries.blueprint.container";
public static final String CONTEXT_LOCATION = "blueprintLocation";
public static final String DEFAULT_CONTEXT_LOCATION = "META-INF/blueprint.xml";
public static final String NAMESPACE_HANDLERS_PARAMETER = "blueprintNamespaceHandlers";
public static final String NAMESPACE_HANDLERS_LOCATION = "META-INF/blueprint.handlers";
public static final String PROPERTIES = "blueprintProperties";
public void contextInitialized(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
String location = servletContext.getInitParameter(CONTEXT_LOCATION);
if (location == null) {
location = DEFAULT_CONTEXT_LOCATION;
}
List<URL> resourcePaths = new ArrayList<URL>();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
Enumeration<URL> resources = classLoader.getResources(location);
while (resources.hasMoreElements()) {
resourcePaths.add(resources.nextElement());
}
servletContext.log("Loading Blueprint contexts " + resourcePaths);
Map<String, String> properties = new HashMap<String, String>();
String propLocations = servletContext.getInitParameter(PROPERTIES);
if (propLocations != null) {
for (String propLoc : propLocations.split(",")) {
Enumeration<URL> propUrl = classLoader.getResources(propLoc);
while (propUrl.hasMoreElements()) {
URL url = propUrl.nextElement();
InputStream is = url.openStream();
try {
Properties props = new Properties();
props.load(is);
Enumeration names = props.propertyNames();
while (names.hasMoreElements()) {
String key = names.nextElement().toString();
properties.put(key, props.getProperty(key));
}
} finally {
is.close();
}
}
}
}
NamespaceHandlerSet nsHandlerSet = getNamespaceHandlerSet(servletContext, classLoader);
BlueprintContainerImpl container = new BlueprintContainerImpl(classLoader, resourcePaths, properties, nsHandlerSet, true);
servletContext.setAttribute(CONTAINER_ATTRIBUTE, container);
} catch (Exception e) {
servletContext.log("Failed to startup blueprint container. " + e, e);
}
}
protected NamespaceHandlerSet getNamespaceHandlerSet(ServletContext servletContext, ClassLoader tccl) {
NamespaceHandlerSet nsSet = getNamespaceHandlerSetFromParameter(servletContext, tccl);
if (nsSet != null) {
return nsSet;
}
return getNamespaceHandlerSetFromLocation(servletContext, tccl);
}
protected NamespaceHandlerSet getNamespaceHandlerSetFromParameter(ServletContext servletContext, ClassLoader tccl) {
String handlersProp = servletContext.getInitParameter(NAMESPACE_HANDLERS_PARAMETER);
if (handlersProp == null) {
return null;
}
return getNamespaceHandlerSetFromClassNames(servletContext, tccl, Arrays.asList(handlersProp.split(",")));
}
protected NamespaceHandlerSet getNamespaceHandlerSetFromLocation(ServletContext servletContext, ClassLoader tccl) {
List<String> handlerClassNames = new LinkedList<String>();
try {
Enumeration<URL> resources = tccl.getResources(NAMESPACE_HANDLERS_LOCATION);
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
BufferedReader br = new BufferedReader(new InputStreamReader(resource.openStream()));
try {
for (String line = br.readLine(); line != null; line = br.readLine()) {
String trimmedLine = line.trim();
if (trimmedLine.isEmpty() || trimmedLine.startsWith("#")) {
continue;
}
handlerClassNames.add(trimmedLine);
}
} finally {
br.close();
}
}
} catch (IOException ex) {
throw new RuntimeException("Failed to load namespace handler resources", ex);
}
if (!handlerClassNames.isEmpty()) {
return getNamespaceHandlerSetFromClassNames(servletContext, tccl, handlerClassNames);
} else {
return null;
}
}
protected NamespaceHandlerSet getNamespaceHandlerSetFromClassNames(ServletContext servletContext, ClassLoader tccl,
List<String> handlerClassNames) {
SimpleNamespaceHandlerSet nsSet = new SimpleNamespaceHandlerSet();
for (String name : handlerClassNames) {
String trimmedName = name.trim();
Object instance = null;
try {
instance = tccl.loadClass(trimmedName).newInstance();
} catch (Exception ex) {
throw new RuntimeException("Failed to load NamespaceHandler: " + trimmedName, ex);
}
if (!(instance instanceof NamespaceHandler)) {
throw new RuntimeException("Invalid NamespaceHandler: " + trimmedName);
}
NamespaceHandler nsHandler = (NamespaceHandler)instance;
Namespaces namespaces = nsHandler.getClass().getAnnotation(Namespaces.class);
if (namespaces != null) {
for (String ns : namespaces.value()) {
nsSet.addNamespace(URI.create(ns), nsHandler.getSchemaLocation(ns), nsHandler);
}
}
}
return nsSet;
}
public void contextDestroyed(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
Object container = servletContext.getAttribute(CONTAINER_ATTRIBUTE);
if (container instanceof BlueprintContainerImpl) {
BlueprintContainerImpl blueprint = (BlueprintContainerImpl) container;
blueprint.destroy();
}
}
}
| 9,645 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/mytest/MySPI.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.mytest;
public interface MySPI {
String someMethod(String s);
}
| 9,646 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/mytest/AltSPI.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.mytest;
public interface AltSPI {
long square(long l);
}
| 9,647 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/JaxpClient.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.spifly.dynamic;
import javax.xml.parsers.DocumentBuilderFactory;
public class JaxpClient {
public Class<?> test() {
return DocumentBuilderFactory.newInstance().getClass();
}
}
| 9,648 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/TestClient.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.spifly.dynamic;
import org.apache.aries.mytest.MySPI;
import java.util.HashSet;
import java.util.ServiceLoader;
import java.util.Set;
public class TestClient {
/**
* Load using a constant as parameter.
*/
public Set<String> test(String input) {
Set<String> results = new HashSet<String>();
ServiceLoader<MySPI> loader = ServiceLoader.load(MySPI.class);
for (MySPI mySPI : loader) {
results.add(mySPI.someMethod(input));
}
return results;
}
/**
* Load using a variable as parameter.
*/
public Set<String> testService(String input, Class<MySPI> service) {
Set<String> results = new HashSet<String>();
// Try to irritate TCCLSetterVisitor by forcing an (irrelevant) LDC.
@SuppressWarnings("unused")
Class<?> causeLDC = String.class;
ServiceLoader<MySPI> loader = ServiceLoader.load(service);
for (MySPI mySPI : loader) {
results.add(mySPI.someMethod(input));
}
return results;
}
/**
* Slightly different example where the class is loaded using Class.forName()
*/
public Set<String> testService2(String input) throws Exception {
Set<String> results = new HashSet<String>();
Class<?> cls = Class.forName("org.apache.aries.mytest.MySPI");
ServiceLoader<?> loader = ServiceLoader.load(cls);
for (Object obj : loader) {
results.add(((MySPI) obj).someMethod(input));
}
return results;
}
}
| 9,649 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookOSGi43Test.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.spifly.dynamic;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.aries.spifly.BaseActivator;
import org.apache.aries.spifly.SpiFlyConstants;
import org.apache.aries.spifly.Streams;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Version;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWiring;
public class ClientWeavingHookOSGi43Test {
DynamicWeavingActivator activator;
@Before
public void setUp() {
activator = new DynamicWeavingActivator();
BaseActivator.activator = activator;
}
@After
public void tearDown() {
BaseActivator.activator = null;
activator = null;
}
@Test
public void testBasicServiceLoaderUsageWithClassLoaderFromBundleRevision() throws Exception {
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
consumerHeaders.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(Collections.singleton("olleh"), result);
}
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle ... bundles) throws Exception {
Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
allBundles.add(spiFlyBundle);
EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes();
EasyMock.replay(spiFlyBundleContext);
EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
EasyMock.replay(spiFlyBundle);
// Set the bundle context for testing purposes
Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
bcField.setAccessible(true);
bcField.set(activator, spiFlyBundle.getBundleContext());
return spiFlyBundle;
}
private Bundle mockProviderBundle(String subdir, long id) throws Exception {
return mockProviderBundle(subdir, id, Version.emptyVersion);
}
private Bundle mockProviderBundle(String subdir, long id, Version version) throws Exception {
URL url = getClass().getResource("/" + getClass().getName().replace('.', '/') + ".class");
File classFile = new File(url.getFile());
File baseDir = new File(classFile.getParentFile(), subdir);
File directory = new File(baseDir, "/META-INF/services");
final List<String> classNames = new ArrayList<String>();
// Do a directory listing of the applicable META-INF/services directory
List<String> resources = new ArrayList<String>();
for (File f : directory.listFiles()) {
String fileName = f.getName();
if (fileName.startsWith(".") || fileName.endsWith("."))
continue;
classNames.addAll(getClassNames(f));
// Needs to be something like: META-INF/services/org.apache.aries.mytest.MySPI
String path = f.getAbsolutePath().substring(baseDir.getAbsolutePath().length());
path = path.replace('\\', '/');
if (path.startsWith("/")) {
path = path.substring(1);
}
resources.add(path);
}
// Set up the classloader that will be used by the ASM-generated code as the TCCL.
// It can load a META-INF/services file
final ClassLoader cl = new TestProviderBundleClassLoader(subdir, resources.toArray(new String [] {}));
final List<String> classResources = new ArrayList<String>();
for(String className : classNames) {
classResources.add("/" + className.replace('.', '/') + ".class");
}
Bundle systemBundle = EasyMock.createMock(Bundle.class);
EasyMock.<Class<?>>expect(systemBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() {
@Override
public Class<?> answer() throws Throwable {
String name = (String) EasyMock.getCurrentArguments()[0];
return ClientWeavingHookOSGi43Test.class.getClassLoader().loadClass(name);
}
}).anyTimes();
EasyMock.replay(systemBundle);
BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(bc.getBundle(0)).andReturn(systemBundle).anyTimes();
EasyMock.replay(bc);
BundleWiring bundleWiring = EasyMock.createMock(BundleWiring.class);
EasyMock.expect(bundleWiring.getClassLoader()).andReturn(cl).anyTimes();
EasyMock.replay(bundleWiring);
BundleRevision bundleRevision = EasyMock.createMock(BundleRevision.class);
EasyMock.expect(bundleRevision.getWiring()).andReturn(bundleWiring).anyTimes();
EasyMock.replay(bundleRevision);
Bundle providerBundle = EasyMock.createMock(Bundle.class);
String bsn = subdir;
int idx = bsn.indexOf('_');
if (idx > 0) {
bsn = bsn.substring(0, idx);
}
EasyMock.expect(providerBundle.getSymbolicName()).andReturn(bsn).anyTimes();
EasyMock.expect(providerBundle.getBundleId()).andReturn(id).anyTimes();
EasyMock.expect(providerBundle.getBundleContext()).andReturn(bc).anyTimes();
EasyMock.expect(providerBundle.getVersion()).andReturn(version).anyTimes();
EasyMock.expect(providerBundle.adapt(BundleRevision.class)).andReturn(bundleRevision).anyTimes();
EasyMock.<Class<?>>expect(providerBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() {
@Override
public Class<?> answer() throws Throwable {
String name = (String) EasyMock.getCurrentArguments()[0];
if (!classNames.contains(name)) {
throw new ClassCastException(name);
}
return cl.loadClass(name);
}
}).anyTimes();
EasyMock.replay(providerBundle);
return providerBundle;
}
private Collection<String> getClassNames(File f) throws IOException {
List<String> names = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
try {
String line = null;
while((line = br.readLine()) != null) {
names.add(line.trim());
}
} finally {
br.close();
}
return names;
}
private Bundle mockConsumerBundle(Dictionary<String, String> headers, Bundle ... otherBundles) {
// Create a mock object for the client bundle which holds the code that uses ServiceLoader.load()
// or another SPI invocation.
BundleContext bc = EasyMock.createMock(BundleContext.class);
Bundle consumerBundle = EasyMock.createMock(Bundle.class);
EasyMock.expect(consumerBundle.getSymbolicName()).andReturn("testConsumer").anyTimes();
EasyMock.expect(consumerBundle.getHeaders()).andReturn(headers).anyTimes();
EasyMock.expect(consumerBundle.getBundleContext()).andReturn(bc).anyTimes();
EasyMock.expect(consumerBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
EasyMock.expect(consumerBundle.adapt(BundleRevision.class)).andReturn(null).anyTimes();
EasyMock.replay(consumerBundle);
List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(otherBundles));
allBundles.add(consumerBundle);
EasyMock.expect(bc.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes();
EasyMock.replay(bc);
return consumerBundle;
}
// A classloader that loads anything starting with org.apache.aries.spifly.dynamic.impl1 from it
// and the rest from the parent. This is to mimic a bundle that holds a specific SPI implementation.
public static class TestProviderBundleClassLoader extends URLClassLoader {
private final List<String> resources;
private final String prefix;
private final String classPrefix;
private final Map<String, Class<?>> loadedClasses = new ConcurrentHashMap<String, Class<?>>();
public TestProviderBundleClassLoader(String subdir, String ... resources) {
super(new URL [] {}, TestProviderBundleClassLoader.class.getClassLoader());
this.prefix = TestProviderBundleClassLoader.class.getPackage().getName().replace('.', '/') + "/" + subdir + "/";
this.classPrefix = prefix.replace('/', '.');
this.resources = Arrays.asList(resources);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith(classPrefix))
return loadClassLocal(name);
return super.loadClass(name);
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (name.startsWith(classPrefix)) {
Class<?> cls = loadClassLocal(name);
if (resolve)
resolveClass(cls);
return cls;
}
return super.loadClass(name, resolve);
}
protected Class<?> loadClassLocal(String name) throws ClassNotFoundException {
Class<?> prevLoaded = loadedClasses.get(name);
if (prevLoaded != null)
return prevLoaded;
URL res = TestProviderBundleClassLoader.class.getClassLoader().getResource(name.replace('.', '/') + ".class");
try {
byte[] bytes = Streams.suck(res.openStream());
Class<?> cls = defineClass(name, bytes, 0, bytes.length);
loadedClasses.put(name, cls);
return cls;
} catch (Exception e) {
throw new ClassNotFoundException(name, e);
}
}
@Override
public URL findResource(String name) {
if (resources.contains(name)) {
return getClass().getClassLoader().getResource(prefix + name);
} else {
return super.findResource(name);
}
}
@Override
public Enumeration<URL> findResources(String name) throws IOException {
if (resources.contains(name)) {
return getClass().getClassLoader().getResources(prefix + name);
} else {
return super.findResources(name);
}
}
}
private static class MyWovenClass implements WovenClass {
byte [] bytes;
final String className;
final Bundle bundleContainingOriginalClass;
List<String> dynamicImports = new ArrayList<String>();
boolean weavingComplete = false;
private MyWovenClass(URL clazz, String name, Bundle bundle) throws Exception {
bytes = Streams.suck(clazz.openStream());
className = name;
bundleContainingOriginalClass = bundle;
}
@Override
public byte[] getBytes() {
return bytes;
}
@Override
public void setBytes(byte[] newBytes) {
bytes = newBytes;
}
@Override
public List<String> getDynamicImports() {
return dynamicImports;
}
@Override
public boolean isWeavingComplete() {
return weavingComplete;
}
@Override
public String getClassName() {
return className;
}
@Override
public ProtectionDomain getProtectionDomain() {
return null;
}
@Override
public Class<?> getDefinedClass() {
try {
weavingComplete = true;
return new MyWovenClassClassLoader(className, getBytes(), getClass().getClassLoader(), bundleContainingOriginalClass).loadClass(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
@Override
public BundleWiring getBundleWiring() {
BundleWiring bw = EasyMock.createMock(BundleWiring.class);
EasyMock.expect(bw.getBundle()).andReturn(bundleContainingOriginalClass);
EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader());
EasyMock.replay(bw);
return bw;
}
}
private static class MyWovenClassClassLoader extends ClassLoader implements BundleReference {
private final String className;
private final Bundle bundle;
private final byte [] bytes;
private Class<?> wovenClass;
public MyWovenClassClassLoader(String className, byte[] bytes, ClassLoader parent, Bundle bundle) {
super(parent);
this.className = className;
this.bundle = bundle;
this.bytes = bytes;
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (name.equals(className)) {
if (wovenClass == null)
wovenClass = defineClass(className, bytes, 0, bytes.length);
return wovenClass;
} else {
return super.loadClass(name, resolve);
}
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
@Override
public Bundle getBundle() {
return bundle;
}
}
}
| 9,650 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookGenericCapabilityTest.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.spifly.dynamic;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.aries.spifly.BaseActivator;
import org.apache.aries.spifly.SpiFlyConstants;
import org.apache.aries.spifly.Streams;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Version;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import aQute.bnd.header.Parameters;
public class ClientWeavingHookGenericCapabilityTest {
DynamicWeavingActivator activator;
@Before
public void setUp() {
activator = new DynamicWeavingActivator();
BaseActivator.activator = activator;
}
@After
public void tearDown() {
BaseActivator.activator = null;
activator = null;
}
@Test
public void testAutoConsumerSystemProperty() throws Exception {
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.setAutoConsumerInstructions(Optional.of(new Parameters(consumerBundle.getSymbolicName())));
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(Collections.singleton("olleh"), result);
}
@Test
public void testAutoConsumerSystemProperty_negative() throws Exception {
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(0, wc.getDynamicImports().size());
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(Collections.emptySet(), result);
}
@Test
public void testBasicServiceLoaderUsage() throws Exception {
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
consumerHeaders.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT);
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(Collections.singleton("olleh"), result);
}
@Test
public void testHeadersFromFragment() throws Exception {
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Dictionary<String, String> fragmentConsumerHeaders = new Hashtable<String, String>();
fragmentConsumerHeaders.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT);
Bundle fragment = EasyMock.createMock(Bundle.class);
EasyMock.expect(fragment.getHeaders()).andReturn(fragmentConsumerHeaders).anyTimes();
EasyMock.replay(fragment);
BundleRevision frev = EasyMock.createMock(BundleRevision.class);
EasyMock.expect(frev.getBundle()).andReturn(fragment).anyTimes();
EasyMock.replay(frev);
BundleRequirement req = EasyMock.createMock(BundleRequirement.class);
EasyMock.expect(req.getRevision()).andReturn(frev).anyTimes();
EasyMock.replay(req);
BundleWire wire = EasyMock.createMock(BundleWire.class);
EasyMock.expect(wire.getRequirement()).andReturn(req).anyTimes();
EasyMock.replay(wire);
List<BundleWire> wires = Collections.singletonList(wire);
BundleWiring wiring = EasyMock.createMock(BundleWiring.class);
EasyMock.expect(wiring.getProvidedWires("osgi.wiring.host")).andReturn(wires).anyTimes();
EasyMock.replay(wiring);
BundleRevision rev = EasyMock.createMock(BundleRevision.class);
EasyMock.expect(rev.getWiring()).andReturn(wiring).anyTimes();
EasyMock.replay(rev);
Bundle consumerBundle = mockConsumerBundle(new Hashtable<String, String>(), rev, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(Collections.singleton("olleh"), result);
}
@Test
public void testTCCLResetting() throws Exception {
ClassLoader cl = new URLClassLoader(new URL [] {});
Thread.currentThread().setContextClassLoader(cl);
Assert.assertSame("Precondition", cl, Thread.currentThread().getContextClassLoader());
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
consumerHeaders.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT);
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
method.invoke(cls.getDeclaredConstructor().newInstance(), "hi there");
Assert.assertSame(cl, Thread.currentThread().getContextClassLoader());
}
@Test
public void testTCCLResettingOnException() throws Exception {
ClassLoader cl = new URLClassLoader(new URL [] {});
Thread.currentThread().setContextClassLoader(cl);
Assert.assertSame("Precondition", cl, Thread.currentThread().getContextClassLoader());
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT);
Bundle providerBundle5 = mockProviderBundle("impl5", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle5, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle5);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle,providerBundle5);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
// Invoke the woven class, check that it properly set the TCCL so that the implementation of impl5 is called.
// That implementation throws an exception, after which we are making sure that the TCCL is set back appropriately.
try {
method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.fail("Invocation should have thrown an exception");
} catch (InvocationTargetException ite) {
RuntimeException re = (RuntimeException) ite.getCause();
String msg = re.getMessage();
Assert.assertEquals("Uh-oh: hello", msg);
// The TCCL should have been reset correctly
Assert.assertSame(cl, Thread.currentThread().getContextClassLoader());
}
}
@Test
public void testAltServiceLoaderLoadUnprocessed() throws Exception {
Bundle spiFlyBundle = mockSpiFlyBundle();
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT);
Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("UnaffectedTestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.UnaffectedTestClient", consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals("The client is not affected so no additional imports should have been added",
0, wc.getDynamicImports().size());
// ok the weaving is done, now prepare the registry for the call
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals("impl4", result);
}
@Test
public void testMultipleProviders() throws Exception {
Bundle spiFlyBundle = mockSpiFlyBundle();
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT);
Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI files from impl1 and impl2 are visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("olleh", "HELLO", "5"));
Assert.assertEquals("All three services should be invoked", expected, result);
}
/* This is currently not supported in the generic model
@Test
public void testClientSpecifyingProvider() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT +
"; " + SpiFlyConstants.PROVIDER_FILTER_DIRECTIVE + ":=\"(bundle-symbolic-name=impl2)\"");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.newInstance(), "hello");
Assert.assertEquals("Only the services from bundle impl2 should be selected", "HELLO5", result);
}
@Test
public void testClientSpecifyingProviderVersion() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT +
"; " + SpiFlyConstants.PROVIDER_FILTER_DIRECTIVE + ":=\"(&(bundle-symbolic-name=impl2)(bundle-version=1.2.3))\"");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle3 = mockProviderBundle("impl2_123", 3, new Version(1, 2, 3));
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle3, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle3);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle3);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.newInstance(), "hello");
Assert.assertEquals("Only the services from bundle impl2 should be selected", "Updated!hello!Updated", result);
}
@Test
public void testClientMultipleTargetBundles() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT +
"; " + SpiFlyConstants.PROVIDER_FILTER_DIRECTIVE + ":=\"(|(bundle-symbolic-name=impl1)(bundle-symbolic-name=impl4))\"");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle4 = mockProviderBundle("impl4", 4);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.newInstance(), "hello");
Assert.assertEquals("All providers should be selected for this one", "ollehimpl4", result);
}
*/
@Test
public void testServiceFiltering() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT + "," +
SpiFlyConstants.SERVICELOADER_CAPABILITY_NAMESPACE +
"; filter:=\"(osgi.serviceloader=org.apache.aries.mytest.AltSPI)\";");
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle4 = mockProviderBundle("impl4", 4);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle2, providerBundle4);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle2, providerBundle4);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class. Since MySPI wasn't selected nothing should be returned
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals("No providers should be selected for this one", Collections.emptySet(), result);
// Weave the AltTestClient class.
URL cls2Url = getClass().getResource("AltTestClient.class");
WovenClass wc2 = new MyWovenClass(cls2Url, "org.apache.aries.spifly.dynamic.AltTestClient", consumerBundle);
wh.weave(wc2);
// Invoke the AltTestClient
Class<?> cls2 = wc2.getDefinedClass();
Method method2 = cls2.getMethod("test", new Class [] {long.class});
Object result2 = method2.invoke(cls2.getDeclaredConstructor().newInstance(), 4096);
Assert.assertEquals("All Providers should be selected", (4096L*4096L)-4096L, result2);
}
@Test
public void testServiceFilteringAlternative() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT + "," +
SpiFlyConstants.SERVICELOADER_CAPABILITY_NAMESPACE +
"; filter:=\"(|(!(osgi.serviceloader=org.apache.aries.mytest.AltSPI))" +
"(&(osgi.serviceloader=org.apache.aries.mytest.AltSPI)(bundle-symbolic-name=impl4)))\"");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle4 = mockProviderBundle("impl4", 4);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
HashMap<String, Object> attrs2 = new HashMap<String, Object>();
attrs2.put("bundle-symbolic-name", "impl2");
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, attrs2);
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2, attrs2);
HashMap<String, Object> attrs4 = new HashMap<String, Object>();
attrs4.put("bundle-symbolic-name", "impl4");
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4, attrs4);
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4, attrs4);
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("olleh", "HELLO", "5", "impl4"));
Assert.assertEquals("All providers should be selected for this one", expected, result);
// Weave the AltTestClient class.
URL cls2Url = getClass().getResource("AltTestClient.class");
WovenClass wc2 = new MyWovenClass(cls2Url, "org.apache.aries.spifly.dynamic.AltTestClient", consumerBundle);
wh.weave(wc2);
// Invoke the AltTestClient
Class<?> cls2 = wc2.getDefinedClass();
Method method2 = cls2.getMethod("test", new Class [] {long.class});
Object result2 = method2.invoke(cls2.getDeclaredConstructor().newInstance(), 4096);
Assert.assertEquals("Only the services from bundle impl4 should be selected", -4096L, result2);
}
@Test
public void testServiceFilteringNarrow() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT + "," +
SpiFlyConstants.SERVICELOADER_CAPABILITY_NAMESPACE +
"; filter:=\"(&(osgi.serviceloader=org.apache.aries.mytest.AltSPI)(bundle-symbolic-name=impl4))\"");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle4 = mockProviderBundle("impl4", 4);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
HashMap<String, Object> attrs2 = new HashMap<String, Object>();
attrs2.put("bundle-symbolic-name", "impl2");
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, attrs2);
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2, attrs2);
HashMap<String, Object> attrs4 = new HashMap<String, Object>();
attrs4.put("bundle-symbolic-name", "impl4");
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4, attrs4);
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4, attrs4);
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals("No providers should be selected here", Collections.emptySet(), result);
// Weave the AltTestClient class.
URL cls2Url = getClass().getResource("AltTestClient.class");
WovenClass wc2 = new MyWovenClass(cls2Url, "org.apache.aries.spifly.dynamic.AltTestClient", consumerBundle);
wh.weave(wc2);
// Invoke the AltTestClient
Class<?> cls2 = wc2.getDefinedClass();
Method method2 = cls2.getMethod("test", new Class [] {long.class});
Object result2 = method2.invoke(cls2.getDeclaredConstructor().newInstance(), 4096);
Assert.assertEquals("Only the services from bundle impl4 should be selected", -4096L, result2);
}
@Test
public void testFilteringCustomAttribute() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.REQUIRE_CAPABILITY, SpiFlyConstants.CLIENT_REQUIREMENT + ", " +
SpiFlyConstants.SERVICELOADER_CAPABILITY_NAMESPACE + "; filter:=\"(approval=global)\"");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Map<String, Object> attrs1 = new HashMap<String, Object>();
attrs1.put("approval", "local");
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, attrs1);
Map<String, Object> attrs2 = new HashMap<String, Object>();
attrs2.put("approval", "global");
attrs2.put("other", "attribute");
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, attrs2);
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("HELLO", "5"));
Assert.assertEquals("Only the services from bundle impl2 should be selected", expected, result);
}
@Test
public void testVersionedRequirement() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(
SpiFlyConstants.REQUIRE_CAPABILITY,
String.format(
"%s;filter:='(&(%s=%s)(version>=1.0)(!(version>=2.0)))',%s;filter:='(%s=%s)'",
SpiFlyConstants.EXTENDER_CAPABILITY_NAMESPACE,
SpiFlyConstants.EXTENDER_CAPABILITY_NAMESPACE,
SpiFlyConstants.PROCESSOR_EXTENDER_NAME,
SpiFlyConstants.SERVICELOADER_CAPABILITY_NAMESPACE,
SpiFlyConstants.SERVICELOADER_CAPABILITY_NAMESPACE,
"org.apache.aries.mytest.MySPI"));
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Map<String, Object> attrs1 = new HashMap<String, Object>();
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, attrs1);
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.REQUIRE_CAPABILITY);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("olleh"));
Assert.assertEquals(expected, result);
}
private Bundle mockSpiFlyBundle(Bundle ... bundles) throws Exception {
return mockSpiFlyBundle("spifly", new Version(1, 0, 0), bundles);
}
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle ... bundles) throws Exception {
Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
allBundles.add(spiFlyBundle);
EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes();
EasyMock.replay(spiFlyBundleContext);
EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
EasyMock.replay(spiFlyBundle);
// Set the bundle context for testing purposes
Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
bcField.setAccessible(true);
bcField.set(activator, spiFlyBundle.getBundleContext());
return spiFlyBundle;
}
private Bundle mockProviderBundle(String subdir, long id) throws Exception {
return mockProviderBundle(subdir, id, Version.emptyVersion);
}
private Bundle mockProviderBundle(String subdir, long id, Version version) throws Exception {
URL url = getClass().getResource("/" + getClass().getName().replace('.', '/') + ".class");
File classFile = new File(url.getFile());
File baseDir = new File(classFile.getParentFile(), subdir);
File directory = new File(baseDir, "/META-INF/services");
final List<String> classNames = new ArrayList<String>();
// Do a directory listing of the applicable META-INF/services directory
List<String> resources = new ArrayList<String>();
for (File f : directory.listFiles()) {
String fileName = f.getName();
if (fileName.startsWith(".") || fileName.endsWith("."))
continue;
classNames.addAll(getClassNames(f));
// Needs to be something like: META-INF/services/org.apache.aries.mytest.MySPI
String path = f.getAbsolutePath().substring(baseDir.getAbsolutePath().length());
path = path.replace('\\', '/');
if (path.startsWith("/")) {
path = path.substring(1);
}
resources.add(path);
}
// Set up the classloader that will be used by the ASM-generated code as the TCCL.
// It can load a META-INF/services file
@SuppressWarnings("resource")
final ClassLoader cl = new TestProviderBundleClassLoader(subdir, resources.toArray(new String [] {}));
final List<String> classResources = new ArrayList<String>();
for(String className : classNames) {
classResources.add("/" + className.replace('.', '/') + ".class");
}
BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
EasyMock.replay(bc);
Bundle providerBundle = EasyMock.createMock(Bundle.class);
String bsn = subdir;
int idx = bsn.indexOf('_');
if (idx > 0) {
bsn = bsn.substring(0, idx);
}
EasyMock.expect(providerBundle.getSymbolicName()).andReturn(bsn).anyTimes();
EasyMock.expect(providerBundle.getBundleId()).andReturn(id).anyTimes();
EasyMock.expect(providerBundle.getBundleContext()).andReturn(bc).anyTimes();
EasyMock.expect(providerBundle.getVersion()).andReturn(version).anyTimes();
EasyMock.expect(providerBundle.getEntryPaths("/")).andAnswer(new IAnswer<Enumeration<String>>() {
@Override
public Enumeration<String> answer() throws Throwable {
return Collections.enumeration(classResources);
}
}).anyTimes();
EasyMock.<Class<?>>expect(providerBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() {
@Override
public Class<?> answer() throws Throwable {
String name = (String) EasyMock.getCurrentArguments()[0];
if (!classNames.contains(name)) {
throw new ClassCastException(name);
}
return cl.loadClass(name);
}
}).anyTimes();
EasyMock.replay(providerBundle);
return providerBundle;
}
private Collection<String> getClassNames(File f) throws IOException {
List<String> names = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
try {
String line = null;
while((line = br.readLine()) != null) {
if (line.trim().startsWith("#")) {
continue;
}
names.add(line.trim());
}
} finally {
br.close();
}
return names;
}
private Bundle mockConsumerBundle(Dictionary<String, String> headers, Bundle ... otherBundles) {
return mockConsumerBundle(headers, null, otherBundles);
}
private Bundle mockConsumerBundle(Dictionary<String, String> headers, BundleRevision rev,
Bundle ... otherBundles) {
// Create a mock object for the client bundle which holds the code that uses ServiceLoader.load()
// or another SPI invocation.
BundleContext bc = EasyMock.createMock(BundleContext.class);
Bundle consumerBundle = EasyMock.createMock(Bundle.class);
EasyMock.expect(consumerBundle.getSymbolicName()).andReturn("testConsumer").anyTimes();
EasyMock.expect(consumerBundle.getVersion()).andReturn(new Version(1, 2, 3)).anyTimes();
EasyMock.expect(consumerBundle.getHeaders()).andReturn(headers).anyTimes();
EasyMock.expect(consumerBundle.getBundleContext()).andReturn(bc).anyTimes();
EasyMock.expect(consumerBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
EasyMock.expect(consumerBundle.adapt(BundleRevision.class)).andReturn(rev).anyTimes();
EasyMock.replay(consumerBundle);
List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(otherBundles));
allBundles.add(consumerBundle);
EasyMock.expect(bc.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes();
EasyMock.replay(bc);
return consumerBundle;
}
// A classloader that loads anything starting with org.apache.aries.spifly.dynamic.impl1 from it
// and the rest from the parent. This is to mimic a bundle that holds a specific SPI implementation.
public static class TestProviderBundleClassLoader extends URLClassLoader {
private final List<String> resources;
private final String prefix;
private final String classPrefix;
private final Map<String, Class<?>> loadedClasses = new ConcurrentHashMap<String, Class<?>>();
public TestProviderBundleClassLoader(String subdir, String ... resources) {
super(new URL [] {}, TestProviderBundleClassLoader.class.getClassLoader());
this.prefix = TestProviderBundleClassLoader.class.getPackage().getName().replace('.', '/') + "/" + subdir + "/";
this.classPrefix = prefix.replace('/', '.');
this.resources = Arrays.asList(resources);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith(classPrefix))
return loadClassLocal(name);
return super.loadClass(name);
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (name.startsWith(classPrefix)) {
Class<?> cls = loadClassLocal(name);
if (resolve)
resolveClass(cls);
return cls;
}
return super.loadClass(name, resolve);
}
protected Class<?> loadClassLocal(String name) throws ClassNotFoundException {
Class<?> prevLoaded = loadedClasses.get(name);
if (prevLoaded != null)
return prevLoaded;
URL res = TestProviderBundleClassLoader.class.getClassLoader().getResource(name.replace('.', '/') + ".class");
try {
byte[] bytes = Streams.suck(res.openStream());
Class<?> cls = defineClass(name, bytes, 0, bytes.length);
loadedClasses.put(name, cls);
return cls;
} catch (Exception e) {
throw new ClassNotFoundException(name, e);
}
}
@Override
public URL findResource(String name) {
if (resources.contains(name)) {
return getClass().getClassLoader().getResource(prefix + name);
} else {
return super.findResource(name);
}
}
@Override
public Enumeration<URL> findResources(String name) throws IOException {
if (resources.contains(name)) {
return getClass().getClassLoader().getResources(prefix + name);
} else {
return super.findResources(name);
}
}
}
private static class MyWovenClass implements WovenClass {
byte [] bytes;
final String className;
final Bundle bundleContainingOriginalClass;
List<String> dynamicImports = new ArrayList<String>();
boolean weavingComplete = false;
private MyWovenClass(URL clazz, String name, Bundle bundle) throws Exception {
bytes = Streams.suck(clazz.openStream());
className = name;
bundleContainingOriginalClass = bundle;
}
@Override
public byte[] getBytes() {
return bytes;
}
@Override
public void setBytes(byte[] newBytes) {
bytes = newBytes;
}
@Override
public List<String> getDynamicImports() {
return dynamicImports;
}
@Override
public boolean isWeavingComplete() {
return weavingComplete;
}
@Override
public String getClassName() {
return className;
}
@Override
public ProtectionDomain getProtectionDomain() {
return null;
}
@Override
public Class<?> getDefinedClass() {
try {
weavingComplete = true;
return new MyWovenClassClassLoader(className, getBytes(), getClass().getClassLoader(), bundleContainingOriginalClass).loadClass(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
@Override
public BundleWiring getBundleWiring() {
BundleWiring bw = EasyMock.createMock(BundleWiring.class);
EasyMock.expect(bw.getBundle()).andReturn(bundleContainingOriginalClass);
EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader());
EasyMock.replay(bw);
return bw;
}
}
private static class MyWovenClassClassLoader extends ClassLoader implements BundleReference {
private final String className;
private final Bundle bundle;
private final byte [] bytes;
private Class<?> wovenClass;
public MyWovenClassClassLoader(String className, byte[] bytes, ClassLoader parent, Bundle bundle) {
super(parent);
this.className = className;
this.bundle = bundle;
this.bytes = bytes;
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (name.equals(className)) {
if (wovenClass == null)
wovenClass = defineClass(className, bytes, 0, bytes.length);
return wovenClass;
} else {
return super.loadClass(name, resolve);
}
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
@Override
public Bundle getBundle() {
return bundle;
}
}
}
| 9,651 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookTest.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.spifly.dynamic;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.aries.mytest.MySPI;
import org.apache.aries.spifly.BaseActivator;
import org.apache.aries.spifly.SpiFlyConstants;
import org.apache.aries.spifly.Streams;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Version;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWiring;
public class ClientWeavingHookTest {
DynamicWeavingActivator activator;
private static final String thisJVMsDBF = DocumentBuilderFactory.newInstance().getClass().getName();
@Before
public void setUp() {
activator = new DynamicWeavingActivator();
BaseActivator.activator = activator;
}
@After
public void tearDown() {
BaseActivator.activator = null;
activator = null;
}
@Test
public void testBasicServiceLoaderUsage() throws Exception {
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
consumerHeaders.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(Collections.singleton("olleh"), result);
}
@Test
public void test_ARIES_1755_ServiceLoaderUsage() throws Exception {
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
consumerHeaders.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient3$EnumLoader.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient3$EnumLoader";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("load", new Class [] {Class.class});
@SuppressWarnings({ "unchecked", "rawtypes" })
Object result = method.invoke(Enum.valueOf((Class<? extends Enum>)cls, "INSTANCE"), MySPI.class);
Assert.assertTrue("Either null or not a MySPI", result instanceof MySPI);
MySPI instance = (MySPI)result;
String someMethod = instance.someMethod("Hello");
Assert.assertEquals("olleH", someMethod);
}
@Test
public void testBasicServiceLoaderUsage2() throws Exception {
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
consumerHeaders.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("testService2", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(Collections.singleton("olleh"), result);
}
@Test
public void testBasicServiceLoaderUsage3() throws Exception {
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
consumerHeaders.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient2.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient2";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(Collections.singleton("olleh"), result);
}
@Test
public void testTCCLResetting() throws Exception {
ClassLoader cl = new URLClassLoader(new URL [] {});
Thread.currentThread().setContextClassLoader(cl);
Assert.assertSame("Precondition", cl, Thread.currentThread().getContextClassLoader());
Dictionary<String, String> consumerHeaders = new Hashtable<String, String>();
consumerHeaders.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
// Register the bundle that provides the SPI implementation.
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(consumerHeaders, providerBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle("spifly", Version.parseVersion("1.9.4"), consumerBundle, providerBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
String clientClassName = "org.apache.aries.spifly.dynamic.TestClient";
WovenClass wc = new MyWovenClass(clsUrl, clientClassName, consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals(1, wc.getDynamicImports().size());
String di1 = "org.apache.aries.spifly";
String di = wc.getDynamicImports().get(0);
Assert.assertTrue("Weaving should have added a dynamic import", di1.equals(di));
// Invoke the woven class and check that it properly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
method.invoke(cls.getDeclaredConstructor().newInstance(), "hi there");
Assert.assertSame(cl, Thread.currentThread().getContextClassLoader());
}
@Test
public void testTCCLResettingOnException() {
// TODO
}
@Test
public void testAltServiceLoaderLoadUnprocessed() throws Exception {
Bundle spiFlyBundle = mockSpiFlyBundle();
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("UnaffectedTestClient.class");
Assert.assertNotNull("Precondition", clsUrl);
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.UnaffectedTestClient", consumerBundle);
Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
wh.weave(wc);
Assert.assertEquals("The client is not affected so no additional imports should have been added",
0, wc.getDynamicImports().size());
// ok the weaving is done, now prepare the registry for the call
Bundle providerBundle = mockProviderBundle("impl1", 1);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals("impl4", result);
}
@Test
public void testMultipleProviders() throws Exception {
Bundle spiFlyBundle = mockSpiFlyBundle();
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI files from impl1 and impl2 are visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("olleh", "HELLO", "5"));
Assert.assertEquals("All three services should be invoked", expected, result);
}
@Test
public void testClientSpecifyingProvider() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundle=impl2");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("HELLO", "5"));
Assert.assertEquals("Only the services from bundle impl2 should be selected", expected, result);
}
@Test
public void testClientSpecifyingProviderVersion() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "java.util.ServiceLoader#load(java.lang.Class);bundle=impl2:version=1.2.3");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle3 = mockProviderBundle("impl2_123", 3, new Version(1, 2, 3));
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle3, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle3);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle3);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals("Only the services from bundle impl2 should be selected", Collections.singleton("Updated!hello!Updated"), result);
}
@Test
public void testClientMultipleTargetBundles() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER,
"java.util.ServiceLoader#load(java.lang.Class);bundle=impl1|impl4");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle4 = mockProviderBundle("impl4", 4);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("olleh", "impl4"));
Assert.assertEquals("All providers should be selected for this one", expected, result);
}
@Test
public void testClientMultipleTargetBundles2() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER,
"java.util.ServiceLoader#load(java.lang.Class);bundleId=1|4");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle4 = mockProviderBundle("impl4", 4);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("olleh", "impl4"));
Assert.assertEquals("All providers should be selected for this one", expected, result);
}
@Test
public void testClientSpecificProviderLoadArgument() throws Exception {
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER,
"java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.MySPI])," +
"java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.AltSPI]);bundle=impl4");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle4 = mockProviderBundle("impl4", 4);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4, new HashMap<String, Object>());
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle1, providerBundle2, providerBundle4);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle, providerBundle1, providerBundle2, providerBundle4);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Set<String> expected = new HashSet<String>(Arrays.asList("olleh", "impl4", "HELLO", "5"));
Assert.assertEquals("All providers should be selected for this one", expected, result);
// Weave the AltTestClient class.
URL cls2Url = getClass().getResource("AltTestClient.class");
WovenClass wc2 = new MyWovenClass(cls2Url, "org.apache.aries.spifly.dynamic.AltTestClient", consumerBundle);
wh.weave(wc2);
// Invoke the AltTestClient
Class<?> cls2 = wc2.getDefinedClass();
Method method2 = cls2.getMethod("test", new Class [] {long.class});
Object result2 = method2.invoke(cls2.getDeclaredConstructor().newInstance(), 4096);
Assert.assertEquals("Only the services from bundle impl4 should be selected", -4096L, result2);
}
@Test
public void testClientSpecifyingDifferentMethodsLimitedToDifferentProviders() throws Exception {
Dictionary<String, String> headers1 = new Hashtable<String, String>();
headers1.put(SpiFlyConstants.SPI_CONSUMER_HEADER,
"javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=impl3," +
"java.util.ServiceLoader#load(java.lang.Class[org.apache.aries.mytest.MySPI]);bundle=impl4");
Dictionary<String, String> headers2 = new Hashtable<String, String>();
headers2.put(SpiFlyConstants.SPI_CONSUMER_HEADER,
"javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=system.bundle," +
"java.util.ServiceLoader#load;bundle=impl1");
Dictionary<String, String> headers3 = new Hashtable<String, String>();
headers3.put(SpiFlyConstants.SPI_CONSUMER_HEADER,
"org.acme.blah#someMethod();bundle=mybundle");
Bundle providerBundle1 = mockProviderBundle("impl1", 1);
Bundle providerBundle2 = mockProviderBundle("impl2", 2);
Bundle providerBundle3 = mockProviderBundle("impl3", 3);
Bundle providerBundle4 = mockProviderBundle("impl4", 4);
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle2, new HashMap<String, Object>());
activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle3, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle4, new HashMap<String, Object>());
activator.registerProviderBundle("org.apache.aries.mytest.AltSPI", providerBundle4, new HashMap<String, Object>());
Bundle consumerBundle1 = mockConsumerBundle(headers1, providerBundle1, providerBundle2, providerBundle3, providerBundle4);
activator.addConsumerWeavingData(consumerBundle1, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle consumerBundle2 = mockConsumerBundle(headers2, providerBundle1, providerBundle2, providerBundle3, providerBundle4);
activator.addConsumerWeavingData(consumerBundle2, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle consumerBundle3 = mockConsumerBundle(headers3, providerBundle1, providerBundle2, providerBundle3, providerBundle4);
activator.addConsumerWeavingData(consumerBundle3, SpiFlyConstants.SPI_CONSUMER_HEADER);
Bundle spiFlyBundle = mockSpiFlyBundle(consumerBundle1, consumerBundle2, consumerBundle3,
providerBundle1, providerBundle2, providerBundle3, providerBundle4);
WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
testConsumerBundleWeaving(consumerBundle1, wh, Collections.singleton("impl4"), "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory");
testConsumerBundleWeaving(consumerBundle2, wh, Collections.singleton("olleh"), thisJVMsDBF);
testConsumerBundleWeaving(consumerBundle3, wh, Collections.<String>emptySet(), thisJVMsDBF);
testConsumerBundleWeavingNonConst(consumerBundle1, wh, Collections.singleton("impl4"), "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory");
testConsumerBundleWeavingNonConst(consumerBundle2, wh, Collections.singleton("olleh"), thisJVMsDBF);
testConsumerBundleWeavingNonConst(consumerBundle3, wh, Collections.<String>emptySet(), thisJVMsDBF);
}
private void testConsumerBundleWeaving(Bundle consumerBundle, WeavingHook wh, Set<String> testClientResult, String jaxpClientResult) throws Exception {
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, TestClient.class.getName(), consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {String.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello");
Assert.assertEquals(testClientResult, result);
URL clsUrl2 = getClass().getResource("JaxpClient.class");
WovenClass wc2 = new MyWovenClass(clsUrl2, JaxpClient.class.getName(), consumerBundle);
wh.weave(wc2);
Class<?> cls2 = wc2.getDefinedClass();
Method method2 = cls2.getMethod("test", new Class [] {});
Class<?> result2 = (Class<?>) method2.invoke(cls2.getDeclaredConstructor().newInstance());
Assert.assertEquals(jaxpClientResult, result2.getName());
}
private void testConsumerBundleWeavingNonConst(Bundle consumerBundle, WeavingHook wh, Set<String> testClientResult, String jaxpClientResult) throws Exception {
// Weave the TestClient class.
URL clsUrl = getClass().getResource("TestClient.class");
WovenClass wc = new MyWovenClass(clsUrl, TestClient.class.getName(), consumerBundle);
wh.weave(wc);
// Invoke the woven class and check that it propertly sets the TCCL so that the
// META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("testService", new Class [] {String.class, Class.class});
Object result = method.invoke(cls.getDeclaredConstructor().newInstance(), "hello", MySPI.class);
Assert.assertEquals(testClientResult, result);
}
@Test
public void testJAXPClientWantsJREImplementation1() throws Exception {
Bundle systembundle = mockSystemBundle();
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()");
Bundle consumerBundle = mockConsumerBundle(headers, systembundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, systembundle).getBundleContext(), activator);
URL clsUrl = getClass().getResource("JaxpClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
wh.weave(wc);
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {});
Class<?> result = (Class<?>) method.invoke(cls.getDeclaredConstructor().newInstance());
Assert.assertEquals("JAXP implementation from JRE", thisJVMsDBF, result.getName());
}
// If there is an alternate implementation it should always be favoured over the JRE one
@Test
public void testJAXPClientWantsAltImplementation1() throws Exception {
Bundle systembundle = mockSystemBundle();
Bundle providerBundle = mockProviderBundle("impl3", 1);
activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance()");
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
URL clsUrl = getClass().getResource("JaxpClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
wh.weave(wc);
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {});
Class<?> result = (Class<?>) method.invoke(cls.getDeclaredConstructor().newInstance());
Assert.assertEquals("JAXP implementation from JRE", "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory", result.getName());
}
@Test
public void testJAXPClientWantsJREImplementation2() throws Exception {
Bundle systembundle = mockSystemBundle();
Bundle providerBundle = mockProviderBundle("impl3", 1);
activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundleId=0");
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
URL clsUrl = getClass().getResource("JaxpClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
wh.weave(wc);
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {});
Class<?> result = (Class<?>) method.invoke(cls.getDeclaredConstructor().newInstance());
Assert.assertEquals("JAXP implementation from JRE", thisJVMsDBF, result.getName());
}
@Test
public void testJAXPClientWantsAltImplementation2() throws Exception {
Bundle systembundle = mockSystemBundle();
Bundle providerBundle = mockProviderBundle("impl3", 1);
activator.registerProviderBundle("javax.xml.parsers.DocumentBuilderFactory", providerBundle, new HashMap<String, Object>());
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "javax.xml.parsers.DocumentBuilderFactory#newInstance();bundle=impl3");
Bundle consumerBundle = mockConsumerBundle(headers, providerBundle, systembundle);
activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
WeavingHook wh = new ClientWeavingHook(mockSpiFlyBundle(consumerBundle, providerBundle, systembundle).getBundleContext(), activator);
URL clsUrl = getClass().getResource("JaxpClient.class");
WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.JaxpClient", consumerBundle);
wh.weave(wc);
Class<?> cls = wc.getDefinedClass();
Method method = cls.getMethod("test", new Class [] {});
Class<?> result = (Class<?>) method.invoke(cls.getDeclaredConstructor().newInstance());
Assert.assertEquals("JAXP implementation from alternative bundle", "org.apache.aries.spifly.dynamic.impl3.MyAltDocumentBuilderFactory", result.getName());
}
private Bundle mockSpiFlyBundle(Bundle ... bundles) throws Exception {
return mockSpiFlyBundle("spifly", new Version(1, 0, 0), bundles);
}
private Bundle mockSpiFlyBundle(String bsn, Version version, Bundle ... bundles) throws Exception {
Bundle spiFlyBundle = EasyMock.createMock(Bundle.class);
BundleContext spiFlyBundleContext = EasyMock.createMock(BundleContext.class);
EasyMock.expect(spiFlyBundleContext.getBundle()).andReturn(spiFlyBundle).anyTimes();
List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(bundles));
allBundles.add(spiFlyBundle);
EasyMock.expect(spiFlyBundleContext.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes();
EasyMock.replay(spiFlyBundleContext);
EasyMock.expect(spiFlyBundle.getSymbolicName()).andReturn(bsn).anyTimes();
EasyMock.expect(spiFlyBundle.getVersion()).andReturn(version).anyTimes();
EasyMock.expect(spiFlyBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
EasyMock.expect(spiFlyBundle.getBundleContext()).andReturn(spiFlyBundleContext).anyTimes();
EasyMock.replay(spiFlyBundle);
// Set the bundle context for testing purposes
Field bcField = BaseActivator.class.getDeclaredField("bundleContext");
bcField.setAccessible(true);
bcField.set(activator, spiFlyBundle.getBundleContext());
return spiFlyBundle;
}
private Bundle mockProviderBundle(String subdir, long id) throws Exception {
return mockProviderBundle(subdir, id, Version.emptyVersion);
}
private Bundle mockProviderBundle(String subdir, long id, Version version) throws Exception {
URL url = getClass().getResource("/" + getClass().getName().replace('.', '/') + ".class");
File classFile = new File(url.getFile());
File baseDir = new File(classFile.getParentFile(), subdir);
File directory = new File(baseDir, "/META-INF/services");
final List<String> classNames = new ArrayList<String>();
// Do a directory listing of the applicable META-INF/services directory
List<String> resources = new ArrayList<String>();
for (File f : directory.listFiles()) {
String fileName = f.getName();
if (fileName.startsWith(".") || fileName.endsWith("."))
continue;
classNames.addAll(getClassNames(f));
// Needs to be something like: META-INF/services/org.apache.aries.mytest.MySPI
String path = f.getAbsolutePath().substring(baseDir.getAbsolutePath().length());
path = path.replace('\\', '/');
if (path.startsWith("/")) {
path = path.substring(1);
}
resources.add(path);
}
// Set up the classloader that will be used by the ASM-generated code as the TCCL.
// It can load a META-INF/services file
@SuppressWarnings("resource")
final ClassLoader cl = new TestProviderBundleClassLoader(subdir, resources.toArray(new String [] {}));
final List<String> classResources = new ArrayList<String>();
for(String className : classNames) {
classResources.add("/" + className.replace('.', '/') + ".class");
}
BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
EasyMock.replay(bc);
Bundle providerBundle = EasyMock.createMock(Bundle.class);
String bsn = subdir;
int idx = bsn.indexOf('_');
if (idx > 0) {
bsn = bsn.substring(0, idx);
}
EasyMock.expect(providerBundle.getSymbolicName()).andReturn(bsn).anyTimes();
EasyMock.expect(providerBundle.getBundleId()).andReturn(id).anyTimes();
EasyMock.expect(providerBundle.getBundleContext()).andReturn(bc).anyTimes();
EasyMock.expect(providerBundle.getVersion()).andReturn(version).anyTimes();
EasyMock.expect(providerBundle.getEntryPaths("/")).andAnswer(new IAnswer<Enumeration<String>>() {
@Override
public Enumeration<String> answer() throws Throwable {
return Collections.enumeration(classResources);
}
}).anyTimes();
EasyMock.<Class<?>>expect(providerBundle.loadClass(EasyMock.anyObject(String.class))).andAnswer(new IAnswer<Class<?>>() {
@Override
public Class<?> answer() throws Throwable {
String name = (String) EasyMock.getCurrentArguments()[0];
if (!classNames.contains(name)) {
throw new ClassCastException(name);
}
return cl.loadClass(name);
}
}).anyTimes();
EasyMock.replay(providerBundle);
return providerBundle;
}
private Collection<String> getClassNames(File f) throws IOException {
List<String> names = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
try {
String line = null;
while((line = br.readLine()) != null) {
if (line.trim().startsWith("#")) {
continue;
}
names.add(line.trim());
}
} finally {
br.close();
}
return names;
}
private Bundle mockConsumerBundle(Dictionary<String, String> headers, Bundle ... otherBundles) {
// Create a mock object for the client bundle which holds the code that uses ServiceLoader.load()
// or another SPI invocation.
BundleContext bc = EasyMock.createMock(BundleContext.class);
Bundle consumerBundle = EasyMock.createMock(Bundle.class);
EasyMock.expect(consumerBundle.getSymbolicName()).andReturn("testConsumer").anyTimes();
EasyMock.expect(consumerBundle.getHeaders()).andReturn(headers).anyTimes();
EasyMock.expect(consumerBundle.getBundleContext()).andReturn(bc).anyTimes();
EasyMock.expect(consumerBundle.getBundleId()).andReturn(Long.MAX_VALUE).anyTimes();
EasyMock.expect(consumerBundle.adapt(BundleRevision.class)).andReturn(null).anyTimes();
EasyMock.replay(consumerBundle);
List<Bundle> allBundles = new ArrayList<Bundle>(Arrays.asList(otherBundles));
allBundles.add(consumerBundle);
EasyMock.expect(bc.getBundles()).andReturn(allBundles.toArray(new Bundle [] {})).anyTimes();
EasyMock.replay(bc);
return consumerBundle;
}
private Bundle mockSystemBundle() {
Bundle systemBundle = EasyMock.createMock(Bundle.class);
EasyMock.expect(systemBundle.getBundleId()).andReturn(0L).anyTimes();
EasyMock.expect(systemBundle.getSymbolicName()).andReturn("system.bundle").anyTimes();
EasyMock.replay(systemBundle);
return systemBundle;
}
// A classloader that loads anything starting with org.apache.aries.spifly.dynamic.impl1 from it
// and the rest from the parent. This is to mimic a bundle that holds a specific SPI implementation.
public static class TestProviderBundleClassLoader extends URLClassLoader {
private final List<String> resources;
private final String prefix;
private final String classPrefix;
private final Map<String, Class<?>> loadedClasses = new ConcurrentHashMap<String, Class<?>>();
public TestProviderBundleClassLoader(String subdir, String ... resources) {
super(new URL [] {}, TestProviderBundleClassLoader.class.getClassLoader());
this.prefix = TestProviderBundleClassLoader.class.getPackage().getName().replace('.', '/') + "/" + subdir + "/";
this.classPrefix = prefix.replace('/', '.');
this.resources = Arrays.asList(resources);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith(classPrefix))
return loadClassLocal(name);
return super.loadClass(name);
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (name.startsWith(classPrefix)) {
Class<?> cls = loadClassLocal(name);
if (resolve)
resolveClass(cls);
return cls;
}
return super.loadClass(name, resolve);
}
protected Class<?> loadClassLocal(String name) throws ClassNotFoundException {
Class<?> prevLoaded = loadedClasses.get(name);
if (prevLoaded != null)
return prevLoaded;
URL res = TestProviderBundleClassLoader.class.getClassLoader().getResource(name.replace('.', '/') + ".class");
try {
byte[] bytes = Streams.suck(res.openStream());
Class<?> cls = defineClass(name, bytes, 0, bytes.length);
loadedClasses.put(name, cls);
return cls;
} catch (Exception e) {
throw new ClassNotFoundException(name, e);
}
}
@Override
public URL findResource(String name) {
if (resources.contains(name)) {
return getClass().getClassLoader().getResource(prefix + name);
} else {
return super.findResource(name);
}
}
@Override
public Enumeration<URL> findResources(String name) throws IOException {
if (resources.contains(name)) {
return getClass().getClassLoader().getResources(prefix + name);
} else {
return super.findResources(name);
}
}
}
private static class MyWovenClass implements WovenClass {
byte [] bytes;
final String className;
final Bundle bundleContainingOriginalClass;
List<String> dynamicImports = new ArrayList<String>();
boolean weavingComplete = false;
private MyWovenClass(URL clazz, String name, Bundle bundle) throws Exception {
bytes = Streams.suck(clazz.openStream());
className = name;
bundleContainingOriginalClass = bundle;
}
@Override
public byte[] getBytes() {
return bytes;
}
@Override
public void setBytes(byte[] newBytes) {
bytes = newBytes;
}
@Override
public List<String> getDynamicImports() {
return dynamicImports;
}
@Override
public boolean isWeavingComplete() {
return weavingComplete;
}
@Override
public String getClassName() {
return className;
}
@Override
public ProtectionDomain getProtectionDomain() {
return null;
}
@Override
public Class<?> getDefinedClass() {
try {
weavingComplete = true;
return new MyWovenClassClassLoader(className, getBytes(), getClass().getClassLoader(), bundleContainingOriginalClass).loadClass(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
@Override
public BundleWiring getBundleWiring() {
BundleWiring bw = EasyMock.createMock(BundleWiring.class);
EasyMock.expect(bw.getBundle()).andReturn(bundleContainingOriginalClass);
EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader());
EasyMock.replay(bw);
return bw;
}
}
private static class MyWovenClassClassLoader extends ClassLoader implements BundleReference {
private final String className;
private final Bundle bundle;
private final byte [] bytes;
private Class<?> wovenClass;
public MyWovenClassClassLoader(String className, byte[] bytes, ClassLoader parent, Bundle bundle) {
super(parent);
this.className = className;
this.bundle = bundle;
this.bytes = bytes;
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (name.equals(className)) {
if (wovenClass == null)
wovenClass = defineClass(className, bytes, 0, bytes.length);
return wovenClass;
} else {
return super.loadClass(name, resolve);
}
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
@Override
public Bundle getBundle() {
return bundle;
}
}
}
| 9,652 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/TestClient3.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.spifly.dynamic;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.Set;
import org.apache.aries.mytest.MySPI;
public class TestClient3 {
public Set<String> test(String input) {
Set<String> results = new HashSet<String>();
MySPI mySPI = EnumLoader.INSTANCE.load(MySPI.class);
results.add(mySPI.someMethod(input));
return results;
}
public static enum EnumLoader {
INSTANCE;
public <S> S load(Class<S> type) {
Iterator<S> services = ServiceLoader.load(type).iterator();
return services.hasNext() ? services.next() : null;
}
}
}
| 9,653 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/AltTestClient.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.spifly.dynamic;
import java.util.ServiceLoader;
import org.apache.aries.mytest.AltSPI;
public class AltTestClient {
public long test(long input) {
long result = 0;
ServiceLoader<AltSPI> loader = ServiceLoader.load(AltSPI.class);
for (AltSPI mySPI : loader) {
result += mySPI.square(input);
}
return result;
}
}
| 9,654 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/TestClient2.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.spifly.dynamic;
import java.util.HashSet;
import java.util.ServiceLoader;
import java.util.Set;
import org.apache.aries.mytest.MySPI;
public class TestClient2 {
public Set<String> test(String input) {
Set<String> results = new HashSet<String>();
ServiceLoader<MySPI> loader = ServiceLoader.load(MySPI.class, getClass().getClassLoader());
for (MySPI mySPI : loader) {
results.add(mySPI.someMethod(input));
}
return results;
}
}
| 9,655 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/UnaffectedTestClient.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.spifly.dynamic;
import java.util.ServiceLoader;
import org.apache.aries.mytest.MySPI;
public class UnaffectedTestClient {
public String test(String input) {
StringBuilder sb = new StringBuilder();
ServiceLoader<MySPI> loader = ServiceLoader.load(MySPI.class,
new ClientWeavingHookTest.TestProviderBundleClassLoader("impl4", "META-INF/services/org.apache.aries.mytest.MySPI"));
for (MySPI mySPI : loader) {
sb.append(mySPI.someMethod(input));
}
return sb.toString();
}
}
| 9,656 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl2_123/MySPIImpl2B.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.spifly.dynamic.impl2_123;
import org.apache.aries.mytest.MySPI;
public class MySPIImpl2B implements MySPI {
@Override
public String someMethod(String s) {
return "Updated!" + s + "!Updated";
}
}
| 9,657 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl1/MySPIImpl1.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.spifly.dynamic.impl1;
import org.apache.aries.mytest.MySPI;
public class MySPIImpl1 implements MySPI{
@Override
public String someMethod(String s) {
return new StringBuilder(s).reverse().toString();
}
}
| 9,658 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl2/MySPIImpl3.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.spifly.dynamic.impl2;
import org.apache.aries.mytest.MySPI;
public class MySPIImpl3 implements MySPI{
@Override
public String someMethod(String s) {
return "" + s.length();
}
}
| 9,659 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl2/MySPIImpl2.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.spifly.dynamic.impl2;
import org.apache.aries.mytest.MySPI;
public class MySPIImpl2 implements MySPI{
@Override
public String someMethod(String s) {
return s.toUpperCase();
}
}
| 9,660 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl2/AltSPIImpl1.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.spifly.dynamic.impl2;
import org.apache.aries.mytest.AltSPI;
public class AltSPIImpl1 implements AltSPI {
@Override
public long square(long l) {
return l * l;
}
}
| 9,661 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl5/MySPIImpl5.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.spifly.dynamic.impl5;
import org.apache.aries.mytest.MySPI;
public class MySPIImpl5 implements MySPI{
@Override
public String someMethod(String s) {
throw new RuntimeException("Uh-oh: " + s);
}
}
| 9,662 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl4/AltSPIImpl2.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.spifly.dynamic.impl4;
import org.apache.aries.mytest.AltSPI;
public class AltSPIImpl2 implements AltSPI {
@Override
public long square(long l) {
return -l;
}
}
| 9,663 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl4/MySPIImpl4.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.spifly.dynamic.impl4;
import org.apache.aries.mytest.MySPI;
public class MySPIImpl4 implements MySPI {
@Override
public String someMethod(String s) {
return "impl4";
}
}
| 9,664 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/impl3/MyAltDocumentBuilderFactory.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.spifly.dynamic.impl3;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class MyAltDocumentBuilderFactory extends DocumentBuilderFactory {
@Override
public DocumentBuilder newDocumentBuilder()
throws ParserConfigurationException {
return null;
}
@Override
public void setAttribute(String name, Object value)
throws IllegalArgumentException {
}
@Override
public Object getAttribute(String name) throws IllegalArgumentException {
return null;
}
@Override
public void setFeature(String name, boolean value)
throws ParserConfigurationException {
}
@Override
public boolean getFeature(String name) throws ParserConfigurationException {
return false;
}
}
| 9,665 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/main/java/org/apache/aries/spifly/dynamic/DynamicWeavingActivator.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.spifly.dynamic;
import org.apache.aries.spifly.BaseActivator;
import org.apache.aries.spifly.SpiFlyConstants;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.hooks.weaving.WeavingHook;
public class DynamicWeavingActivator extends BaseActivator implements BundleActivator {
@SuppressWarnings("rawtypes")
private ServiceRegistration weavingHookService;
@Override
public synchronized void start(BundleContext context) throws Exception {
WeavingHook wh = new ClientWeavingHook(context, this);
weavingHookService = context.registerService(WeavingHook.class.getName(), wh, null);
super.start(context, SpiFlyConstants.SPI_CONSUMER_HEADER);
}
@Override
public synchronized void stop(BundleContext context) throws Exception {
weavingHookService.unregister();
super.stop(context);
}
}
| 9,666 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/main/java/org/apache/aries/spifly/dynamic/OSGiFriendlyClassWriter.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.spifly.dynamic;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import aQute.bnd.annotation.baseline.BaselineIgnore;
/**
* We need to override ASM's default behaviour in {@link #getCommonSuperClass(String, String)}
* so that it doesn't load classes (which it was doing on the wrong {@link ClassLoader}
* anyway...)
*
* Taken from the org.apache.aries.proxy.impl module.
*/
@BaselineIgnore("1.3.0")
public final class OSGiFriendlyClassWriter extends ClassWriter {
private static final String OBJECT_INTERNAL_NAME = "java/lang/Object";
private final ClassLoader loader;
public OSGiFriendlyClassWriter(ClassReader arg0, int arg1, ClassLoader loader) {
super(arg0, arg1);
this.loader = loader;
}
public OSGiFriendlyClassWriter(int arg0, ClassLoader loader) {
super(arg0);
this.loader = loader;
}
/**
* We provide an implementation that doesn't cause class loads to occur. It may
* not be sufficient because it expects to find the common parent using a single
* classloader, though in fact the common parent may only be loadable by another
* bundle from which an intermediate class is loaded
*
* precondition: arg0 and arg1 are not equal. (checked before this method is called)
*/
@Override
protected final String getCommonSuperClass(String arg0, String arg1) {
//If either is Object, then Object must be the answer
if(arg0.equals(OBJECT_INTERNAL_NAME) || arg1.equals(OBJECT_INTERNAL_NAME)) {
return OBJECT_INTERNAL_NAME;
}
Set<String> names = new HashSet<String>();
names.add(arg0);
names.add(arg1);
//Try loading the class (in ASM not for real)
try {
boolean bRunning = true;
boolean aRunning = true;
InputStream is;
String arg00 = arg0;
String arg11 = arg1;
while(aRunning || bRunning ) {
if(aRunning) {
is = loader.getResourceAsStream(arg00 + ".class");
if(is != null) {
ClassReader cr = new ClassReader(is);
arg00 = cr.getSuperName();
if(arg00 == null) {
if (names.size() == 2) {
return OBJECT_INTERNAL_NAME; //arg0 is an interface
}
aRunning = false; //old arg00 was java.lang.Object
} else if(!!!names.add(arg00)) {
return arg00;
}
} else {
//The class file isn't visible on this ClassLoader
aRunning = false;
}
}
if(bRunning) {
is = loader.getResourceAsStream(arg11 + ".class");
if(is != null) {
ClassReader cr = new ClassReader(is);
arg11 = cr.getSuperName();
if(arg11 == null) {
if (names.size() == 3) {
return OBJECT_INTERNAL_NAME; //arg1 is an interface
}
bRunning = false; //old arg11 was java.lang.Object
} else if(!!!names.add(arg11)) {
return arg11;
}
} else {
bRunning = false;
}
}
}
throw new RuntimeException("No Common Superclass:" + arg0 + " " + arg1);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 9,667 |
0 | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-dynamic-bundle/src/main/java/org/apache/aries/spifly/dynamic/ClientWeavingHook.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.spifly.dynamic;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Set;
import java.util.logging.Level;
import org.apache.aries.spifly.Util;
import org.apache.aries.spifly.WeavingData;
import org.apache.aries.spifly.weaver.TCCLSetterVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.TraceClassVisitor;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
public class ClientWeavingHook implements WeavingHook {
private final String addedImport;
private final DynamicWeavingActivator activator;
ClientWeavingHook(BundleContext context, DynamicWeavingActivator dwActivator) {
activator = dwActivator;
addedImport = Util.class.getPackage().getName();
}
@Override
public void weave(WovenClass wovenClass) {
Bundle consumerBundle = wovenClass.getBundleWiring().getBundle();
Set<WeavingData> wd = activator.getWeavingData(consumerBundle);
if (wd != null) {
activator.log(Level.FINE, "Weaving class " + wovenClass.getClassName());
ClassReader cr = new ClassReader(wovenClass.getBytes());
ClassWriter cw = new OSGiFriendlyClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES,
wovenClass.getBundleWiring().getClassLoader());
TCCLSetterVisitor tsv = new TCCLSetterVisitor(cw, wovenClass.getClassName(), wd);
cr.accept(tsv, ClassReader.SKIP_FRAMES);
if (tsv.isWoven()) {
wovenClass.setBytes(cw.toByteArray());
if (tsv.additionalImportRequired())
wovenClass.getDynamicImports().add(addedImport);
if (activator.isLogEnabled(Level.FINEST)) {
StringWriter stringWriter = new StringWriter();
ClassReader reader = new ClassReader(wovenClass.getBytes());
ClassVisitor tracer = new TraceClassVisitor(new PrintWriter(stringWriter));
ClassVisitor checker = new CheckClassAdapter(tracer, true);
reader.accept(checker, 0);
activator.log(Level.FINEST, "Woven class bytecode: \n" + stringWriter.toString());
}
}
}
}
}
| 9,668 |
0 | Create_ds/aries/spi-fly/spi-fly-itests/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-itests/src/main/java/org/apache/aries/spifly/itests/InitialTest.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.spifly.itests;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.namespace.HostNamespace;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.test.assertj.bundle.BundleAssert;
import org.osgi.test.common.annotation.InjectBundleContext;
import org.osgi.test.junit5.context.BundleContextExtension;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.aries.spifly.itests.util.TeeOutputStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(BundleContextExtension.class)
public class InitialTest {
static URI testBase;
static Path testBasePath;
static Path examplesBasePath;
@InjectBundleContext
BundleContext bundleContext;
private ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private PrintStream originalOut = System.out;
@BeforeAll
static void beforeAll(@InjectBundleContext BundleContext bundleContext) {
testBase = URI.create(bundleContext.getProperty("test.base"));
testBasePath = Paths.get(testBase);
examplesBasePath = testBasePath.getParent().resolve(
"spi-fly-examples"
);
}
@BeforeEach
public void beforeEachTest() {
System.setOut(new PrintStream(new TeeOutputStream(outContent, originalOut)));
}
@AfterEach
public void afterEachTest() {
System.setOut(originalOut);
}
@Test
public void example1() throws Exception {
assertBundleInstallation(getExampleJar("spi-fly-example-provider1-bundle"));
assertBundleInstallation(getExampleJar("spi-fly-example-client1-bundle"));
assertThat(
outContent.toString()
).contains(
"*** Result from invoking the SPI consume via library:",
"Doing it!"
).doesNotContain("Doing it too!", "Doing it as well!");
}
@Test
public void example2() throws Exception {
assertBundleInstallation(getExampleJar("spi-fly-example-provider2-bundle"));
assertBundleInstallation(getExampleJar("spi-fly-example-client2-bundle"));
assertThat(
outContent.toString()
).contains(
"*** Result from invoking the SPI directly:",
"Doing it too!"
).doesNotContain("Doing it!", "Doing it as well!");
}
@Test
public void example3() throws Exception {
Bundle provider3fragment = assertBundleInstallation(getExampleJar("spi-fly-example-provider3-fragment"), true);
Bundle provider3Bundle = assertBundleInstallation(getExampleJar("spi-fly-example-provider3-bundle"));
BundleAssert.assertThat(provider3fragment).isFragment().isInState(Bundle.RESOLVED);
assertFragmentAttached(provider3Bundle, provider3fragment);
Bundle client3fragment = assertBundleInstallation(getExampleJar("spi-fly-example-client3-fragment"), true);
Bundle client3Bundle = assertBundleInstallation(getExampleJar("spi-fly-example-client3-bundle"));
BundleAssert.assertThat(client3fragment).isFragment().isInState(Bundle.RESOLVED);
assertFragmentAttached(client3Bundle, client3fragment);
assertThat(
outContent.toString()
).contains(
"*** Result from invoking the SPI from untreated bundle:",
"Doing it as well!"
).doesNotContain("Doing it!", "Doing it too!");
}
@Test
public void example4() throws Exception {
assertBundleInstallation(getExampleJar("spi-fly-example-resource-provider-bundle"));
assertBundleInstallation(getExampleJar("spi-fly-example-resource-client-bundle"));
assertThat(
outContent.toString()
).contains(
"*** First line of content:",
"This is a test resource."
);
}
Bundle assertBundleInstallation(Path bundleJar) throws Exception {
return assertBundleInstallation(bundleJar, false);
}
Bundle assertBundleInstallation(Path bundleJar, boolean fragment) throws Exception {
assertThat(bundleJar).exists();
Bundle bundle = bundleContext.installBundle(
bundleJar.toString(),
bundleJar.toUri().toURL().openConnection().getInputStream());
BundleAssert.assertThat(bundle).isInState(Bundle.INSTALLED);
if (!fragment) {
bundle.start();
BundleAssert.assertThat(bundle).isInState(Bundle.ACTIVE);
}
return bundle;
}
void assertFragmentAttached(Bundle bundle, Bundle fragment) throws Exception {
BundleAssert.assertThat(
bundle.adapt(
BundleWiring.class
).getProvidedWires(
HostNamespace.HOST_NAMESPACE
).stream().map(
BundleWire::getRequirerWiring
).map(
BundleWiring::getBundle
).findFirst().orElseThrow(
() -> new Exception("Fragment did not attach")
)
).hasBundleId(
fragment.getBundleId()
);
}
Path getExampleJar(String mavenModuleName) throws IOException {
Path bundle1TargetDirPath = examplesBasePath.resolve(
mavenModuleName
).resolve(
"target"
);
assertThat(bundle1TargetDirPath).exists();
return Files.list(bundle1TargetDirPath).filter(
p -> {
String name = p.getFileName().toString();
return name.endsWith(".jar") && !name.endsWith("-javadoc.jar") && !name.endsWith("-sources.jar");
}
).findFirst().orElseThrow(
() -> new FileNotFoundException("Could not find jar for " + mavenModuleName)
);
}
}
| 9,669 |
0 | Create_ds/aries/spi-fly/spi-fly-itests/src/main/java/org/apache/aries/spifly/itests | Create_ds/aries/spi-fly/spi-fly-itests/src/main/java/org/apache/aries/spifly/itests/util/TeeOutputStream.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.spifly.itests.util;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class TeeOutputStream extends OutputStream {
final OutputStream[] out;
final Thread thread;
public TeeOutputStream(OutputStream... out) {
this(null, out);
}
public TeeOutputStream(Thread thread, OutputStream... out) {
this.thread = thread;
this.out = out;
}
@Override
public void write(int b) throws IOException {
if (thread == null || Thread.currentThread() == thread)
for (OutputStream o : out) {
o.write(b);
}
}
@Override
public void write(byte[] b) throws IOException {
if (thread == null || Thread.currentThread() == thread)
for (OutputStream o : out) {
o.write(b);
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (thread == null || Thread.currentThread() == thread)
for (OutputStream o : out) {
o.write(b, off, len);
}
}
public void close() throws IOException {
if (out == null)
return;
List<Throwable> exceptions = new ArrayList<>();
for (Object o : out) {
if (o instanceof AutoCloseable) {
close((AutoCloseable) o).ifPresent(exceptions::add);
} else if (o instanceof Iterable) {
for (Object oo : (Iterable<?>) o) {
if (oo instanceof AutoCloseable) {
// do not recurse!
close((AutoCloseable) oo).ifPresent(exceptions::add);
}
}
}
}
if (!exceptions.isEmpty()) {
IOException ioe = new IOException();
exceptions.stream().forEach(ioe::addSuppressed);
throw ioe;
}
}
private Optional<Throwable> close(AutoCloseable in) {
try {
if (in != null)
in.close();
} catch (Throwable e) {
return Optional.of(e);
}
return Optional.empty();
}
}
| 9,670 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool/ConsumerTest.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.spifly.statictool;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.apache.aries.spifly.SpiFlyConstants;
import org.apache.aries.spifly.Streams;
import org.apache.aries.spifly.statictool.bundle.Test2Class;
import org.apache.aries.spifly.statictool.bundle.Test3Class;
import org.apache.aries.spifly.statictool.bundle.TestClass;
import org.junit.Assert;
import org.junit.Test;
public class ConsumerTest {
@Test
public void testConsumerBundle() throws Exception {
String testClassFileName = TestClass.class.getName().replace('.', '/') + ".class";
URL testClassURL = getClass().getResource("/" + testClassFileName);
String test2ClassFileName = Test2Class.class.getName().replace('.', '/') + ".class";
URL test2ClassURL = getClass().getResource("/" + test2ClassFileName);
String test3ClassFileName = Test3Class.class.getName().replace('.', '/') + ".class";
URL test3ClassURL = getClass().getResource("/" + test3ClassFileName);
File jarFile = new File(System.getProperty("java.io.tmpdir") + "/testjar_" + System.currentTimeMillis() + ".jar");
File expectedFile = null;
try {
// Create the jarfile to be used for testing
Manifest mf = new Manifest();
Attributes mainAttributes = mf.getMainAttributes();
mainAttributes.putValue("Manifest-Version", "1.0");
mainAttributes.putValue("Bundle-ManifestVersion", "2.0");
mainAttributes.putValue("Bundle-SymbolicName", "testbundle");
mainAttributes.putValue("Foo", "Bar Bar");
mainAttributes.putValue(SpiFlyConstants.SPI_CONSUMER_HEADER, Test2Class.class.getName() + "#getTCCL()");
JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), mf);
jos.putNextEntry(new ZipEntry(testClassFileName));
Streams.pump(testClassURL.openStream(), jos);
jos.putNextEntry(new ZipEntry(test2ClassFileName));
Streams.pump(test2ClassURL.openStream(), jos);
jos.putNextEntry(new ZipEntry(test3ClassFileName));
Streams.pump(test3ClassURL.openStream(), jos);
jos.close();
Main.main(jarFile.getCanonicalPath());
expectedFile = new File(jarFile.getParent(), jarFile.getName().replaceAll("[.]jar", "_spifly.jar"));
Assert.assertTrue("A processed separate bundle should have been created", expectedFile.exists());
// Check manifest in generated bundle.
JarFile transformedJarFile = new JarFile(expectedFile);
Manifest expectedMF = transformedJarFile.getManifest();
Assert.assertEquals("1.0", expectedMF.getMainAttributes().getValue("Manifest-Version"));
Assert.assertEquals("2.0", expectedMF.getMainAttributes().getValue("Bundle-ManifestVersion"));
Assert.assertEquals("testbundle", expectedMF.getMainAttributes().getValue("Bundle-SymbolicName"));
Assert.assertEquals("Bar Bar", expectedMF.getMainAttributes().getValue("Foo"));
Assert.assertEquals("org.apache.aries.spifly;version=\"[1.1.0,1.2.0)\"", expectedMF.getMainAttributes().getValue("Import-Package"));
Assert.assertNull(expectedMF.getMainAttributes().get(SpiFlyConstants.SPI_CONSUMER_HEADER));
JarFile initialJarFile = new JarFile(jarFile);
byte[] orgBytes = Streams.suck(initialJarFile.getInputStream(new ZipEntry(testClassFileName)));
byte[] transBytes = Streams.suck(transformedJarFile.getInputStream(new ZipEntry(testClassFileName)));
Assert.assertFalse("The transformed class should be different", Arrays.equals(orgBytes, transBytes));
byte[] orgBytes2 = Streams.suck(initialJarFile.getInputStream(new ZipEntry(test2ClassFileName)));
byte[] nonTransBytes2 = Streams.suck(transformedJarFile.getInputStream(new ZipEntry(test2ClassFileName)));
Assert.assertArrayEquals(orgBytes2, nonTransBytes2);
byte[] orgBytes3 = Streams.suck(initialJarFile.getInputStream(new ZipEntry(test3ClassFileName)));
byte[] nonTransBytes3 = Streams.suck(transformedJarFile.getInputStream(new ZipEntry(test3ClassFileName)));
Assert.assertArrayEquals(orgBytes3, nonTransBytes3);
initialJarFile.close();
transformedJarFile.close();
} finally {
jarFile.delete();
if (expectedFile != null)
expectedFile.delete();
}
}
}
| 9,671 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool/MainTest.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.spifly.statictool;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.jar.Manifest;
import org.apache.aries.spifly.Streams;
import org.junit.Assert;
import org.junit.Test;
import org.junit.internal.ArrayComparisonFailure;
public class MainTest {
@Test
public void testUnJarReJar() throws Exception {
URL jarURL = getClass().getResource("/testjar.jar");
File jarFile = new File(jarURL.getFile());
File tempDir = new File(System.getProperty("java.io.tmpdir") + "/testjar_" + System.currentTimeMillis());
try {
Manifest manifest = Main.unJar(jarFile, tempDir);
assertStreams(new File(tempDir, "META-INF/MANIFEST.MF"),
"jar:" + jarURL + "!/META-INF/MANIFEST.MF");
assertStreams(new File(tempDir, "A text File with no content"),
"jar:" + jarURL + "!/A text File with no content");
assertStreams(new File(tempDir, "dir/Main.class"),
"jar:" + jarURL + "!/dir/Main.class");
assertStreams(new File(tempDir, "dir/dir 2/a.txt"),
"jar:" + jarURL + "!/dir/dir 2/a.txt");
assertStreams(new File(tempDir, "dir/dir 2/b.txt"),
"jar:" + jarURL + "!/dir/dir 2/b.txt");
Assert.assertTrue(new File(tempDir, "dir/dir.3").exists());
// Create a second jar from the exploded directory
File copiedFile = new File(jarFile.getAbsolutePath() + ".copy");
Main.jar(copiedFile, tempDir, manifest);
URL copyURL = copiedFile.toURI().toURL();
assertStreams("jar:" + copyURL + "!/META-INF/MANIFEST.MF",
"jar:" + jarURL + "!/META-INF/MANIFEST.MF");
assertStreams("jar:" + copyURL + "!/A text File with no content",
"jar:" + jarURL + "!/A text File with no content");
assertStreams("jar:" + copyURL + "!/dir/Main.class",
"jar:" + jarURL + "!/dir/Main.class");
assertStreams("jar:" + copyURL + "!/dir/dir 2/a.txt",
"jar:" + jarURL + "!/dir/dir 2/a.txt");
assertStreams("jar:" + copyURL + "!/dir/dir 2/b.txt",
"jar:" + jarURL + "!/dir/dir 2/b.txt");
} finally {
Main.delTree(tempDir);
}
}
@Test
public void testDelTree() throws IOException {
URL jarURL = getClass().getResource("/testjar.jar");
File jarFile = new File(jarURL.getFile());
File tempDir = new File(System.getProperty("java.io.tmpdir") + "/testjar_" + System.currentTimeMillis());
assertFalse("Precondition", tempDir.exists());
Main.unJar(jarFile, tempDir);
assertTrue(tempDir.exists());
Main.delTree(tempDir);
assertFalse(tempDir.exists());
}
private void assertStreams(String url1, String url2) throws Exception {
InputStream is1 = new URL(url1).openStream();
InputStream is2 = new URL(url2).openStream();
assertStreams(is1, is2);
}
private void assertStreams(File file, String url) throws Exception {
InputStream is1 = new FileInputStream(file);
InputStream is2 = new URL(url).openStream();
assertStreams(is1, is2);
}
private void assertStreams(InputStream is1, InputStream is2)
throws IOException, ArrayComparisonFailure {
try {
byte[] bytes1 = Streams.suck(is1);
byte[] bytes2 = Streams.suck(is2);
Assert.assertArrayEquals("Files not equal", bytes1, bytes2);
} finally {
is1.close();
is2.close();
}
}
}
| 9,672 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool/RequirementTest.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.spifly.statictool;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.apache.aries.spifly.SpiFlyConstants;
import org.apache.aries.spifly.Streams;
import org.apache.aries.spifly.statictool.bundle.Test2Class;
import org.apache.aries.spifly.statictool.bundle.Test3Class;
import org.apache.aries.spifly.statictool.bundle.TestClass;
import org.junit.Assert;
import org.junit.Test;
public class RequirementTest {
@Test
public void testConsumerBundle() throws Exception {
String testClassFileName = TestClass.class.getName().replace('.', '/') + ".class";
URL testClassURL = getClass().getResource("/" + testClassFileName);
String test2ClassFileName = Test2Class.class.getName().replace('.', '/') + ".class";
URL test2ClassURL = getClass().getResource("/" + test2ClassFileName);
String test3ClassFileName = Test3Class.class.getName().replace('.', '/') + ".class";
URL test3ClassURL = getClass().getResource("/" + test3ClassFileName);
File jarFile = new File(System.getProperty("java.io.tmpdir") + "/testjar_" + System.currentTimeMillis() + ".jar");
File expectedFile = null;
try {
// Create the jarfile to be used for testing
Manifest mf = new Manifest();
Attributes mainAttributes = mf.getMainAttributes();
mainAttributes.putValue("Manifest-Version", "1.0");
mainAttributes.putValue("Bundle-ManifestVersion", "2.0");
mainAttributes.putValue("Bundle-SymbolicName", "testbundle");
mainAttributes.putValue("Foo", "Bar Bar");
mainAttributes.putValue("Import-Package", "org.foo.bar");
mainAttributes.putValue(SpiFlyConstants.REQUIRE_CAPABILITY,
"osgi.serviceloader; filter:=\"(osgi.serviceloader=org.apache.aries.spifly.mysvc.SPIProvider)\";cardinality:=multiple, " +
"osgi.extender; filter:=\"(osgi.extender=osgi.serviceloader.processor)\"");
JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), mf);
jos.putNextEntry(new ZipEntry(testClassFileName));
Streams.pump(testClassURL.openStream(), jos);
jos.putNextEntry(new ZipEntry(test2ClassFileName));
Streams.pump(test2ClassURL.openStream(), jos);
jos.putNextEntry(new ZipEntry(test3ClassFileName));
Streams.pump(test3ClassURL.openStream(), jos);
jos.close();
Main.main(jarFile.getCanonicalPath());
expectedFile = new File(jarFile.getParent(), jarFile.getName().replaceAll("[.]jar", "_spifly.jar"));
Assert.assertTrue("A processed separate bundle should have been created", expectedFile.exists());
// Check manifest in generated bundle.
JarFile transformedJarFile = new JarFile(expectedFile);
Manifest actualMF = transformedJarFile.getManifest();
Assert.assertEquals("1.0", actualMF.getMainAttributes().getValue("Manifest-Version"));
Assert.assertEquals("2.0", actualMF.getMainAttributes().getValue("Bundle-ManifestVersion"));
Assert.assertEquals("testbundle", actualMF.getMainAttributes().getValue("Bundle-SymbolicName"));
Assert.assertEquals("Bar Bar", actualMF.getMainAttributes().getValue("Foo"));
Assert.assertEquals("osgi.serviceloader; filter:=\"(osgi.serviceloader=org.apache.aries.spifly.mysvc.SPIProvider)\";cardinality:=multiple",
actualMF.getMainAttributes().getValue(SpiFlyConstants.REQUIRE_CAPABILITY));
Assert.assertNull("Should not generate this header when processing Require-Capability",
actualMF.getMainAttributes().getValue(SpiFlyConstants.PROCESSED_SPI_CONSUMER_HEADER));
String importPackage = actualMF.getMainAttributes().getValue("Import-Package");
Assert.assertTrue(
importPackage,
"org.foo.bar,org.apache.aries.spifly;version=\"[1.1.0,1.2.0)\"".equals(importPackage) ||
"org.apache.aries.spifly;version=\"[1.1.0,1.2.0)\",org.foo.bar".equals(importPackage));
JarFile initialJarFile = new JarFile(jarFile);
byte[] orgBytes = Streams.suck(initialJarFile.getInputStream(new ZipEntry(testClassFileName)));
byte[] nonTransBytes = Streams.suck(transformedJarFile.getInputStream(new ZipEntry(testClassFileName)));
Assert.assertArrayEquals(orgBytes, nonTransBytes);
byte[] orgBytes2 = Streams.suck(initialJarFile.getInputStream(new ZipEntry(test2ClassFileName)));
byte[] nonTransBytes2 = Streams.suck(transformedJarFile.getInputStream(new ZipEntry(test2ClassFileName)));
Assert.assertArrayEquals(orgBytes2, nonTransBytes2);
byte[] orgBytes3 = Streams.suck(initialJarFile.getInputStream(new ZipEntry(test3ClassFileName)));
byte[] transBytes3 = Streams.suck(transformedJarFile.getInputStream(new ZipEntry(test3ClassFileName)));
Assert.assertFalse("The transformed class should be different", Arrays.equals(orgBytes3, transBytes3));
initialJarFile.close();
transformedJarFile.close();
} finally {
jarFile.delete();
if (expectedFile != null)
expectedFile.delete();
}
}
}
| 9,673 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool/bundle/TestClass.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.spifly.statictool.bundle;
public class TestClass {
public void doit() {
Test2Class.getTCCL();
}
}
| 9,674 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool/bundle/Test2Class.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.spifly.statictool.bundle;
public class Test2Class {
public static ClassLoader getTCCL() {
return Thread.currentThread().getContextClassLoader();
}
}
| 9,675 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool | Create_ds/aries/spi-fly/spi-fly-static-tool/src/test/java/org/apache/aries/spifly/statictool/bundle/Test3Class.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.spifly.statictool.bundle;
import java.util.ServiceLoader;
public class Test3Class {
public void doitToo() {
ServiceLoader<String> sl = ServiceLoader.load(String.class);
for (String s : sl) {
System.out.println("***: " + s);
}
}
}
| 9,676 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/StaticToolClassWriter.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.spifly.statictool;
import org.objectweb.asm.ClassWriter;
/**
* We need to override ASM's default behaviour in
* {@link #getCommonSuperClass(String, String)} so that it accepts a custom
* classloader that can also see the jar that is being processed.
*/
public final class StaticToolClassWriter extends ClassWriter {
private static final String OBJECT_INTERNAL_NAME = "java/lang/Object";
private final ClassLoader loader;
public StaticToolClassWriter(int flags, ClassLoader loader) {
super(flags);
this.loader = loader;
}
/**
* The implementation uses the classloader provided using the Constructor.
*
* This is a slight variation on ASM's default behaviour as that obtains the
* classloader to use ASMs classloader.
*/
@Override
protected String getCommonSuperClass(final String type1, final String type2) {
Class<?> c, d;
try {
c = Class.forName(type1.replace('/', '.'), false, loader);
d = Class.forName(type2.replace('/', '.'), false, loader);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (c.isAssignableFrom(d)) {
return type1;
}
if (d.isAssignableFrom(c)) {
return type2;
}
if (c.isInterface() || d.isInterface()) {
return OBJECT_INTERNAL_NAME;
}
do {
c = c.getSuperclass();
} while (!c.isAssignableFrom(d));
return c.getName().replace('.', '/');
}
}
| 9,677 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/DirTree.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.spifly.statictool;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class DirTree {
List<File> fileList = new ArrayList<File>();
public DirTree(File f) {
String[] names = f.list();
if (names == null) {
fileList.add(f);
return;
}
for (String name : names) {
File curFile = new File(f, name);
if (curFile.isDirectory()) {
fileList.addAll(new DirTree(curFile).getFiles());
} else {
fileList.add(curFile);
}
}
fileList.add(f);
}
public List<File> getFiles() {
return fileList;
}
}
| 9,678 |
0 | Create_ds/aries/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.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.spifly.statictool;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.spifly.ConsumerHeaderProcessor;
import org.apache.aries.spifly.SpiFlyConstants;
import org.apache.aries.spifly.Streams;
import org.apache.aries.spifly.Util;
import org.apache.aries.spifly.WeavingData;
import org.apache.aries.spifly.weaver.TCCLSetterVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
public class Main {
private static final String MODIFIED_BUNDLE_SUFFIX = "_spifly.jar";
private static final String IMPORT_PACKAGE = "Import-Package";
public static void usage() {
System.err.println("This tool processes OSGi Bundles that use java.util.ServiceLoader.load() to");
System.err.println("obtain implementations via META-INF/services. The byte code in the bundles is");
System.err.println("modified so that the ThreadContextClassLoader is set appropriately for the ");
System.err.println("duration of the java.util.ServiceLoader.load() call.");
System.err.println("To opt-in to this process, bundles need to have the following MANIFEST.MF");
System.err.println("header set:");
System.err.println(" " + SpiFlyConstants.SPI_CONSUMER_HEADER + ": *");
System.err.println("Modified bundles are written out under the following name:");
System.err.println(" <original-bundle-name>" + MODIFIED_BUNDLE_SUFFIX);
System.err.println();
System.err.println("Usage: java " + Main.class.getName() + " bundle1.jar bundle2.jar ...");
System.exit(-1);
}
public static void main(String ... args) throws Exception {
if (args.length < 1)
usage();
for (String arg : args) {
weaveJar(arg);
}
}
private static void weaveJar(String jarPath) throws Exception {
System.out.println("[SPI Fly Static Tool] Processing: " + jarPath);
File jarFile = new File(jarPath);
File tempDir = new File(System.getProperty("java.io.tmpdir") + File.separator + jarFile.getName() + "_" + System.currentTimeMillis());
Manifest manifest = unJar(jarFile, tempDir);
String consumerHeaderVal = manifest.getMainAttributes().getValue(SpiFlyConstants.SPI_CONSUMER_HEADER);
String consumerHeaderKey = null;
if (consumerHeaderVal != null) {
consumerHeaderKey = SpiFlyConstants.SPI_CONSUMER_HEADER;
} else {
consumerHeaderVal = manifest.getMainAttributes().getValue(SpiFlyConstants.REQUIRE_CAPABILITY);
if (consumerHeaderVal != null) {
consumerHeaderKey = SpiFlyConstants.REQUIRE_CAPABILITY;
}
}
if (consumerHeaderVal != null) {
String bcp = manifest.getMainAttributes().getValue(Constants.BUNDLE_CLASSPATH);
weaveDir(tempDir, consumerHeaderKey, consumerHeaderVal, bcp);
if (SpiFlyConstants.SPI_CONSUMER_HEADER.equals(consumerHeaderKey)) {
manifest.getMainAttributes().remove(new Attributes.Name(SpiFlyConstants.SPI_CONSUMER_HEADER));
manifest.getMainAttributes().putValue(SpiFlyConstants.PROCESSED_SPI_CONSUMER_HEADER, consumerHeaderVal);
} else {
// It's SpiFlyConstants.REQUIRE_CAPABILITY
// Take out the processor requirement, this probably needs to be improved a little bit
String newConsumerHeaderVal = consumerHeaderVal.replaceAll(
"osgi[.]extender;\\s*filter[:][=][\"]?[(]osgi[.]extender[=]osgi[.]serviceloader[.]processor[)][\"]?", "").
trim();
if (newConsumerHeaderVal.startsWith(","))
newConsumerHeaderVal = newConsumerHeaderVal.substring(1);
if (newConsumerHeaderVal.endsWith(","))
newConsumerHeaderVal = newConsumerHeaderVal.substring(0, newConsumerHeaderVal.length()-1);
manifest.getMainAttributes().putValue(SpiFlyConstants.REQUIRE_CAPABILITY, newConsumerHeaderVal);
manifest.getMainAttributes().putValue("X-SpiFly-Processed-Require-Capability", consumerHeaderVal);
}
// TODO if new packages needed then...
extendImportPackage(manifest);
File newJar = getNewJarFile(jarFile);
jar(newJar, tempDir, manifest);
} else {
System.out.println("[SPI Fly Static Tool] This file is not marked as an SPI Consumer.");
}
delTree(tempDir);
}
private static void extendImportPackage(Manifest manifest) throws IOException {
String utilPkgVersion = getPackageVersion(Util.class);
Version osgiVersion = Version.parseVersion(utilPkgVersion);
Version minVersion = new Version(osgiVersion.getMajor(), osgiVersion.getMinor(), osgiVersion.getMicro());
Version maxVersion = new Version(osgiVersion.getMajor(), osgiVersion.getMinor() + 1, 0);
String ip = manifest.getMainAttributes().getValue(IMPORT_PACKAGE);
if (ip == null)
ip = "";
StringBuilder sb = new StringBuilder(ip);
if (ip.length() > 0)
sb.append(",");
sb.append(Util.class.getPackage().getName());
sb.append(";version=\"[");
sb.append(minVersion);
sb.append(",");
sb.append(maxVersion);
sb.append(")\"");
manifest.getMainAttributes().putValue(IMPORT_PACKAGE, sb.toString());
}
private static String getPackageVersion(Class<?> clazz) throws IOException {
URL url = clazz.getResource("packageinfo");
if (url == null) {
throw new RuntimeException("'packageinfo' file with version information not found for package: "
+ clazz.getPackage().getName());
}
byte[] bytes = Streams.suck(url.openStream());
Properties p = new Properties();
p.load(new ByteArrayInputStream(bytes));
return p.getProperty("version");
}
private static File getNewJarFile(File jarFile) {
String s = jarFile.getAbsolutePath();
int idx = s.lastIndexOf('.');
s = s.substring(0, idx);
s += MODIFIED_BUNDLE_SUFFIX;
return new File(s);
}
private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception {
Set<WeavingData> wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue);
URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader());
String dirName = dir.getAbsolutePath();
DirTree dt = new DirTree(dir);
for (File f : dt.getFiles()) {
if (!f.getName().endsWith(".class"))
continue;
String className = f.getAbsolutePath().substring(dirName.length());
if (className.startsWith(File.separator))
className = className.substring(1);
className = className.substring(0, className.length() - ".class".length());
className = className.replace(File.separator, ".");
InputStream is = new FileInputStream(f);
byte[] b;
try {
ClassReader cr = new ClassReader(is);
ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl);
TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd);
cr.accept(cv, ClassReader.SKIP_FRAMES);
if (cv.isWoven()) {
b = cw.toByteArray();
} else {
// if not woven, store the original bytes
b = Streams.suck(new FileInputStream(f));
}
} finally {
is.close();
}
OutputStream os = new FileOutputStream(f);
try {
os.write(b);
} finally {
os.close();
}
}
if (bundleClassPath != null) {
for (String entry : bundleClassPath.split(",")) {
File jarFile = new File(dir, entry.trim());
if (jarFile.isFile()) {
weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue);
}
}
}
}
private static void weaveBCPJar(File jarFile, String consumerHeaderKey, String consumerHeaderVal) throws Exception {
File tempDir = new File(System.getProperty("java.io.tmpdir") + File.separator + jarFile.getName() + "_" + System.currentTimeMillis());
try {
Manifest manifest = unJar(jarFile, tempDir);
weaveDir(tempDir, consumerHeaderKey, consumerHeaderVal, null);
if (!jarFile.delete()) {
throw new IOException("Could not replace file: " + jarFile);
}
jar(jarFile, tempDir, manifest);
} finally {
delTree(tempDir);
}
}
static Manifest unJar(File jarFile, File tempDir) throws IOException {
ensureDirectory(tempDir);
JarInputStream jis = new JarInputStream(new FileInputStream(jarFile));
JarEntry je = null;
while((je = jis.getNextJarEntry()) != null) {
File outFile = new File(tempDir, je.getName());
String canonicalizedTargetDir = tempDir.getCanonicalPath();
if (!canonicalizedTargetDir.endsWith(File.separator)) {
canonicalizedTargetDir += File.separator;
}
if (!outFile.getCanonicalPath().startsWith(canonicalizedTargetDir)) {
throw new IOException("The output file is not contained in the destination directory");
}
if (je.isDirectory()) {
ensureDirectory(outFile);
continue;
}
File outDir = outFile.getParentFile();
ensureDirectory(outDir);
OutputStream out = new FileOutputStream(outFile);
try {
Streams.pump(jis, out);
} finally {
out.flush();
out.close();
jis.closeEntry();
}
outFile.setLastModified(je.getTime());
}
Manifest manifest = jis.getManifest();
if (manifest != null) {
File mf = new File(tempDir, "META-INF/MANIFEST.MF");
File mfDir = mf.getParentFile();
ensureDirectory(mfDir);
OutputStream out = new FileOutputStream(mf);
try {
manifest.write(out);
} finally {
out.flush();
out.close();
}
}
jis.close();
return manifest;
}
static void jar(File jarFile, File rootFile, Manifest manifest) throws IOException {
JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), manifest);
try {
addToJarRecursively(jos, rootFile.getAbsoluteFile(), rootFile.getAbsolutePath());
} finally {
jos.close();
}
}
static void addToJarRecursively(JarOutputStream jar, File source, String rootDirectory) throws IOException {
String sourceName = source.getAbsolutePath().replace("\\", "/");
sourceName = sourceName.substring(rootDirectory.length());
if (sourceName.startsWith("/")) {
sourceName = sourceName.substring(1);
}
if ("META-INF/MANIFEST.MF".equals(sourceName))
return;
if (source.isDirectory()) {
/* Is there any point in adding a directory beyond just taking up space?
if (!sourceName.isEmpty()) {
if (!sourceName.endsWith("/")) {
sourceName += "/";
}
JarEntry entry = new JarEntry(sourceName);
jar.putNextEntry(entry);
jar.closeEntry();
}
*/
for (File nested : source.listFiles()) {
addToJarRecursively(jar, nested, rootDirectory);
}
return;
}
JarEntry entry = new JarEntry(sourceName);
jar.putNextEntry(entry);
InputStream is = new FileInputStream(source);
try {
Streams.pump(is, jar);
} finally {
jar.closeEntry();
is.close();
}
}
static void delTree(File tempDir) throws IOException {
for (File f : new DirTree(tempDir).getFiles()) {
if (!f.delete())
throw new IOException("Problem deleting file: " + tempDir.getAbsolutePath());
}
}
private static void ensureDirectory(File outDir) throws IOException {
if (!outDir.isDirectory())
if (!outDir.mkdirs())
throw new IOException("Unable to create directory " + outDir.getAbsolutePath());
}
}
| 9,679 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-provider1-jar/src/main/java/org/apache/aries/spifly/mysvc | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-provider1-jar/src/main/java/org/apache/aries/spifly/mysvc/impl/SPIProviderImpl.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.spifly.mysvc.impl;
import org.apache.aries.spifly.mysvc.SPIProvider;
public class SPIProviderImpl extends SPIProvider {
@Override
public String doit() {
return "Doing it!";
}
}
| 9,680 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-provider3-bundle/src/main/java/org/apache/aries/spifly/mysvc | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-provider3-bundle/src/main/java/org/apache/aries/spifly/mysvc/impl3/SPIProviderImpl.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.spifly.mysvc.impl3;
import org.apache.aries.spifly.mysvc.SPIProvider;
public class SPIProviderImpl extends SPIProvider {
@Override
public String doit() {
return "Doing it as well!";
}
}
| 9,681 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-spi-bundle/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-spi-bundle/src/main/java/org/apache/aries/spifly/mysvc/SPIProvider.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.spifly.mysvc;
public abstract class SPIProvider {
public abstract String doit();
}
| 9,682 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-resource-client-bundle/src/main/java/org/apache/aries/spifly/example/resource | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-resource-client-bundle/src/main/java/org/apache/aries/spifly/example/resource/client/Foo.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.spifly.example.resource.client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
class Foo {
static void doit() throws Exception {
System.out.println("*** About to invoke getThreadContextClassLoader().getResource()");
URL r = Thread.currentThread().getContextClassLoader().getResource("/org/apache/aries/spifly/test/blah.txt");
System.out.println("*** Found resource: " + r);
System.out.println("*** First line of content: " + new BufferedReader(new InputStreamReader(r.openStream())).readLine());
}
}
| 9,683 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-resource-client-bundle/src/main/java/org/apache/aries/spifly/example/resource | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-resource-client-bundle/src/main/java/org/apache/aries/spifly/example/resource/client/Activator.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.spifly.example.resource.client;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
Foo.doit();
}
@Override
public void stop(BundleContext context) throws Exception {
}
}
| 9,684 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-client3-bundle/src/main/java/org/apache/aries/spifly/examples/client3 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-client3-bundle/src/main/java/org/apache/aries/spifly/examples/client3/impl/Activator.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.spifly.examples.client3.impl;
import java.util.ServiceLoader;
import org.apache.aries.spifly.mysvc.SPIProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
System.out.println("*** Result from invoking the SPI from untreated bundle: ");
ServiceLoader<SPIProvider> ldr = ServiceLoader.load(SPIProvider.class);
for (SPIProvider spiObject : ldr) {
System.out.println(spiObject.doit()); // invoke the SPI object
}
}
@Override
public void stop(BundleContext context) throws Exception {
}
}
| 9,685 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-client1-bundle/src/main/java/org/apache/aries/spifly/client | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-client1-bundle/src/main/java/org/apache/aries/spifly/client/bundle/Activator.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.spifly.client.bundle;
import org.apache.aries.spifly.client.jar.Consumer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
Consumer consumer = new Consumer();
System.out.println("*** Result from invoking the SPI consume via library: " + consumer.callSPI());
}
public void stop(BundleContext context) throws Exception {
}
}
| 9,686 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-provider2-bundle/src/main/java/org/apache/aries/spifly/mysvc | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-provider2-bundle/src/main/java/org/apache/aries/spifly/mysvc/impl2/SPIProviderImpl.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.spifly.mysvc.impl2;
import org.apache.aries.spifly.mysvc.SPIProvider;
public class SPIProviderImpl extends SPIProvider {
@Override
public String doit() {
return "Doing it too!";
}
}
| 9,687 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-client2-bundle/src/main/java/org/apache/aries/spifly/examples/client2 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-client2-bundle/src/main/java/org/apache/aries/spifly/examples/client2/impl/Activator.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.spifly.examples.client2.impl;
import java.util.ServiceLoader;
import org.apache.aries.spifly.mysvc.SPIProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
System.out.println("*** Result from invoking the SPI directly: ");
ServiceLoader<SPIProvider> ldr = ServiceLoader.load(SPIProvider.class);
for (SPIProvider spiObject : ldr) {
System.out.println(spiObject.doit()); // invoke the SPI object
}
}
@Override
public void stop(BundleContext context) throws Exception {
}
}
| 9,688 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-client1-jar/src/main/java/org/apache/aries/spifly/client | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-client1-jar/src/main/java/org/apache/aries/spifly/client/jar/Consumer.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.spifly.client.jar;
import java.util.ServiceLoader;
import org.apache.aries.spifly.mysvc.SPIProvider;
public class Consumer {
public String callSPI() {
StringBuilder sb = new StringBuilder();
ServiceLoader<SPIProvider> ldr = ServiceLoader.load(SPIProvider.class);
for (SPIProvider spiObject : ldr) {
sb.append(spiObject.doit()); // invoke the SPI object
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
}
| 9,689 |
0 | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-provider-consumer-bundle/src/main/java/org/apache/aries/spifly/pc | Create_ds/aries/spi-fly/spi-fly-examples/spi-fly-example-provider-consumer-bundle/src/main/java/org/apache/aries/spifly/pc/bundle/Activator.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.spifly.pc.bundle;
import org.apache.aries.spifly.client.jar.Consumer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
/** The activator invokes the SPI Consumer, which is also provided by this bundle. It does so
* asynchronously to give the SPI-Fly extender a chance to register the provider, which is done
* asynchronously as well.
*/
public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("*** Asynchronous invocation to let the extender do its work.");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// ignore
}
Consumer consumer = new Consumer();
System.out.println("*** Result from invoking the SPI consumer via library: " + consumer.callSPI());
}
});
t.start();
}
@Override
public void stop(BundleContext context) throws Exception {
}
}
| 9,690 |
0 | Create_ds/aries/spi-fly/spi-fly-static-bundle/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-static-bundle/src/main/java/org/apache/aries/spifly/staticbundle/StaticWeavingActivator.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.spifly.staticbundle;
import org.apache.aries.spifly.BaseActivator;
import org.apache.aries.spifly.SpiFlyConstants;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class StaticWeavingActivator extends BaseActivator implements BundleActivator {
@Override
public synchronized void start(BundleContext context) throws Exception {
super.start(context, SpiFlyConstants.PROCESSED_SPI_CONSUMER_HEADER);
}
@Override
public synchronized void stop(BundleContext context) throws Exception {
super.stop(context);
}
}
| 9,691 |
0 | Create_ds/aries/spi-fly/spi-fly-weaver/src/main/java/org/apache/aries/spifly | Create_ds/aries/spi-fly/spi-fly-weaver/src/main/java/org/apache/aries/spifly/weaver/TCCLSetterVisitor.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.spifly.weaver;
import java.util.Arrays;
import java.util.HashSet;
import java.util.ServiceLoader;
import java.util.Set;
import org.apache.aries.spifly.Util;
import org.apache.aries.spifly.WeavingData;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.JSRInlinerAdapter;
import org.objectweb.asm.commons.Method;
import aQute.bnd.annotation.baseline.BaselineIgnore;
/**
* This class implements an ASM ClassVisitor which puts the appropriate ThreadContextClassloader
* calls around applicable method invocations. It does the actual bytecode weaving.
*/
@BaselineIgnore("1.3.0")
public class TCCLSetterVisitor extends ClassVisitor implements Opcodes {
private static final Type CLASSLOADER_TYPE = Type.getType(ClassLoader.class);
private static final String GENERATED_METHOD_NAME = "$$FCCL$$";
private static final Type UTIL_CLASS = Type.getType(Util.class);
private static final Type CLASS_TYPE = Type.getType(Class.class);
private static final Type String_TYPE = Type.getType(String.class);
private static final Type SERVICELOADER_TYPE = Type.getType(ServiceLoader.class);
private final Type targetClass;
private final Set<WeavingData> weavingData;
// Set to true when the weaving code has changed the client such that an additional import
// (to the Util.class.getPackage()) is needed.
private boolean additionalImportRequired = false;
// This field is true when the class was woven
private boolean woven = false;
public TCCLSetterVisitor(ClassVisitor cv, String className, Set<WeavingData> weavingData) {
super(Opcodes.ASM9, cv);
this.targetClass = Type.getType("L" + className.replace('.', '/') + ";");
this.weavingData = weavingData;
}
public boolean isWoven() {
return woven;
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
mv = new TCCLSetterMethodVisitor(mv, access, name, desc);
mv = new JSRInlinerAdapter(mv, access, name, desc, signature, exceptions);
return mv;
}
@Override
public void visitEnd() {
if (!woven) {
// if this class wasn't woven, then don't add the synthesized method either.
super.visitEnd();
return;
}
// Add generated static method
Set<String> methodNames = new HashSet<String>();
for (WeavingData wd : weavingData) {
String methodName = getGeneratedMethodName(wd);
if (methodNames.contains(methodName))
continue;
methodNames.add(methodName);
if (ServiceLoader.class.getName().equals(wd.getClassName())) {
continue;
}
/* Equivalent to:
* private static void $$FCCL$$<className>$<methodName>(Class<?> cls) {
* Util.fixContextClassLoader("java.util.ServiceLoader", "load", cls, WovenClass.class.getClassLoader());
* }
*/
Method method = new Method(methodName, Type.VOID_TYPE, new Type[] {CLASS_TYPE});
GeneratorAdapter mv = new GeneratorAdapter(cv.visitMethod(ACC_PRIVATE + ACC_STATIC, methodName,
method.getDescriptor(), null, null), ACC_PRIVATE + ACC_STATIC, methodName,
method.getDescriptor());
//Load the strings, method parameter and target
mv.visitLdcInsn(wd.getClassName());
mv.visitLdcInsn(wd.getMethodName());
mv.loadArg(0);
mv.visitLdcInsn(targetClass);
//Change the class on the stack into a classloader
mv.invokeVirtual(CLASS_TYPE, new Method("getClassLoader",
CLASSLOADER_TYPE, new Type[0]));
//Call our util method
mv.invokeStatic(UTIL_CLASS, new Method("fixContextClassloader", Type.VOID_TYPE,
new Type[] {String_TYPE, String_TYPE, CLASS_TYPE, CLASSLOADER_TYPE}));
mv.returnValue();
mv.endMethod();
}
super.visitEnd();
}
private String getGeneratedMethodName(WeavingData wd) {
StringBuilder name = new StringBuilder(GENERATED_METHOD_NAME);
name.append(wd.getClassName().replace('.', '#'));
name.append("$");
name.append(wd.getMethodName());
if (wd.getArgClasses() != null) {
for (String cls : wd.getArgClasses()) {
name.append("$");
name.append(cls.replace('.', '#'));
}
}
return name.toString();
}
private class TCCLSetterMethodVisitor extends GeneratorAdapter {
Type lastLDCType;
private int lastOpcode;
private int lastVar;
public TCCLSetterMethodVisitor(MethodVisitor mv, int access, String name, String descriptor) {
super(Opcodes.ASM7, mv, access, name, descriptor);
}
/**
* Store the last LDC call. When ServiceLoader.load(Class cls) is called
* with a class constant (XXX.class) as parameter, the last LDC call
* before the ServiceLoader.load() visitMethodInsn call
* contains the class being passed in. We need to pass this class to
* $$FCCL$$ as well so we can copy the value found in here.
*/
@Override
public void visitLdcInsn(Object cst) {
if (cst instanceof Type) {
lastLDCType = ((Type) cst);
}
super.visitLdcInsn(cst);
}
/**
* Store the last ALOAD call. When ServiceLoader.load(Class cls) is called
* with using a variable as parameter, the last ALOAD call
* before the ServiceLoader.load() visitMethodInsn call
* contains the class being passed in. Annihilate any previously
* found LDC, because it had nothing to do with the call to
* ServiceLoader.load(Class cls) if it is followed by an ALOAD
* (before the actual call).
*/
@Override
public void visitVarInsn(int opcode, int var) {
lastLDCType = null;
this.lastOpcode = opcode;
this.lastVar = var;
super.visitVarInsn(opcode, var);
}
/**
* Wrap selected method calls with
* Util.storeContextClassloader();
* $$FCCL$$(<class>)
* Util.restoreContextClassloader();
*/
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
if (opcode != INVOKESTATIC) {
super.visitMethodInsn(opcode, owner, name, desc, itf);
return;
}
WeavingData wd = findWeavingData(owner, name, desc);
if (wd == null) {
super.visitMethodInsn(opcode, owner, name, desc, itf);
return;
}
additionalImportRequired = true;
woven = true;
// ServiceLoader.load(Class, ClassLoader)
if (ServiceLoader.class.getName().equals(wd.getClassName()) &&
"load".equals(wd.getMethodName()) &&
Arrays.equals(new String [] {Class.class.getName(), ClassLoader.class.getName()}, wd.getArgClasses())) {
visitLdcInsn(targetClass);
invokeStatic(UTIL_CLASS, new Method("serviceLoaderLoad",
SERVICELOADER_TYPE, new Type[] {CLASS_TYPE, CLASSLOADER_TYPE, CLASS_TYPE}));
return;
}
// ServiceLoader.load(Class)
if (ServiceLoader.class.getName().equals(wd.getClassName()) &&
"load".equals(wd.getMethodName())) {
visitLdcInsn(targetClass);
invokeStatic(UTIL_CLASS, new Method("serviceLoaderLoad",
SERVICELOADER_TYPE, new Type[] {CLASS_TYPE, CLASS_TYPE}));
return;
}
// Add: MyClass.$$FCCL$$<classname>$<methodname>(<class>);
Label startTry = newLabel();
Label endTry = newLabel();
//start try block
visitTryCatchBlock(startTry, endTry, endTry, null);
mark(startTry);
// Add: Util.storeContextClassloader();
invokeStatic(UTIL_CLASS, new Method("storeContextClassloader", Type.VOID_TYPE, new Type[0]));
// Add: MyClass.$$FCCL$$<classname>$<methodname>(<class>);
// In any other case, we're not dealing with a general-purpose service loader, but rather
// with a specific one, such as DocumentBuilderFactory.newInstance(). In that case the
// target class is the class that is being invoked on (i.e. DocumentBuilderFactory).
Type type = Type.getObjectType(owner);
mv.visitLdcInsn(type);
invokeStatic(targetClass, new Method(getGeneratedMethodName(wd),
Type.VOID_TYPE, new Type[] {CLASS_TYPE}));
//Call the original instruction
super.visitMethodInsn(opcode, owner, name, desc, itf);
//If no exception then go to the finally (finally blocks are a catch block with a jump)
Label afterCatch = newLabel();
goTo(afterCatch);
//start the catch
mark(endTry);
//Run the restore method then throw on the exception
invokeStatic(UTIL_CLASS, new Method("restoreContextClassloader", Type.VOID_TYPE, new Type[0]));
throwException();
//start the finally
mark(afterCatch);
//Run the restore and continue
invokeStatic(UTIL_CLASS, new Method("restoreContextClassloader", Type.VOID_TYPE, new Type[0]));
}
private WeavingData findWeavingData(String owner, String methodName, String methodDesc) {
owner = owner.replace('/', '.');
Type[] argTypes = Type.getArgumentTypes(methodDesc);
String [] argClassNames = new String[argTypes.length];
for (int i = 0; i < argTypes.length; i++) {
argClassNames[i] = argTypes[i].getClassName();
}
for (WeavingData wd : weavingData) {
if (wd.getClassName().equals(owner) &&
wd.getMethodName().equals(methodName) &&
(wd.getArgClasses() != null ? Arrays.equals(argClassNames, wd.getArgClasses()) : true)) {
return wd;
}
}
return null;
}
}
public boolean additionalImportRequired() {
return additionalImportRequired ;
}
}
| 9,692 |
0 | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries/mytest/MySPI2.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.mytest;
public interface MySPI2 {
String someMethod(String s);
}
| 9,693 |
0 | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries/mytest/MySPI.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.mytest;
public interface MySPI {
String someMethod(String s);
}
| 9,694 |
0 | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries/spifly/MySPIImpl.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.spifly;
import org.apache.aries.mytest.MySPI;
public class MySPIImpl implements MySPI {
@Override
public String someMethod(String s) {
return "a" + s + "z";
}
}
| 9,695 |
0 | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries/spifly/JaxpClient.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.spifly;
import javax.xml.parsers.DocumentBuilderFactory;
public class JaxpClient {
public Class<?> test() {
return DocumentBuilderFactory.newInstance().getClass();
}
}
| 9,696 |
0 | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries/spifly/ProviderBundleTrackerCustomizerTest.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.spifly;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import org.easymock.EasyMock;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
public class ProviderBundleTrackerCustomizerTest {
private BaseActivator activator = new BaseActivator() {
@Override
public void start(BundleContext context) throws Exception {}
};
@Test
public void testAddingRemovedBundle() throws Exception {
Bundle mediatorBundle = EasyMock.createMock(Bundle.class);
EasyMock.expect(mediatorBundle.getBundleId()).andReturn(42l).anyTimes();
EasyMock.replay(mediatorBundle);
ProviderBundleTrackerCustomizer customizer = new ProviderBundleTrackerCustomizer(activator, mediatorBundle);
ServiceRegistration sreg = EasyMock.createMock(ServiceRegistration.class);
sreg.unregister();
EasyMock.expectLastCall();
EasyMock.replay(sreg);
BundleContext implBC = mockSPIBundleContext(sreg);
Bundle implBundle = mockSPIBundle(implBC);
assertEquals("Precondition", 0, activator.findProviderBundles("org.apache.aries.mytest.MySPI").size());
// Call addingBundle();
List<ServiceRegistration> registrations = customizer.addingBundle(implBundle, null);
Collection<Bundle> bundles = activator.findProviderBundles("org.apache.aries.mytest.MySPI");
assertEquals(1, bundles.size());
assertSame(implBundle, bundles.iterator().next());
// The bc.registerService() call should now have been made
EasyMock.verify(implBC);
// Call removedBundle();
customizer.removedBundle(implBundle, null, registrations);
// sreg.unregister() should have been called.
EasyMock.verify(sreg);
}
@Test
public void testAddingBundleSPIBundle() throws Exception {
BundleContext implBC = mockSPIBundleContext(EasyMock.createNiceMock(ServiceRegistration.class));
Bundle spiBundle = mockSPIBundle(implBC);
ProviderBundleTrackerCustomizer customizer = new ProviderBundleTrackerCustomizer(activator, spiBundle);
assertNull("The SpiFly bundle itself should be ignored", customizer.addingBundle(spiBundle, null));
}
@Test
public void testAddingNonOptInBundle() throws Exception {
BundleContext implBC = mockSPIBundleContext(EasyMock.createNiceMock(ServiceRegistration.class));
Bundle implBundle = mockSPIBundle(implBC, null);
ProviderBundleTrackerCustomizer customizer = new ProviderBundleTrackerCustomizer(activator, null);
assertNull("Bundle doesn't opt-in so should be ignored", customizer.addingBundle(implBundle, null));
}
@Test
@SuppressWarnings("unchecked")
public void testAddingBundleWithBundleClassPath() throws Exception {
Bundle mediatorBundle = EasyMock.createMock(Bundle.class);
EasyMock.expect(mediatorBundle.getBundleId()).andReturn(42l).anyTimes();
EasyMock.replay(mediatorBundle);
ProviderBundleTrackerCustomizer customizer = new ProviderBundleTrackerCustomizer(activator, mediatorBundle);
BundleContext implBC = EasyMock.createMock(BundleContext.class);
EasyMock.<Object>expect(implBC.registerService(
EasyMock.eq("org.apache.aries.mytest.MySPI"),
EasyMock.isA(ServiceFactory.class),
(Dictionary<String,?>) EasyMock.anyObject())).andReturn(EasyMock.createNiceMock(ServiceRegistration.class)).times(3);
EasyMock.replay(implBC);
Bundle implBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(implBundle.getBundleContext()).andReturn(implBC).anyTimes();
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(SpiFlyConstants.SPI_PROVIDER_HEADER, "*");
headers.put(Constants.BUNDLE_CLASSPATH, ".,non-jar.jar,embedded.jar,embedded2.jar");
EasyMock.expect(implBundle.getHeaders()).andReturn(headers).anyTimes();
URL embeddedJar = getClass().getResource("/embedded.jar");
assertNotNull("precondition", embeddedJar);
EasyMock.expect(implBundle.getResource("embedded.jar")).andReturn(embeddedJar).anyTimes();
URL embedded2Jar = getClass().getResource("/embedded2.jar");
assertNotNull("precondition", embedded2Jar);
EasyMock.expect(implBundle.getResource("embedded2.jar")).andReturn(embedded2Jar).anyTimes();
URL dir = new URL("jar:" + embeddedJar + "!/META-INF/services");
assertNotNull("precondition", dir);
EasyMock.expect(implBundle.getResource("/META-INF/services")).andReturn(dir).anyTimes();
EasyMock.expect(implBundle.findEntries((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), EasyMock.anyBoolean())).
andReturn(null).anyTimes();
ClassLoader cl = new URLClassLoader(new URL [] {embeddedJar}, getClass().getClassLoader());
Class<?> clsA = cl.loadClass("org.apache.aries.spifly.impl2.MySPIImpl2a");
EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl2.MySPIImpl2a")).andReturn(clsA).anyTimes();
Class<?> clsB = cl.loadClass("org.apache.aries.spifly.impl2.MySPIImpl2b");
EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl2.MySPIImpl2b")).andReturn(clsB).anyTimes();
ClassLoader cl2 = new URLClassLoader(new URL [] {embedded2Jar}, getClass().getClassLoader());
Class<?> clsC = cl2.loadClass("org.apache.aries.spifly.impl3.MySPIImpl3");
EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl3.MySPIImpl3")).andReturn(clsC).anyTimes();
EasyMock.replay(implBundle);
assertEquals("Precondition", 0, activator.findProviderBundles("org.apache.aries.mytest.MySPI").size());
// Call addingBundle();
List<ServiceRegistration> registrations = customizer.addingBundle(implBundle, null);
Collection<Bundle> bundles = activator.findProviderBundles("org.apache.aries.mytest.MySPI");
assertEquals(1, bundles.size());
assertSame(implBundle, bundles.iterator().next());
// The bc.registerService() call should now have been made
EasyMock.verify(implBC);
}
@Test
public void testMultipleProviderServices() throws Exception {
BundleContext implBC = mockSPIBundleContext(EasyMock.createNiceMock(ServiceRegistration.class));
Bundle implBundle = mockMultiSPIBundle(implBC);
Bundle spiBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(spiBundle.getBundleId()).andReturn(25l).anyTimes();
EasyMock.replay(spiBundle);
ProviderBundleTrackerCustomizer customizer = new ProviderBundleTrackerCustomizer(activator, spiBundle);
assertEquals(2, customizer.addingBundle(implBundle, null).size());
}
@SuppressWarnings("unchecked")
private BundleContext mockSPIBundleContext(ServiceRegistration sreg) {
BundleContext implBC = EasyMock.createMock(BundleContext.class);
EasyMock.<Object>expect(implBC.registerService(
EasyMock.anyString(),
EasyMock.isA(ServiceFactory.class),
(Dictionary<String,?>) EasyMock.anyObject())).andReturn(sreg).anyTimes();
EasyMock.replay(implBC);
return implBC;
}
private Bundle mockSPIBundle(BundleContext implBC) throws ClassNotFoundException {
return mockSPIBundle(implBC, "*");
}
private Bundle mockSPIBundle(BundleContext implBC, String spiProviderHeader) throws ClassNotFoundException {
Bundle implBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(implBundle.getBundleContext()).andReturn(implBC).anyTimes();
Dictionary<String, String> headers = new Hashtable<String, String>();
if (spiProviderHeader != null)
headers.put(SpiFlyConstants.SPI_PROVIDER_HEADER, spiProviderHeader);
EasyMock.expect(implBundle.getHeaders()).andReturn(headers).anyTimes();
// List the resources found at META-INF/services in the test bundle
URL dir = getClass().getResource("impl1/META-INF/services");
assertNotNull("precondition", dir);
EasyMock.expect(implBundle.getResource("/META-INF/services")).andReturn(dir).anyTimes();
URL res = getClass().getResource("impl1/META-INF/services/org.apache.aries.mytest.MySPI");
assertNotNull("precondition", res);
EasyMock.expect(implBundle.findEntries("META-INF/services", "*", false)).andReturn(
Collections.enumeration(Collections.singleton(res))).anyTimes();
Class<?> cls = getClass().getClassLoader().loadClass("org.apache.aries.spifly.impl1.MySPIImpl1");
EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl1.MySPIImpl1")).andReturn(cls).anyTimes();
EasyMock.replay(implBundle);
return implBundle;
}
private Bundle mockMultiSPIBundle(BundleContext implBC) throws ClassNotFoundException {
Bundle implBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(implBundle.getBundleContext()).andReturn(implBC).anyTimes();
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(
Constants.REQUIRE_CAPABILITY,
"osgi.extender;filter:='(osgi.extender=osgi.serviceloader.registrar)'"
);
headers.put(
Constants.PROVIDE_CAPABILITY,
"osgi.serviceloader;osgi.serviceloader='org.apache.aries.mytest.MySPI2';register:='org.apache.aries.spifly.impl4.MySPIImpl4b';foo='bbb'," +
"osgi.serviceloader;osgi.serviceloader='org.apache.aries.mytest.MySPI2';register:='org.apache.aries.spifly.impl4.MySPIImpl4c';foo='ccc'"
);
EasyMock.expect(implBundle.getHeaders()).andReturn(headers).anyTimes();
// List the resources found at META-INF/services in the test bundle
URL dir = getClass().getResource("impl4/META-INF/services");
assertNotNull("precondition", dir);
EasyMock.expect(implBundle.getResource("/META-INF/services")).andReturn(dir).anyTimes();
URL resA = getClass().getResource("impl4/META-INF/services/org.apache.aries.mytest.MySPI");
assertNotNull("precondition", resA);
URL resB = getClass().getResource("impl4/META-INF/services/org.apache.aries.mytest.MySPI2");
assertNotNull("precondition", resB);
EasyMock.expect(implBundle.findEntries("META-INF/services", "*", false)).andReturn(
Collections.enumeration(Arrays.asList(resA, resB))).anyTimes();
Class<?> cls = getClass().getClassLoader().loadClass("org.apache.aries.spifly.impl4.MySPIImpl4b");
EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl4.MySPIImpl4b")).andReturn(cls).anyTimes();
cls = getClass().getClassLoader().loadClass("org.apache.aries.spifly.impl4.MySPIImpl4c");
EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl4.MySPIImpl4c")).andReturn(cls).anyTimes();
EasyMock.replay(implBundle);
return implBundle;
}
}
| 9,697 |
0 | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries/spifly/UtilTest.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.spifly;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.ServiceLoader;
import org.apache.aries.mytest.MySPI;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Constants;
public class UtilTest {
private ClassLoader storedTCCL;
@Before
public void setup() {
storedTCCL = Thread.currentThread().getContextClassLoader();
}
@After
public void tearDown() {
Thread.currentThread().setContextClassLoader(storedTCCL);
storedTCCL = null;
}
@Test
public void testSetRestoreTCCL() {
ClassLoader cl = new URLClassLoader(new URL[] {});
Thread.currentThread().setContextClassLoader(cl);
Util.storeContextClassloader();
Thread.currentThread().setContextClassLoader(null);
Util.restoreContextClassloader();
assertSame(cl, Thread.currentThread().getContextClassLoader());
}
@Test
public void testFixContextClassLoaderSimpleViaEmbeddedJar() throws Exception {
BaseActivator activator = new BaseActivator() {
public void start(BundleContext context) throws Exception {
}
};
BaseActivator.activator = activator;
URL url = getClass().getResource("/embedded3.jar");
assertNotNull("precondition", url);
Bundle providerBundle = EasyMock.createMock(Bundle.class);
final ClassLoader providerCL = new TestBundleClassLoader(new URL [] {url}, getClass().getClassLoader(), providerBundle);
EasyMock.expect(providerBundle.getBundleContext()).andThrow(new IllegalStateException("Disable getBundleClassLoaderViaAdapt"));
EasyMock.expect(providerBundle.getBundleId()).andReturn(42L).anyTimes();
EasyMock.expect(providerBundle.getEntryPaths((String) EasyMock.anyObject())).andReturn(null).anyTimes();
Dictionary<String, String> providerHeaders = new Hashtable<String, String>();
providerHeaders.put(Constants.BUNDLE_CLASSPATH, ".,embedded3.jar");
EasyMock.expect(providerBundle.getHeaders()).andReturn(providerHeaders).anyTimes();
EasyMock.expect(providerBundle.getResource("embedded3.jar")).andReturn(url).anyTimes();
providerBundle.loadClass((String) EasyMock.anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Class<?>>() {
@Override
public Class<?> answer() throws Throwable {
return providerCL.loadClass((String) EasyMock.getCurrentArguments()[0]);
}
}).anyTimes();
EasyMock.replay(providerBundle);
activator.registerProviderBundle(MySPI.class.getName(), providerBundle, new HashMap<String, Object>());
Bundle clientBundle = EasyMock.createMock(Bundle.class);
EasyMock.replay(clientBundle);
ClassLoader clientCL = new TestBundleClassLoader(new URL [] {}, getClass().getClassLoader(), clientBundle);
Thread.currentThread().setContextClassLoader(null);
Util.fixContextClassloader(ServiceLoader.class.getName(), "load", MySPI.class, clientCL);
assertSame(providerCL, Thread.currentThread().getContextClassLoader());
}
@Test
public void testNotInitialized() throws Exception {
BaseActivator.activator = null;
URL url = getClass().getResource("/embedded3.jar");
assertNotNull("precondition", url);
Bundle providerBundle = EasyMock.createMock(Bundle.class);
final ClassLoader providerCL = new TestBundleClassLoader(new URL [] {url}, getClass().getClassLoader(), providerBundle);
EasyMock.expect(providerBundle.getBundleId()).andReturn(42L).anyTimes();
EasyMock.expect(providerBundle.getEntryPaths((String) EasyMock.anyObject())).andReturn(null).anyTimes();
Dictionary<String, String> providerHeaders = new Hashtable<String, String>();
providerHeaders.put(Constants.BUNDLE_CLASSPATH, ".,embedded3.jar");
EasyMock.expect(providerBundle.getHeaders()).andReturn(providerHeaders).anyTimes();
EasyMock.expect(providerBundle.getResource("embedded3.jar")).andReturn(url).anyTimes();
providerBundle.loadClass((String) EasyMock.anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Class<?>>() {
@Override
public Class<?> answer() throws Throwable {
return providerCL.loadClass((String) EasyMock.getCurrentArguments()[0]);
}
}).anyTimes();
EasyMock.replay(providerBundle);
Bundle clientBundle = EasyMock.createMock(Bundle.class);
EasyMock.replay(clientBundle);
ClassLoader clientCL = new TestBundleClassLoader(new URL [] {}, getClass().getClassLoader(), clientBundle);
Thread.currentThread().setContextClassLoader(null);
Util.fixContextClassloader(ServiceLoader.class.getName(), "load", MySPI.class, clientCL);
assertSame("The system is not yet initialized, so the TCCL should not be set",
null, Thread.currentThread().getContextClassLoader());
}
private static class TestBundleClassLoader extends URLClassLoader implements BundleReference {
private final Bundle bundle;
public TestBundleClassLoader(URL[] urls, ClassLoader parent, Bundle bundle) {
super(urls, parent);
this.bundle = bundle;
}
@Override
public Bundle getBundle() {
return bundle;
}
}
}
| 9,698 |
0 | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries | Create_ds/aries/spi-fly/spi-fly-core/src/test/java/org/apache/aries/spifly/HeaderParserTest.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.spifly;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Test;
public class HeaderParserTest extends TestCase {
@Test
public void testMethodWithMultipleParameters() {
String header = "javax.ws.rs.client.FactoryFinder#find(java.lang.String," +
"java.lang.String),javax.ws.rs.ext.FactoryFinder#find(java.lang.String,java" +
".lang.String) ,javax.ws.rs.other.FactoryFinder#find(java.lang.String,java" +
".lang.String)";
List<HeaderParser.PathElement> pathElements = HeaderParser.parseHeader(header);
assertEquals(3, pathElements.size());
assertEquals(pathElements.get(0).getName(), "javax.ws.rs.client.FactoryFinder#find(java.lang.String,java.lang.String)");
assertEquals(pathElements.get(1).getName(), "javax.ws.rs.ext.FactoryFinder#find(java.lang.String,java.lang.String)");
assertEquals(pathElements.get(2).getName(), "javax.ws.rs.other.FactoryFinder#find(java.lang.String,java.lang.String)");
}
} | 9,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.