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-core/src/test/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/ParserTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.IOException;
import javax.xml.validation.Schema;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.apache.aries.blueprint.reflect.BeanMetadataImpl;
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.Metadata;
import org.osgi.service.blueprint.reflect.NullMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
import org.xml.sax.SAXException;
/**
* TODO: constructor injection
* TODO: Dependency#setMethod
*/
public class ParserTest extends AbstractBlueprintTest {
public void test() {
Integer[] oo = new Integer[1];
Object[] ii = oo;
}
public void testParseComponent() throws Exception {
ComponentDefinitionRegistry registry = parse("/test-simple-component.xml");
assertNotNull(registry);
ComponentMetadata component = registry.getComponentDefinition("pojoA");
assertNotNull(component);
assertEquals("pojoA", component.getId());
assertTrue(component instanceof BeanMetadata);
BeanMetadata local = (BeanMetadata) component;
List<String> deps = local.getDependsOn();
assertNotNull(deps);
assertEquals(2, deps.size());
assertTrue(deps.contains("pojoB"));
assertTrue(deps.contains("pojoC"));
assertEquals("org.apache.aries.blueprint.pojos.PojoA", local.getClassName());
List<BeanArgument> params = local.getArguments();
assertNotNull(params);
assertEquals(6, params.size());
BeanArgument param = params.get(0);
assertNotNull(param);
assertEquals(-1, param.getIndex());
assertNull(param.getValueType());
assertNotNull(param.getValue());
assertTrue(param.getValue() instanceof ValueMetadata);
assertEquals("val0", ((ValueMetadata) param.getValue()).getStringValue());
assertNull(((ValueMetadata) param.getValue()).getType());
param = params.get(1);
assertNotNull(param);
assertEquals(-1, param.getIndex());
assertNull(param.getValueType());
assertNotNull(param.getValue());
assertTrue(param.getValue() instanceof RefMetadata);
assertEquals("val1", ((RefMetadata) param.getValue()).getComponentId());
param = params.get(2);
assertNotNull(param);
assertEquals(-1, param.getIndex());
assertNull(param.getValueType());
assertNotNull(param.getValue());
assertTrue(param.getValue() instanceof NullMetadata);
param = params.get(3);
assertNotNull(param);
assertEquals(-1, param.getIndex());
assertEquals("java.lang.String", param.getValueType());
assertNotNull(param.getValue());
assertTrue(param.getValue() instanceof ValueMetadata);
assertEquals("val3", ((ValueMetadata) param.getValue()).getStringValue());
assertNull(((ValueMetadata) param.getValue()).getType());
param = params.get(4);
assertNotNull(param);
assertEquals(-1, param.getIndex());
assertNull(param.getValueType());
assertNotNull(param.getValue());
assertTrue(param.getValue() instanceof CollectionMetadata);
CollectionMetadata array = (CollectionMetadata) param.getValue();
assertNull(array.getValueType());
assertNotNull(array.getValues());
assertEquals(3, array.getValues().size());
assertTrue(array.getValues().get(0) instanceof ValueMetadata);
assertTrue(array.getValues().get(1) instanceof ComponentMetadata);
assertTrue(array.getValues().get(2) instanceof NullMetadata);
param = params.get(5);
assertNotNull(param);
assertEquals(-1, param.getIndex());
assertNull(param.getValueType());
assertNotNull(param.getValue());
assertTrue(param.getValue() instanceof RefMetadata);
assertEquals("pojoB", ((RefMetadata) param.getValue()).getComponentId());
assertEquals(null, local.getInitMethod());
assertEquals(null, local.getDestroyMethod());
// test pojoB
ComponentMetadata pojoB = registry.getComponentDefinition("pojoB");
assertNotNull(pojoB);
assertEquals("pojoB", pojoB.getId());
assertTrue(pojoB instanceof BeanMetadata);
BeanMetadata pojoBLocal = (BeanMetadata) pojoB;
assertEquals("initPojo", pojoBLocal.getInitMethod());
// assertEquals("", pojoBLocal.getDestroyMethod());
params = pojoBLocal.getArguments();
assertNotNull(params);
assertEquals(2, params.size());
param = params.get(0);
assertNotNull(param);
assertEquals(1, param.getIndex());
param = params.get(1);
assertNotNull(param);
assertEquals(0, param.getIndex());
}
public void testParse() throws Exception {
parse("/test.xml");
}
public void testCustomNodes() throws Exception {
ComponentDefinitionRegistry registry = parse("/test-custom-nodes.xml", new TestNamespaceHandlerSet());
ComponentMetadata metadata;
metadata = registry.getComponentDefinition("fooService");
assertNotNull(metadata);
assertTrue(metadata instanceof MyLocalComponentMetadata);
MyLocalComponentMetadata comp1 = (MyLocalComponentMetadata) metadata;
assertEquals(true, comp1.getCacheReturnValues());
assertEquals("getVolatile", comp1.getOperation());
metadata = registry.getComponentDefinition("barService");
assertNotNull(metadata);
assertTrue(metadata instanceof BeanMetadata);
BeanMetadata comp2 = (BeanMetadata) metadata;
assertEquals(1, comp2.getProperties().size());
BeanProperty propertyMetadata = comp2.getProperties().get(0);
assertEquals("localCache", propertyMetadata.getName());
Metadata propertyValue = propertyMetadata.getValue();
assertTrue(propertyValue instanceof BeanMetadata);
BeanMetadata innerComp = (BeanMetadata) propertyValue;
assertEquals("org.apache.aries.CacheProperty", innerComp.getClassName());
metadata = registry.getComponentDefinition("myCache");
assertNotNull(metadata);
assertTrue(metadata instanceof BeanMetadata);
BeanMetadata comp3 = (BeanMetadata) metadata;
assertEquals("org.apache.aries.Cache", comp3.getClassName());
}
public void testScopes() throws Exception {
ComponentDefinitionRegistry registry = parse("/test-scopes.xml", new TestNamespaceHandlerSet());
ComponentMetadata metadata = registry.getComponentDefinition("fooService");
assertNotNull(metadata);
assertTrue(metadata instanceof BeanMetadata);
BeanMetadata bm = (BeanMetadata) metadata;
assertNull(bm.getScope());
metadata = registry.getComponentDefinition("barService");
assertNotNull(metadata);
assertTrue(metadata instanceof BeanMetadata);
bm = (BeanMetadata) metadata;
assertEquals("prototype", bm.getScope());
metadata = registry.getComponentDefinition("bazService");
assertNotNull(metadata);
assertTrue(metadata instanceof BeanMetadata);
bm = (BeanMetadata) metadata;
assertEquals("singleton", bm.getScope());
metadata = registry.getComponentDefinition("booService");
assertNotNull(metadata);
assertTrue(metadata instanceof BeanMetadata);
bm = (BeanMetadata) metadata;
assertEquals("{http://test.org}boo", bm.getScope());
}
private static class TestNamespaceHandlerSet implements NamespaceHandlerSet {
private static final URI CACHE = URI.create("http://cache.org");
private static final URI TEST = URI.create("http://test.org");
private TestNamespaceHandlerSet() {
}
public Set<URI> getNamespaces() {
Set<URI> namespaces = new HashSet<URI>();
namespaces.add(CACHE);
namespaces.add(TEST);
return namespaces;
}
public boolean isComplete() {
return true;
}
public NamespaceHandler getNamespaceHandler(URI namespace) {
if (CACHE.equals(namespace)) {
return new TestNamespaceHandler();
} else if (TEST.equals(namespace)) {
return new ScopeNamespaceHandler();
} else {
return null;
}
}
public Schema getSchema() throws SAXException, IOException {
return null;
}
public Schema getSchema(Map<String, String> locations) throws SAXException, IOException {
return null;
}
public void addListener(NamespaceHandlerSet.Listener listener) {
}
public void removeListener(NamespaceHandlerSet.Listener listener) {
}
public void destroy() {
}
}
private static class ScopeNamespaceHandler implements NamespaceHandler {
public URL getSchemaLocation(String namespace) {
// TODO Auto-generated method stub
return null;
}
public Set<Class> getManagedClasses() {
// TODO Auto-generated method stub
return null;
}
public Metadata parse(Element element, ParserContext context) {
// TODO Auto-generated method stub
return null;
}
public ComponentMetadata decorate(Node node,
ComponentMetadata component, ParserContext context) {
return component;
}
}
private static class TestNamespaceHandler implements NamespaceHandler {
public URL getSchemaLocation(String namespace) {
return getClass().getResource("/cache.xsd");
}
public Set<Class> getManagedClasses() {
return new HashSet<Class>();
}
public ComponentMetadata decorate(Node node,
ComponentMetadata component,
ParserContext context) {
//System.out.println("decorate: " + node + " " + component + " " + container.getEnclosingComponent().getId());
if (node instanceof Attr) {
Attr attr = (Attr) node;
MyLocalComponentMetadata decoratedComp = new MyLocalComponentMetadata((BeanMetadata)component);
decoratedComp.setCacheReturnValues(Boolean.parseBoolean(attr.getValue()));
return decoratedComp;
} else if (node instanceof Element) {
Element element = (Element) node;
MyLocalComponentMetadata decoratedComp = (MyLocalComponentMetadata) component;
decoratedComp.setOperation(element.getAttribute("name"));
return decoratedComp;
} else {
throw new RuntimeException("Unhandled node: " + node);
}
}
public Metadata parse(Element element, ParserContext context) {
String comp = (context.getEnclosingComponent() == null) ? null : context.getEnclosingComponent().getId();
//System.out.println("parse: " + element.getLocalName() + " " + comp);
String className;
if (context.getEnclosingComponent() == null) {
className = "org.apache.aries.Cache";
} else {
className = "org.apache.aries.CacheProperty";
}
BeanMetadataImpl p = new BeanMetadataImpl();
p.setId(element.getAttribute("id"));
p.setClassName(className);
return p;
}
}
private static class MyLocalComponentMetadata extends BeanMetadataImpl {
private boolean cacheReturnValues;
private String operation;
public MyLocalComponentMetadata(BeanMetadata impl) {
super(impl);
}
public boolean getCacheReturnValues() {
return cacheReturnValues;
}
public void setCacheReturnValues(boolean value) {
cacheReturnValues = value;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getOperation() {
return this.operation;
}
}
}
| 9,400 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/NonStandardSettersTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.di.Repository;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.pojos.NonStandardSetter;
import org.junit.Test;
public class NonStandardSettersTest extends AbstractBlueprintTest {
@Test
public void testNonStandardSetters() throws Exception {
ComponentDefinitionRegistryImpl registry = parse("/test-non-standard-setters.xml");
Repository repository = new TestBlueprintContainer(registry).getRepository();
NonStandardSetter nss = (NonStandardSetter) repository.create("nss");
assertNotNull(nss);
assertEquals("value", nss.a());
}
}
| 9,401 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/ExtPlaceholderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.di.Repository;
import org.apache.aries.blueprint.ext.impl.ExtNamespaceHandler;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.pojos.BeanD;
import org.junit.Test;
public class ExtPlaceholderTest extends AbstractBlueprintTest {
@Test
public void testStaticValues() throws Exception {
ComponentDefinitionRegistryImpl registry = parse("/test-staticvalues.xml");
Repository repository = new TestBlueprintContainer(registry).getRepository();
Object obj1 = repository.create("beanD");
assertNotNull(obj1);
assertTrue(obj1 instanceof BeanD);
BeanD beanD = (BeanD) obj1;
assertEquals(ExtNamespaceHandler.BLUEPRINT_EXT_NAMESPACE_V1_5, beanD.getName());
}
}
| 9,402 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/NullProxyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.SatisfiableRecipe;
import org.apache.aries.blueprint.di.Repository;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.pojos.PojoC;
import org.apache.aries.blueprint.pojos.Service;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.proxy.impl.JdkProxyManager;
public class NullProxyTest extends AbstractBlueprintTest {
public void testNullProxy() throws Exception {
ComponentDefinitionRegistryImpl registry = parse("/test-null-proxy.xml");
ProxyManager proxyManager = new JdkProxyManager();
Repository repository = new TestBlueprintContainer(registry, proxyManager).getRepository();
((SatisfiableRecipe) repository.getRecipe("refDefNullProxy")).start(new SatisfiableRecipe.SatisfactionListener() {
@Override
public void notifySatisfaction(SatisfiableRecipe satisfiable) {
}
});
PojoC pojoC = (PojoC) repository.create("pojoC");
assertTrue(pojoC.getService() instanceof Service);
assertEquals(0, pojoC.getService().getInt());
assertNull(pojoC.getService().getPojoA());
}
static class ProxyGenerationException extends RuntimeException {
}
}
| 9,403 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/TestBlueprintContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.List;
import org.apache.aries.blueprint.container.BlueprintContainerImpl;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.proxy.impl.JdkProxyManager;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Target;
public class TestBlueprintContainer extends BlueprintContainerImpl {
public TestBlueprintContainer(ComponentDefinitionRegistryImpl registry) throws Exception {
this(registry, new JdkProxyManager());
}
public TestBlueprintContainer(ComponentDefinitionRegistryImpl registry, ProxyManager proxyManager) throws Exception {
super(null, new TestBundleContext(), null, null, null, null, null, null, proxyManager, null);
resetComponentDefinitionRegistry();
if (registry == null) {
return;
}
List<Target> converters = registry.getTypeConverters();
for (Target converter : converters) {
getComponentDefinitionRegistry().registerTypeConverter(converter);
}
for (String name : registry.getComponentDefinitionNames()) {
ComponentMetadata comp = registry.getComponentDefinition(name);
if (!converters.contains(comp)) {
getComponentDefinitionRegistry().registerComponentDefinition(comp);
for (Interceptor interceptor : registry.getInterceptors(comp)) {
getComponentDefinitionRegistry().registerInterceptorWithComponent(comp, interceptor);
}
}
}
processTypeConverters();
processProcessors();
}
@Override
public Class loadClass(String name) throws ClassNotFoundException {
return Thread.currentThread().getContextClassLoader().loadClass(name);
}
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
}
| 9,404 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/BeanLoadingTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.di.Repository;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.pojos.SimpleBean;
public class BeanLoadingTest extends AbstractBlueprintTest {
public void testLoadSimpleBean() throws Exception {
ComponentDefinitionRegistryImpl registry = parse("/test-bean-classes.xml");
Repository repository = new TestBlueprintContainer(registry)
.getRepository();
Object obj = repository.create("simpleBean");
assertNotNull(obj);
assertTrue(obj instanceof SimpleBean);
}
public void testLoadSimpleBeanNested() throws Exception {
ComponentDefinitionRegistryImpl registry = parse("/test-bean-classes.xml");
Repository repository = new TestBlueprintContainer(registry)
.getRepository();
Object obj = repository.create("simpleBeanNested");
assertNotNull(obj);
assertTrue(obj instanceof SimpleBean.Nested);
}
}
| 9,405 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/AbstractBlueprintTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import javax.xml.validation.Schema;
import junit.framework.TestCase;
import org.apache.aries.blueprint.ext.impl.ExtNamespaceHandler;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.parser.Parser;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.xml.sax.SAXException;
public abstract class AbstractBlueprintTest extends TestCase {
protected ComponentDefinitionRegistryImpl parse(String name) throws Exception {
NamespaceHandlerSet handlers = new NamespaceHandlerSet() {
public Set<URI> getNamespaces() {
return null;
}
public NamespaceHandler getNamespaceHandler(URI namespace) {
if (ExtNamespaceHandler.isExtNamespace(namespace.toString())) {
return new ExtNamespaceHandler();
} else {
return null;
}
}
public void removeListener(NamespaceHandlerSet.Listener listener) {
}
public Schema getSchema() throws SAXException, IOException {
return null;
}
public Schema getSchema(Map<String, String> locations) throws SAXException, IOException {
return null;
}
public boolean isComplete() {
return false;
}
public void addListener(NamespaceHandlerSet.Listener listener) {
}
public void destroy() {
}
};
return parse(name, handlers);
}
protected ComponentDefinitionRegistryImpl parse(String name, NamespaceHandlerSet handlers) throws Exception {
ComponentDefinitionRegistryImpl registry = new ComponentDefinitionRegistryImpl();
Parser parser = new Parser();
parser.parse(Collections.singletonList(getClass().getResource(name)));
parser.populate(handlers, registry);
return registry;
}
}
| 9,406 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/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 static org.junit.Assert.assertNotNull;
import java.lang.reflect.Method;
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 PropertyPlaceholderExt {
private final Map<String,String> values = new HashMap<String,String>();
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 testAries1858() throws Exception {
Method method = AbstractPropertyPlaceholder.class.getDeclaredMethod("retrieveValue", String.class);
method.setAccessible(true);
assertNotNull(method);
PropertyPlaceholderExt pp = new PropertyPlaceholderExt();
Map<String, Object> defaults = new HashMap<String, Object>();
defaults.put("property.1", "value.1");
defaults.put("property.2", 42L);
pp.setDefaultProperties(defaults);
String v = (String) method.invoke(pp, "property.1");
assertEquals("value.1", v);
try {
// Camel without CAMEL-12570 casts to string. If old Camel is used with new blueprint-core
v = (String) method.invoke(pp, "property.2");
} catch (ClassCastException expected) {
}
// Camel without CAMEL-12570 calls getDefaultProperties() via PropertyPlaceholder
Map<String, Object> map = ((PropertyPlaceholder) pp).getDefaultProperties();
assertEquals(42L, map.get("property.2"));
}
// @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 String 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,407 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/intercept/BeanA.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.intercept;
public class BeanA implements BeanItf {
public String hello(String msg) {
return "Hello " + msg + " !";
}
}
| 9,408 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/intercept/BeanItf.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.intercept;
public interface BeanItf {
String hello(String msg);
}
| 9,409 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/intercept/TheProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.intercept;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.reflect.BeanMetadata;
public class TheProcessor implements BeanProcessor {
private BlueprintContainer blueprintContainer;
public BlueprintContainer getBlueprintContainer() {
return blueprintContainer;
}
public void setBlueprintContainer(BlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
@Override
public Object beforeInit(Object bean, String beanName, BeanCreator beanCreator, BeanMetadata beanData) {
if (bean.getClass() == BeanA.class) {
((ExtendedBlueprintContainer) blueprintContainer)
.getComponentDefinitionRegistry()
.registerInterceptorWithComponent(beanData, new TheInterceptor());
}
return bean;
}
@Override
public Object afterInit(Object o, String s, BeanCreator beanCreator, BeanMetadata beanMetadata) {
return o;
}
@Override
public void beforeDestroy(Object o, String s) {
}
@Override
public void afterDestroy(Object o, String s) {
}
}
| 9,410 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/intercept/BeanB.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.intercept;
public class BeanB {
BeanItf a;
public BeanItf getA() {
return a;
}
public void setA(BeanItf a) {
this.a = a;
}
}
| 9,411 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/intercept/TheInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.intercept;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.aries.blueprint.Interceptor;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
public class TheInterceptor implements Interceptor {
public static final AtomicInteger calls = new AtomicInteger();
@Override
public Object preCall(ComponentMetadata componentMetadata, Method method, Object... objects) throws Throwable {
calls.incrementAndGet();
return null;
}
@Override
public void postCallWithReturn(ComponentMetadata componentMetadata, Method method, Object o, Object o1) throws Throwable {
}
@Override
public void postCallWithException(ComponentMetadata componentMetadata, Method method, Throwable throwable, Object o) throws Throwable {
}
@Override
public int getRank() {
return 0;
}
}
| 9,412 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/utils/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.blueprint.utils;
import java.util.List;
import junit.framework.TestCase;
import org.apache.aries.blueprint.utils.HeaderParser.PathElement;
public class HeaderParserTest extends TestCase {
public void testSimple() throws Exception {
List<PathElement> paths = HeaderParser.parseHeader("/foo.xml, /foo/bar.xml");
assertEquals(2, paths.size());
assertEquals("/foo.xml", paths.get(0).getName());
assertEquals(0, paths.get(0).getAttributes().size());
assertEquals(0, paths.get(0).getDirectives().size());
assertEquals("/foo/bar.xml", paths.get(1).getName());
assertEquals(0, paths.get(1).getAttributes().size());
assertEquals(0, paths.get(1).getDirectives().size());
}
public void testComplex() throws Exception {
List<PathElement> paths = HeaderParser.parseHeader("OSGI-INF/blueprint/comp1_named.xml;ignored-directive:=true,OSGI-INF/blueprint/comp2_named.xml;some-other-attribute=1");
assertEquals(2, paths.size());
assertEquals("OSGI-INF/blueprint/comp1_named.xml", paths.get(0).getName());
assertEquals(0, paths.get(0).getAttributes().size());
assertEquals(1, paths.get(0).getDirectives().size());
assertEquals("true", paths.get(0).getDirective("ignored-directive"));
assertEquals("OSGI-INF/blueprint/comp2_named.xml", paths.get(1).getName());
assertEquals(1, paths.get(1).getAttributes().size());
assertEquals("1", paths.get(1).getAttribute("some-other-attribute"));
assertEquals(0, paths.get(1).getDirectives().size());
}
public void testPaths() throws Exception {
List<PathElement> paths = HeaderParser.parseHeader("OSGI-INF/blueprint/comp1_named.xml;ignored-directive:=true,OSGI-INF/blueprint/comp2_named.xml;foo.xml;a=b;1:=2;c:=d;4=5");
assertEquals(3, paths.size());
assertEquals("OSGI-INF/blueprint/comp1_named.xml", paths.get(0).getName());
assertEquals(0, paths.get(0).getAttributes().size());
assertEquals(1, paths.get(0).getDirectives().size());
assertEquals("true", paths.get(0).getDirective("ignored-directive"));
assertEquals("OSGI-INF/blueprint/comp2_named.xml", paths.get(1).getName());
assertEquals(0, paths.get(1).getAttributes().size());
assertEquals(0, paths.get(1).getDirectives().size());
assertEquals("foo.xml", paths.get(2).getName());
assertEquals(2, paths.get(2).getAttributes().size());
assertEquals("b", paths.get(2).getAttribute("a"));
assertEquals("5", paths.get(2).getAttribute("4"));
assertEquals(2, paths.get(2).getDirectives().size());
assertEquals("d", paths.get(2).getDirective("c"));
assertEquals("2", paths.get(2).getDirective("1"));
}
}
| 9,413 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/utils/DynamicCollectionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import java.util.Iterator;
import junit.framework.TestCase;
public class DynamicCollectionTest extends TestCase {
protected static final Object O0 = new Object();
protected static final Object O1 = new Object();
protected static final Object O2 = new Object();
protected static final Object O3 = new Object();
protected DynamicCollection<Object> collection;
protected void setUp() {
collection = new DynamicCollection<Object>();
}
public void testAddRemove() throws Exception {
assertEquals(0, collection.size());
assertTrue(collection.isEmpty());
collection.add(O0);
assertEquals(1, collection.size());
assertFalse(collection.isEmpty());
assertTrue(collection.contains(O0));
assertFalse(collection.contains(O1));
collection.clear();
assertEquals(0, collection.size());
collection.add(O0);
collection.add(O0);
assertEquals(2, collection.size());
assertTrue(collection.remove(O0));
assertEquals(1, collection.size());
assertTrue(collection.remove(O0));
assertEquals(0, collection.size());
}
public void testSimpleIterator() throws Exception {
collection.add(O0);
Iterator iterator = collection.iterator();
assertTrue(iterator.hasNext());
assertEquals(O0, iterator.next());
assertFalse(iterator.hasNext());
}
public void testAddWhileIterating() throws Exception {
Iterator iterator = collection.iterator();
assertFalse(iterator.hasNext());
collection.add(O0);
assertTrue(iterator.hasNext());
assertEquals(O0, iterator.next());
assertFalse(iterator.hasNext());
}
public void testRemoveElementWhileIterating() throws Exception {
collection.add(O0);
collection.add(O1);
Iterator iterator = collection.iterator();
assertTrue(iterator.hasNext());
collection.remove(O0);
assertEquals(O0, iterator.next());
assertTrue(iterator.hasNext());
assertEquals(O1, iterator.next());
assertFalse(iterator.hasNext());
}
public void testRemoveElementAfterWhileIterating() throws Exception {
collection.add(O0);
collection.add(O1);
Iterator iterator = collection.iterator();
assertTrue(iterator.hasNext());
assertEquals(O0, iterator.next());
collection.remove(O1);
assertFalse(iterator.hasNext());
}
public void testRemoveElementBeforeWhileIterating() throws Exception {
collection.add(O0);
collection.add(O1);
Iterator iterator = collection.iterator();
assertTrue(iterator.hasNext());
assertEquals(O0, iterator.next());
collection.remove(O0);
assertTrue(iterator.hasNext());
assertEquals(O1, iterator.next());
assertFalse(iterator.hasNext());
}
}
| 9,414 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/utils/ReflectionUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Future;
import org.apache.aries.blueprint.di.CircularDependencyException;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.ReflectionUtils.PropertyDescriptor;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.BeforeClass;
import org.junit.Test;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
public class ReflectionUtilsTest {
private PropertyDescriptor[] sut;
private static ExtendedBlueprintContainer mockBlueprint;
public static class GetterOnly {
public String getValue() { return "test"; }
}
private class Inconvertible {}
@BeforeClass
public static void before() throws ClassNotFoundException
{
mockBlueprint = EasyMock.createNiceMock(ExtendedBlueprintContainer.class);
final Capture<String> nameCapture = Capture.newInstance();
EasyMock.expect(mockBlueprint.loadClass(EasyMock.capture(nameCapture))).andAnswer(new IAnswer<Class<?>>() {
public Class<?> answer() throws Throwable {
return Thread.currentThread().getContextClassLoader().loadClass(nameCapture.getValue());
}
});
EasyMock.replay(mockBlueprint);
ExecutionContext.Holder.setContext(new ExecutionContext() {
public void addPartialObject(String name, Object object) {}
public boolean containsObject(String name) { return false; }
public Object convert(Object value, ReifiedType type) throws Exception {
if (type.getRawClass().equals(Inconvertible.class)) throw new Exception();
else if (type.getRawClass().equals(String.class)) return String.valueOf(value);
else if (type.getRawClass().equals(List.class)) {
if (value == null) return null;
else if (value instanceof Collection) return new ArrayList((Collection) value);
else throw new Exception();
} else if (value == null) return null;
else if (type.getRawClass().isInstance(value)) return value;
else throw new Exception();
}
public boolean canConvert(Object value, ReifiedType type) {
if (value instanceof Inconvertible) return false;
else if (type.getRawClass().equals(String.class)) return true;
else if (type.getRawClass().equals(List.class) && (value == null || value instanceof Collection)) return true;
else return false;
}
public Object getObject(String name) { return null; }
public Object getPartialObject(String name) { return null; }
public Recipe getRecipe(String name) { return null; }
public Class loadClass(String className) throws ClassNotFoundException { return null; }
public Recipe pop() { return null; }
public void push(Recipe recipe) throws CircularDependencyException {}
public void removePartialObject(String name) {}
public Future<Object> addFullObject(String name, Future<Object> object) { return null; }
});
}
@Test
public void testGetterOnly() throws Exception {
loadProps(GetterOnly.class, true, false);
assertEquals(2, sut.length);
assertEquals("class", sut[0].getName());
assertEquals("value", sut[1].getName());
assertTrue(sut[1].allowsGet());
assertFalse(sut[1].allowsSet());
assertEquals("test", sut[1].get(new GetterOnly(), mockBlueprint));
}
public static class SetterOnly {
private String f;
public void setField(String val) { f = val; }
public String retrieve() { return f; }
}
@Test
public void testSetterOnly() throws Exception {
loadProps(SetterOnly.class, false, false);
assertEquals(2, sut.length);
assertEquals("field", sut[1].getName());
assertFalse(sut[1].allowsGet());
assertTrue(sut[1].allowsSet());
SetterOnly so = new SetterOnly();
sut[1].set(so, "trial", mockBlueprint);
assertEquals("trial", so.retrieve());
}
public static class SetterAndGetter {
private String f;
public void setField(String val) { f = val; }
public String getField() { return f; }
}
@Test
public void testSetterAndGetter() throws Exception {
loadProps(SetterAndGetter.class, false, false);
assertEquals(2, sut.length);
assertEquals("field", sut[1].getName());
assertTrue(sut[1].allowsGet());
assertTrue(sut[1].allowsSet());
SetterAndGetter sag = new SetterAndGetter();
sut[1].set(sag, "tribulation", mockBlueprint);
assertEquals("tribulation", sut[1].get(sag, mockBlueprint));
}
public static class DuplicateGetter {
public boolean isField() { return true; }
public boolean getField() { return false; }
}
public static class DuplicateGetter2 {
public boolean getField() { return false; }
public boolean isField() { return true; }
}
@Test
public void testDuplicateGetter() throws Exception {
loadProps(DuplicateGetter.class, false, false);
assertEquals(2, sut.length);
assertEquals("class", sut[0].getName());
assertEquals("field", sut[1].getName());
assertTrue(sut[1].allowsGet());
assertFalse(sut[1].allowsSet());
assertTrue((Boolean) sut[1].get(new DuplicateGetter(), mockBlueprint));
loadProps(DuplicateGetter2.class, false, false);
assertEquals(2, sut.length);
assertEquals("class", sut[0].getName());
assertEquals("field", sut[1].getName());
assertTrue(sut[1].allowsGet());
assertFalse(sut[1].allowsSet());
assertTrue((Boolean) sut[1].get(new DuplicateGetter2(), mockBlueprint));
}
static class FieldsAndProps {
private String hidden = "ordeal";
private String nonHidden;
public String getHidden() { return hidden; }
}
@Test
public void testFieldsAndProps() throws Exception {
loadProps(FieldsAndProps.class, true, false);
assertEquals(3, sut.length);
FieldsAndProps fap = new FieldsAndProps();
// no mixing of setter and field injection
assertEquals("hidden", sut[1].getName());
assertTrue(sut[1].allowsGet());
assertTrue(sut[1].allowsSet());
assertEquals("ordeal", sut[1].get(fap, mockBlueprint));
sut[1].set(fap, "calvary", mockBlueprint);
assertEquals("calvary", sut[1].get(fap, mockBlueprint));
assertEquals("nonHidden", sut[2].getName());
assertTrue(sut[2].allowsGet());
assertTrue(sut[2].allowsSet());
sut[2].set(fap, "predicament", mockBlueprint);
assertEquals("predicament", sut[2].get(fap, mockBlueprint));
}
public static class OverloadedSetters {
public Object field;
public void setField(String val) { field = val; }
public void setField(List<String> val) { field = val; }
}
@Test
public void testOverloadedSetters() throws Exception {
loadProps(OverloadedSetters.class, false, false);
OverloadedSetters os = new OverloadedSetters();
sut[1].set(os, "scrutiny", mockBlueprint);
assertEquals("scrutiny", os.field);
sut[1].set(os, Arrays.asList("evaluation"), mockBlueprint);
assertEquals(Arrays.asList("evaluation"), os.field);
// conversion case, Integer -> String
sut[1].set(os, new Integer(3), mockBlueprint);
assertEquals("3", os.field);
}
@Test(expected=ComponentDefinitionException.class)
public void testApplicableSetter() throws Exception {
loadProps(OverloadedSetters.class, false, false);
sut[1].set(new OverloadedSetters(), new Inconvertible(), mockBlueprint);
}
public static class MultipleMatchesByConversion {
public void setField(String s) {}
public void setField(List<String> list) {}
}
@Test(expected=ComponentDefinitionException.class)
public void testMultipleMatchesByConversion() throws Exception {
loadProps(MultipleMatchesByConversion.class, false, false);
sut[1].set(new MultipleMatchesByConversion(), new HashSet<String>(), mockBlueprint);
}
public static class MultipleMatchesByType {
public void setField(List<String> list) {}
public void setField(Queue<String> list) {}
public static int field;
public void setOther(Collection<String> list) { field=1; }
public void setOther(List<String> list) { field=2; }
}
@Test(expected=ComponentDefinitionException.class)
public void testMultipleSettersMatchByType() throws Exception {
loadProps(MultipleMatchesByType.class, false, false);
sut[1].set(new MultipleMatchesByType(), new LinkedList<String>(), mockBlueprint);
}
@Test
public void testDisambiguationByHierarchy() throws Exception {
loadProps(MultipleMatchesByType.class, false, false);
sut[2].set(new MultipleMatchesByType(), new ArrayList<String>(), mockBlueprint);
assertEquals(2, MultipleMatchesByType.field);
}
public static class NullSetterDisambiguation {
public static int field;
public void setField(int i) { field = i; }
public void setField(Integer i) { field = -1; }
}
@Test
public void testNullDisambiguation() throws Exception {
loadProps(NullSetterDisambiguation.class, false, false);
sut[1].set(new NullSetterDisambiguation(), null, mockBlueprint);
assertEquals(-1, NullSetterDisambiguation.field);
}
private void loadProps(Class<?> clazz, boolean allowFieldInjection, boolean allowNonStandardSetters)
{
List<PropertyDescriptor> props = new ArrayList<PropertyDescriptor>(
Arrays.asList(ReflectionUtils.getPropertyDescriptors(clazz, allowFieldInjection, allowNonStandardSetters)));
Collections.sort(props, new Comparator<PropertyDescriptor>() {
public int compare(PropertyDescriptor o1, PropertyDescriptor o2) {
return o1.getName().compareTo(o2.getName());
}
});
sut = props.toArray(new PropertyDescriptor[0]);
}
}
| 9,415 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/container/LifecyclePolicyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util.ArrayList;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.aries.blueprint.BlueprintConstants;
import org.apache.aries.blueprint.ExtendedReferenceMetadata;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.apache.aries.blueprint.reflect.BeanMetadataImpl;
import org.apache.aries.blueprint.reflect.RefMetadataImpl;
import org.apache.aries.blueprint.reflect.ReferenceMetadataImpl;
import org.apache.aries.proxy.ProxyManager;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.Version;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;
public class LifecyclePolicyTest {
@Test
public void testStatic() throws Exception {
final ReferenceMetadataImpl ref = new ReferenceMetadataImpl();
ref.setId("ref");
ref.setRuntimeInterface(TestItf.class);
ref.setLifecycle(ExtendedReferenceMetadata.LIFECYCLE_STATIC);
final BeanMetadataImpl bean1 = new BeanMetadataImpl();
bean1.setId("bean1");
bean1.setRuntimeClass(Bean1.class);
bean1.setInitMethod("init");
bean1.setDestroyMethod("destroy");
bean1.addProperty("itf", new RefMetadataImpl("ref"));
final BeanMetadataImpl bean2 = new BeanMetadataImpl();
bean2.setId("bean2");
bean2.setRuntimeClass(Bean2.class);
bean2.setInitMethod("init");
bean2.setDestroyMethod("destroy");
bean2.addProperty("bean1", new RefMetadataImpl("bean1"));
Bundle bundle = EasyMock.createMock(Bundle.class);
BundleContext bundleContext = EasyMock.createMock(BundleContext.class);
Bundle extenderBundle = EasyMock.createMock(Bundle.class);
BundleContext extenderBundleContext = EasyMock.createMock(BundleContext.class);
BlueprintListener eventDispatcher = EasyMock.createMock(BlueprintListener.class);
NamespaceHandlerRegistry namespaceHandlerRegistry = EasyMock.createMock(NamespaceHandlerRegistry.class);
ProxyManager proxyManager = EasyMock.createMock(ProxyManager.class);
NamespaceHandlerSet namespaceHandlerSet = EasyMock.createMock(NamespaceHandlerSet.class);
TestItf itf = EasyMock.createMock(TestItf.class);
ServiceRegistration registration = EasyMock.createMock(ServiceRegistration.class);
ExecutorService executorService = Executors.newFixedThreadPool(1);
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
List<URL> pathList = new ArrayList<URL>();
Set<URI> namespaces = new HashSet<URI>();
BlueprintContainerImpl container = new BlueprintContainerImpl(
bundle, bundleContext, extenderBundle, eventDispatcher, namespaceHandlerRegistry,
executorService, timer, pathList, proxyManager, namespaces
) {
private boolean repoCreated = false;
@Override
public BlueprintRepository getRepository() {
if (!repoCreated) {
getComponentDefinitionRegistry().registerComponentDefinition(ref);
getComponentDefinitionRegistry().registerComponentDefinition(bean1);
getComponentDefinitionRegistry().registerComponentDefinition(bean2);
repoCreated = true;
}
return super.getRepository();
}
};
ServiceReference svcRef1 = EasyMock.createMock(ServiceReference.class);
EasyMock.expect(bundle.getSymbolicName()).andReturn("bundleSymbolicName").anyTimes();
EasyMock.expect(bundle.getVersion()).andReturn(Version.emptyVersion).anyTimes();
EasyMock.expect(bundle.getState()).andReturn(Bundle.ACTIVE).anyTimes();
EasyMock.expect(bundle.getBundleContext()).andReturn(bundleContext).anyTimes();
Hashtable<String, String> headers = new Hashtable<String, String>();
headers.put(Constants.BUNDLE_SYMBOLICNAME, "bundleSymbolicName;blueprint.aries.xml-validation:=false");
EasyMock.expect(bundle.getHeaders()).andReturn(headers).anyTimes();
eventDispatcher.blueprintEvent(EasyMock.<BlueprintEvent>anyObject());
EasyMock.expectLastCall().anyTimes();
EasyMock.expect(namespaceHandlerRegistry.getNamespaceHandlers(namespaces, bundle))
.andReturn(namespaceHandlerSet).anyTimes();
EasyMock.expect(namespaceHandlerSet.getNamespaces()).andReturn(namespaces).anyTimes();
namespaceHandlerSet.addListener(container);
EasyMock.expectLastCall();
EasyMock.expect(bundleContext.getProperty(BlueprintConstants.XML_VALIDATION_PROPERTY))
.andReturn(null);
Properties props = new Properties();
props.put("osgi.blueprint.container.version", Version.emptyVersion);
props.put("osgi.blueprint.container.symbolicname", "bundleSymbolicName");
EasyMock.expect(bundleContext.registerService(
EasyMock.aryEq(new String[] {BlueprintContainer.class.getName()}),
EasyMock.same(container),
EasyMock.eq((Dictionary)props))).andReturn(registration);
bundleContext.addServiceListener(EasyMock.<org.osgi.framework.ServiceListener>anyObject(), EasyMock.<String>anyObject());
EasyMock.expectLastCall();
EasyMock.expect(bundleContext.getServiceReferences((String) null, "(objectClass=" + TestItf.class.getName() + ")"))
.andReturn(new ServiceReference[] { svcRef1 });
EasyMock.expect(bundleContext.getService(svcRef1)).andReturn(itf);
EasyMock.expect(bundle.loadClass("java.lang.Object")).andReturn((Class) Object.class).anyTimes();
EasyMock.replay(bundle, bundleContext, extenderBundle, extenderBundleContext,
eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager,
svcRef1, registration);
container.run();
ReferenceRecipe recipe = (ReferenceRecipe) container.getRepository().getRecipe("ref");
recipe.start(container);
Bean2 bean2i = (Bean2) container.getRepository().create("bean2");
Assert.assertNotNull(bean2i);
Assert.assertEquals(1, Bean2.initialized);
Assert.assertEquals(0, Bean2.destroyed);
EasyMock.verify(bundle, bundleContext, extenderBundle, extenderBundleContext,
eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager,
svcRef1, registration);
//
// Unregister the service
//
// Given the lifecycle is 'static', this should cause the Bean1 and Bean2
// to be destroyed
//
EasyMock.reset(bundle, bundleContext, extenderBundle, extenderBundleContext,
eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager,
svcRef1, registration);
EasyMock.expect(bundle.getSymbolicName()).andReturn("bundleSymbolicName").anyTimes();
EasyMock.expect(bundle.getVersion()).andReturn(Version.emptyVersion).anyTimes();
EasyMock.expect(bundleContext.ungetService(svcRef1)).andReturn(false);
EasyMock.replay(bundle, bundleContext, extenderBundle, extenderBundleContext,
eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager,
svcRef1, registration);
recipe.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, svcRef1));
Assert.assertEquals(1, Bean2.initialized);
Assert.assertEquals(1, Bean2.destroyed);
EasyMock.verify(bundle, bundleContext, extenderBundle, extenderBundleContext,
eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager,
svcRef1, registration);
//
// Re-register the service
//
// Given the lifecycle is 'static', this should cause the Bean1 and Bean2
// to be recreated
//
EasyMock.reset(bundle, bundleContext, extenderBundle, extenderBundleContext,
eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager,
svcRef1, registration);
EasyMock.expect(bundle.getSymbolicName()).andReturn("bundleSymbolicName").anyTimes();
EasyMock.expect(bundle.getVersion()).andReturn(Version.emptyVersion).anyTimes();
EasyMock.expect(bundleContext.getService(svcRef1)).andReturn(itf);
EasyMock.expect(bundle.loadClass("java.lang.Object")).andReturn((Class) Object.class).anyTimes();
EasyMock.replay(bundle, bundleContext, extenderBundle, extenderBundleContext,
eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager,
svcRef1, registration);
recipe.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, svcRef1));
Assert.assertEquals(2, Bean2.initialized);
Assert.assertEquals(1, Bean2.destroyed);
EasyMock.verify(bundle, bundleContext, extenderBundle, extenderBundleContext,
eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager,
svcRef1, registration);
}
public interface TestItf {
}
public static class Bean1 {
private TestItf itf;
public TestItf getItf() {
return itf;
}
public void setItf(TestItf itf) {
this.itf = itf;
}
public void init() {
}
public void destroy() {
}
}
public static class Bean2 {
private Bean1 bean1;
static int initialized = 0;
static int destroyed = 0;
public Bean1 getBean1() {
return bean1;
}
public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
}
public void init() {
initialized++;
}
public void destroy() {
destroyed++;
}
}
}
| 9,416 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/container/AggregateConverterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.ByteArrayOutputStream;
import java.lang.reflect.Constructor;
import java.math.BigInteger;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.aries.blueprint.TestBlueprintContainer;
import org.apache.aries.blueprint.pojos.PojoGenerics2.MyClass;
import org.apache.aries.blueprint.pojos.PojoGenerics2.MyObject;
import org.apache.aries.blueprint.pojos.PojoGenerics2.Tata;
import org.apache.aries.blueprint.pojos.PojoGenerics2.Toto;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.container.Converter;
public class AggregateConverterTest extends TestCase {
private AggregateConverter service;
protected void setUp() throws Exception {
service = new AggregateConverter(new TestBlueprintContainer(null));
}
public void testConvertNumbers() throws Exception {
assertEquals(1, service.convert(1.46f, int.class));
assertEquals(1.0d, service.convert(1, double.class));
}
public void testConvertSimpleTypes() throws Exception {
assertEquals(123, service.convert("123", int.class));
assertEquals(123, service.convert("123", Integer.class));
assertEquals(123l, service.convert("123", long.class));
assertEquals(123l, service.convert("123", Long.class));
assertEquals((short) 123, service.convert("123", short.class));
assertEquals((short) 123, service.convert("123", Short.class));
assertEquals(1.5f, service.convert("1.5", float.class));
assertEquals(1.5f, service.convert("1.5", Float.class));
assertEquals(1.5, service.convert("1.5", double.class));
assertEquals(1.5, service.convert("1.5", Double.class));
}
public void testConvertCharacter() throws Exception {
assertEquals('c', service.convert("c", char.class));
assertEquals('c', service.convert("c", Character.class));
assertEquals('\u00F6', service.convert("\\u00F6", char.class));
assertEquals('\u00F6', service.convert("\\u00F6", Character.class));
}
public void testConvertBoolean() throws Exception {
assertEquals(Boolean.TRUE, service.convert("true", Boolean.class));
assertEquals(Boolean.TRUE, service.convert("yes", Boolean.class));
assertEquals(Boolean.TRUE, service.convert("on", Boolean.class));
assertEquals(Boolean.TRUE, service.convert("TRUE", Boolean.class));
assertEquals(Boolean.TRUE, service.convert("YES", Boolean.class));
assertEquals(Boolean.TRUE, service.convert("ON", Boolean.class));
assertEquals(Boolean.TRUE, service.convert("true", boolean.class));
assertEquals(Boolean.TRUE, service.convert("yes", boolean.class));
assertEquals(Boolean.TRUE, service.convert("on", boolean.class));
assertEquals(Boolean.TRUE, service.convert("TRUE", boolean.class));
assertEquals(Boolean.TRUE, service.convert("YES", boolean.class));
assertEquals(Boolean.TRUE, service.convert("ON", boolean.class));
assertEquals(Boolean.FALSE, service.convert("false", Boolean.class));
assertEquals(Boolean.FALSE, service.convert("no", Boolean.class));
assertEquals(Boolean.FALSE, service.convert("off", Boolean.class));
assertEquals(Boolean.FALSE, service.convert("FALSE", Boolean.class));
assertEquals(Boolean.FALSE, service.convert("NO", Boolean.class));
assertEquals(Boolean.FALSE, service.convert("OFF", Boolean.class));
assertEquals(Boolean.FALSE, service.convert("false", boolean.class));
assertEquals(Boolean.FALSE, service.convert("no", boolean.class));
assertEquals(Boolean.FALSE, service.convert("off", boolean.class));
assertEquals(Boolean.FALSE, service.convert("FALSE", boolean.class));
assertEquals(Boolean.FALSE, service.convert("NO", boolean.class));
assertEquals(Boolean.FALSE, service.convert("OFF", boolean.class));
assertEquals(Boolean.FALSE, service.convert(false, boolean.class));
assertEquals(Boolean.TRUE, service.convert(true, boolean.class));
assertEquals(Boolean.FALSE, service.convert(false, Boolean.class));
assertEquals(Boolean.TRUE, service.convert(true, Boolean.class));
}
public void testConvertOther() throws Exception {
assertEquals(URI.create("urn:test"), service.convert("urn:test", URI.class));
assertEquals(new URL("file:/test"), service.convert("file:/test", URL.class));
assertEquals(new BigInteger("12345"), service.convert("12345", BigInteger.class));
}
public void testConvertProperties() throws Exception {
Properties props = new Properties();
props.setProperty("key", "value");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
props.store(baos, null);
props = (Properties) service.convert(baos.toString(), Properties.class);
assertEquals(1, props.size());
assertEquals("value", props.getProperty("key"));
}
public void testConvertLocale() throws Exception {
Object result;
result = service.convert("en", Locale.class);
assertTrue(result instanceof Locale);
assertEquals(new Locale("en"), result);
result = service.convert("de_DE", Locale.class);
assertTrue(result instanceof Locale);
assertEquals(new Locale("de", "DE"), result);
result = service.convert("_GB", Locale.class);
assertTrue(result instanceof Locale);
assertEquals(new Locale("", "GB"), result);
result = service.convert("en_US_WIN", Locale.class);
assertTrue(result instanceof Locale);
assertEquals(new Locale("en", "US", "WIN"), result);
result = service.convert("de__POSIX", Locale.class);
assertTrue(result instanceof Locale);
assertEquals(new Locale("de", "", "POSIX"), result);
}
public void testConvertClass() throws Exception {
assertEquals(this, service.convert(this, AggregateConverterTest.class));
assertEquals(AggregateConverterTest.class, service.convert(this.getClass().getName(), Class.class));
assertEquals(int[].class, service.convert("int[]", Class.class));
assertEquals(RegionIterable.class, service.convert(RegionIterable.class.getName(), new GenericType(Class.class, new GenericType(RegionIterable.class))));
assertTrue(AggregateConverter.isAssignable(RegionIterable.class, new GenericType(Class.class, new GenericType(RegionIterable.class))));
}
public void testConvertArray() throws Exception {
Object obj = service.convert(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4)),
GenericType.parse("java.util.List<java.lang.Integer>[]", getClass().getClassLoader()));
assertNotNull(obj);
assertTrue(obj.getClass().isArray());
Object[] o = (Object[]) obj;
assertEquals(2, o.length);
assertNotNull(o[0]);
assertTrue(o[0] instanceof List);
assertEquals(2, ((List) o[0]).size());
assertEquals(1, ((List) o[0]).get(0));
assertEquals(2, ((List) o[0]).get(1));
assertNotNull(o[0]);
assertTrue(o[1] instanceof List);
assertEquals(2, ((List) o[1]).size());
assertEquals(3, ((List) o[1]).get(0));
assertEquals(4, ((List) o[1]).get(1));
//assertEquals((Object) new int[] { 1, 2 }, (Object) service.convert(Arrays.asList(1, 2), int[].class));
}
public void testCustom() throws Exception {
AggregateConverter s = new AggregateConverter(new TestBlueprintContainer(null));
s.registerConverter(new RegionConverter());
s.registerConverter(new EuRegionConverter());
// lookup on a specific registered converter type
Object result;
result = s.convert(new Object(), Region.class);
assertTrue(result instanceof Region);
assertFalse(result instanceof EuRegion);
result = s.convert(new Object(), EuRegion.class);
assertTrue(result instanceof EuRegion);
// find first converter that matches the type
s = new AggregateConverter(new TestBlueprintContainer(null));
s.registerConverter(new AsianRegionConverter());
s.registerConverter(new EuRegionConverter());
s.registerConverter(new NullMarkerConverter());
result = s.convert(new Object(), Region.class);
// TODO: check with the spec about the result
//assertTrue(result instanceof AsianRegion || result instanceof EuRegion);
result = s.convert(new Object(), NullMarker.class);
assertNull(result);
}
public void testGenericWilcard() throws Exception {
Constructor cns = MyClass.class.getConstructor(MyObject.class);
assertTrue(AggregateConverter.isAssignable(new Toto(), new GenericType(cns.getGenericParameterTypes()[0])));
cns = Tata.class.getConstructor(MyObject.class);
assertTrue(AggregateConverter.isAssignable(new Toto(), new GenericType(cns.getGenericParameterTypes()[0])));
}
public void testGenericAssignable() throws Exception {
AggregateConverter s = new AggregateConverter(new TestBlueprintContainer(null));
assertNotNull(s.convert(new RegionIterable(), new GenericType(Iterable.class, new GenericType(Region.class))));
try {
s.convert(new ArrayList<Region>(), new GenericType(Iterable.class, new GenericType(Region.class)));
fail("Conversion should have thrown an exception");
} catch (Exception e) {
// Ignore
}
assertTrue(Iterable.class.isAssignableFrom(RegionIterable.class));
// note that method signature is fromType, toType - reverse than above
assertTrue("Type should be assignable.", AggregateConverter.isTypeAssignable(new GenericType(RegionIterable.class), new GenericType(Iterable.class)));
}
public void testGenericCollection() throws Exception {
AggregateConverter s = new AggregateConverter(new TestBlueprintContainer(null));
try {
s.convert(new ArrayList(), new GenericType(Iterable.class, new GenericType(Region.class)));
fail("Conversion should have thrown an exception");
} catch (Exception e) {
// Ignore
}
try {
s.convert(Arrays.asList(0l), new GenericType(Iterable.class, new GenericType(Region.class)));
fail("Conversion should have thrown an exception");
} catch (Exception e) {
// Ignore
}
assertNotNull(s.convert(Arrays.asList(new EuRegion() {}), new GenericType(List.class, new GenericType(Region.class))));
}
public void testConvertCompatibleCollections() throws Exception {
Object org = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4));
Object obj = service.convert(org,
GenericType.parse("java.util.List<java.util.List<java.lang.Integer>>", getClass().getClassLoader()));
assertSame(org, obj);
org = Collections.singletonMap("foo", 1);
obj = service.convert(org,
GenericType.parse("java.util.Map<java.lang.String,java.lang.Integer>", getClass().getClassLoader()));
assertSame(org, obj);
org = new int[] { 1, 2 };
obj = service.convert(org,
GenericType.parse("int[]", getClass().getClassLoader()));
assertSame(org, obj);
org = new Object[] { 1, 2 };
obj = service.convert(org,
GenericType.parse("int[]", getClass().getClassLoader()));
assertNotSame(org, obj);
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
ht.put("foo", 1);
org = ht;
obj = service.convert(org, GenericType.parse("java.util.Dictionary<java.lang.String,java.lang.Integer>", getClass().getClassLoader()));
assertSame(org, obj);;
}
private interface Region {}
private interface EuRegion extends Region {}
private interface AsianRegion extends Region {}
private interface NullMarker {}
private static class RegionConverter implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return Region.class == toType.getRawClass();
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return new Region() {} ;
}
}
private static class EuRegionConverter implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return toType.getRawClass().isAssignableFrom(EuRegion.class);
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return new EuRegion() {} ;
}
}
private static class AsianRegionConverter implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return toType.getRawClass().isAssignableFrom(AsianRegion.class);
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return new AsianRegion() {} ;
}
}
private static class NullMarkerConverter implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return toType.getRawClass().isAssignableFrom(NullMarker.class);
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return null;
}
}
private static class RegionIterable implements Iterable<Region> {
public Iterator<Region> iterator() {
return null;
}
}
}
| 9,417 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/container/BPQuiesceTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 junit.framework.Assert.assertTrue;
import java.util.Arrays;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.apache.aries.quiesce.manager.QuiesceCallback;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
public class BPQuiesceTest {
@Test
public void canQuiesceNoBPBundle() throws Exception {
IMocksControl c = EasyMock.createControl();
BundleContext ctx = c.createMock(BundleContext.class);
Bundle bpBundle = c.createMock(Bundle.class);
Bundle testBundle = c.createMock(Bundle.class);
EasyMock.expect(ctx.getBundle()).andReturn(bpBundle);
BlueprintQuiesceParticipant bqp = new BlueprintQuiesceParticipant(ctx, new BlueprintExtender() {
@Override
protected BlueprintContainerImpl getBlueprintContainerImpl(Bundle bundle) {
return null;
}
});
final Semaphore result = new Semaphore(0);
QuiesceCallback qc = new QuiesceCallback() {
public void bundleQuiesced(Bundle... bundlesQuiesced) {
result.release();
}
};
c.replay();
bqp.quiesce(qc, Arrays.asList(testBundle));
c.verify();
assertTrue(result.tryAcquire(2, TimeUnit.SECONDS));
}
}
| 9,418 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/container/DampingPolicyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util.concurrent.atomic.AtomicReference;
import org.apache.aries.blueprint.ExtendedReferenceMetadata;
import org.apache.aries.blueprint.container.SatisfiableRecipe.SatisfactionListener;
import org.apache.aries.blueprint.reflect.ReferenceMetadataImpl;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
public class DampingPolicyTest {
@Test
public void testGreedy() throws InvalidSyntaxException {
ExtendedBlueprintContainer container = EasyMock.createMock(ExtendedBlueprintContainer.class);
BundleContext containerContext = EasyMock.createMock(BundleContext.class);
ReferenceMetadataImpl metadata = new ReferenceMetadataImpl();
metadata.setInterface("my.interface");
metadata.setDamping(ExtendedReferenceMetadata.DAMPING_GREEDY);
final AtomicReference<ServiceReference> currentReference = new AtomicReference<ServiceReference>();
ReferenceRecipe recipe = new ReferenceRecipe(
"myref",
container,
metadata,
null, null, null
) {
@Override
protected void bind(ServiceReference ref) {
currentReference.set(ref);
super.bind(ref);
}
};
SatisfactionListener listener = new SatisfactionListener() {
@Override
public void notifySatisfaction(SatisfiableRecipe satisfiable) {
}
};
ServiceReference svcRef1 = EasyMock.createMock(ServiceReference.class);
EasyMock.expect(container.getBundleContext()).andReturn(containerContext).anyTimes();
containerContext.addServiceListener(recipe, "(objectClass=my.interface)");
EasyMock.expectLastCall();
EasyMock.expect(containerContext.getServiceReferences((String) null, "(objectClass=my.interface)"))
.andReturn(new ServiceReference[] { svcRef1 });
EasyMock.replay(container, containerContext, svcRef1);
recipe.start(listener);
Assert.assertSame(svcRef1, currentReference.get());
EasyMock.verify(container, containerContext, svcRef1);
EasyMock.reset(container, containerContext, svcRef1);
ServiceReference svcRef2 = EasyMock.createMock(ServiceReference.class);
ServiceEvent event2 = new ServiceEvent(ServiceEvent.REGISTERED, svcRef2);
EasyMock.expect(svcRef1.getProperty(Constants.SERVICE_ID)).andReturn(0L).anyTimes();
EasyMock.expect(svcRef1.getProperty(Constants.SERVICE_RANKING)).andReturn(0).anyTimes();
EasyMock.expect(svcRef2.getProperty(Constants.SERVICE_ID)).andReturn(1L).anyTimes();
EasyMock.expect(svcRef2.getProperty(Constants.SERVICE_RANKING)).andReturn(1).anyTimes();
EasyMock.replay(container, containerContext, svcRef1, svcRef2);
recipe.serviceChanged(event2);
Assert.assertSame(svcRef2, currentReference.get());
EasyMock.verify(container, containerContext, svcRef1, svcRef2);
}
}
| 9,419 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/container/GenericTypeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.net.URI;
import junit.framework.TestCase;
public class GenericTypeTest extends TestCase {
private GenericType parse(String expression) throws Exception {
GenericType type = GenericType.parse(expression, getClass().getClassLoader());
assertEquals(expression, type.toString());
return type;
}
public void testArrays() {
assertTrue(AggregateConverter.isAssignable(new Object[0], new GenericType(Object[].class)));
assertFalse(AggregateConverter.isAssignable(new Object[0], new GenericType(String[].class)));
assertTrue(AggregateConverter.isAssignable(new String[0], new GenericType(String[].class)));
assertFalse(AggregateConverter.isAssignable(new String[0], new GenericType(URI[].class)));
assertTrue(AggregateConverter.isAssignable(new String[0], new GenericType(Object[].class)));
}
public void testParseTypes() throws Exception {
GenericType type = parse("java.util.List<java.lang.String[]>");
assertEquals(List.class, type.getRawClass());
assertEquals(1, type.size());
assertEquals(String[].class, type.getActualTypeArgument(0).getRawClass());
assertEquals(1, type.getActualTypeArgument(0).size());
assertEquals(String.class, type.getActualTypeArgument(0).getActualTypeArgument(0).getRawClass());
type = parse("java.util.Map<int,java.util.List<java.lang.Integer>[]>");
assertEquals(Map.class, type.getRawClass());
assertEquals(2, type.size());
assertEquals(int.class, type.getActualTypeArgument(0).getRawClass());
assertEquals(List[].class, type.getActualTypeArgument(1).getRawClass());
assertEquals(1, type.getActualTypeArgument(1).size());
assertEquals(Integer.class, type.getActualTypeArgument(1).getActualTypeArgument(0).getActualTypeArgument(0).getRawClass());
type = parse("java.util.List<java.lang.Integer>[]");
assertEquals(List[].class, type.getRawClass());
assertEquals(1, type.size());
assertEquals(Integer.class, type.getActualTypeArgument(0).getActualTypeArgument(0).getRawClass());
type = parse("java.util.List<? extends java.lang.Number>");
assertEquals(List.class, type.getRawClass());
assertEquals(1, type.size());
assertEquals(Number.class, type.getActualTypeArgument(0).getRawClass());
}
public void testBasic() throws Exception {
GenericType type = new GenericType(int[].class);
assertEquals("int[]", type.toString());
assertEquals(int[].class, type.getRawClass());
assertEquals(0, type.getActualTypeArgument(0).size());
}
}
| 9,420 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/container/BeanRecipeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.di.PassThroughRecipe;
import org.apache.aries.blueprint.utils.generics.TypeInference;
import org.junit.Test;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import static org.junit.Assert.*;
public class BeanRecipeTest {
static class Base {
public static Object getObject() { return null; }
public static Object getOne(Object o) { return null; }
public static Object getMany(Object o, String n, String n2) { return null; }
}
static class Middle extends Base {
public static Number getObject() { return null; }
public static Number getOne(Number n) { return null; }
public static Number getOne(Object o) { return null; }
public static Object getMany(Object o, String n, Number i) { return null; }
public static Object getBasic(int n) { return 0; }
}
static class Top extends Middle {
public static Integer getObject() { return null; }
public static Integer getOne(Integer n) { return null; }
public static Object getMany(Object o, String n, Number i) { return null; }
public static Object getBasic(int n) { return 0; }
}
static class Unrelated {
public static String getObject() { return null; }
public static Object getBasic(int n) { return 1; }
}
static public interface EventMessage<T> {
}
static public interface SequentialPolicy<T> {
}
static public class DummySequentialPolicy implements SequentialPolicy<Object> {
}
static public class MessageDriven {
public MessageDriven(SequentialPolicy<? super EventMessage<?>> policy) {
}
}
static public interface Example<A> {}
static public class ExampleImpl implements Example<String> {}
static public class ExampleService {
public ExampleService(Example<String> e) {}
}
static public interface BaseInterface<T> { }
static public interface ExtendedInterface<T0, T1> extends BaseInterface<T1> {}
static public class MyClass implements ExtendedInterface<String, Integer> { }
static public class MyClass2<T> implements BaseInterface<T> { }
static public class MyClass3 extends MyClass2<Long> { }
static public class MyService {
public MyService(BaseInterface<? extends Number> e) {}
}
static public interface A {
String getA();
void setA(String a);
}
static public interface B extends A {
String getB();
void setB(String b);
void init();
}
static public class C implements B {
String a = "a", b = "b", c = "c";
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public void init() {
}
}
static public class Factory {
public B create() {
return new D();
}
private class D extends C {
String d = "d";
public String getD() {
return d;
}
public void setD(String d) {
this.d = d;
}
public void init() {
}
}
}
static public class VarArg {
public VarArg(String... as) {
}
}
@Test
public void parameterWithGenerics() throws Exception {
BlueprintContainerImpl container = new BlueprintContainerImpl(null, null, null, null, null, null, null, null, null, null);
BeanRecipe recipe = new BeanRecipe("example", container, ExampleService.class, false, false, false);
recipe.setArguments(Arrays.<Object>asList(new ExampleImpl()));
recipe.setArgTypes(Arrays.<String>asList((String) null));
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
recipe.create();
}
@Test
public void parameterWithComplexGenerics1() throws Exception {
BlueprintContainerImpl container = new BlueprintContainerImpl(null, null, null, null, null, null, null, null, null, null);
BeanRecipe recipe = new BeanRecipe("example", container, MyService.class, false, false, false);
recipe.setArguments(Arrays.<Object>asList(new MyClass()));
recipe.setArgTypes(Arrays.<String>asList((String) null));
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
recipe.create();
}
@Test
public void parameterWithComplexGenerics2() throws Exception {
BlueprintContainerImpl container = new BlueprintContainerImpl(null, null, null, null, null, null, null, null, null, null);
BeanRecipe recipe = new BeanRecipe("example", container, MyService.class, false, false, false);
recipe.setArguments(Arrays.<Object>asList(new MyClass3()));
recipe.setArgTypes(Arrays.<String>asList((String) null));
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
recipe.create();
}
@Test
public void constructorWithGenerics() throws Exception {
BlueprintContainerImpl container = new BlueprintContainerImpl(null, null, null, null, null, null, null, null, null, null);
BeanRecipe recipe = new BeanRecipe("example", container, MessageDriven.class, false, false, false);
recipe.setArguments(Arrays.<Object>asList(new DummySequentialPolicy()));
recipe.setArgTypes(Arrays.<String>asList((String) null));
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
recipe.create();
}
@Test
public void constructorWithVarArg() throws Exception {
BlueprintContainerImpl container = new BlueprintContainerImpl(null, null, null, null, null, null, null, null, null, null);
BeanRecipe recipe = new BeanRecipe("example", container, VarArg.class, false, false, false);
recipe.setArguments(Arrays.<Object>asList(Arrays.asList("-web")));
recipe.setArgTypes(Arrays.<String>asList((String) null));
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
recipe.create();
}
@Test
public void parameterLessHiding() throws Exception {
Set<Method> methods = new HashSet<Method>(
Arrays.asList(
Base.class.getMethod("getObject"),
Middle.class.getMethod("getObject"),
Top.class.getMethod("getObject"),
Unrelated.class.getMethod("getObject")
));
methods = applyStaticHidingRules(methods);
assertEquals(2, methods.size());
assertTrue(methods.contains(Top.class.getMethod("getObject")));
assertTrue(methods.contains(Unrelated.class.getMethod("getObject")));
assertFalse(methods.contains(Middle.class.getMethod("getObject")));
}
@Test
public void parameterDistinction() throws Exception {
Set<Method> methods = new HashSet<Method>(
Arrays.asList(
Base.class.getMethod("getOne", Object.class),
Middle.class.getMethod("getOne", Number.class),
Middle.class.getMethod("getOne", Object.class),
Top.class.getMethod("getOne", Integer.class)
));
methods = applyStaticHidingRules(methods);
assertEquals(3, methods.size());
assertFalse(methods.contains(Base.class.getMethod("getOne", Object.class)));
}
@Test
public void multiParameterTest() throws Exception {
Set<Method> methods = new HashSet<Method>(
Arrays.asList(
Base.class.getMethod("getMany", Object.class, String.class, String.class),
Middle.class.getMethod("getMany", Object.class, String.class, Number.class),
Top.class.getMethod("getMany", Object.class, String.class, Number.class)
));
methods = applyStaticHidingRules(methods);
assertEquals(2, methods.size());
assertFalse(methods.contains(Middle.class.getMethod("getMany", Object.class, String.class, Number.class)));
}
@Test
public void baseTypeHiding() throws Exception {
Set<Method> methods = new HashSet<Method>(
Arrays.asList(
Middle.class.getMethod("getBasic", int.class),
Top.class.getMethod("getBasic", int.class),
Unrelated.class.getMethod("getBasic", int.class)
));
methods = applyStaticHidingRules(methods);
assertEquals(2, methods.size());
assertFalse(methods.contains(Middle.class.getMethod("getBasic", int.class)));
}
@Test
public void protectedClassAccess() throws Exception {
BlueprintContainerImpl container = new BlueprintContainerImpl(null, null, null, null, null, null, null, null, null, null);
BeanRecipe recipe = new BeanRecipe("a", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory().create()));
recipe.setFactoryMethod("getA");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
assertNotNull(recipe.create());
recipe = new BeanRecipe("b", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory().create()));
recipe.setFactoryMethod("getB");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
assertNotNull(recipe.create());
recipe = new BeanRecipe("c", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory().create()));
recipe.setFactoryMethod("getC");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
assertNotNull(recipe.create());
recipe = new BeanRecipe("d", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory().create()));
recipe.setFactoryMethod("getD");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
try {
assertNotNull(recipe.create());
fail("Should have thrown an exception");
} catch (ComponentDefinitionException e) {
// ok
}
recipe = new BeanRecipe("a", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory()));
recipe.setFactoryMethod("create");
recipe.setProperty("a", "a");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
assertNotNull(recipe.create());
recipe = new BeanRecipe("b", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory()));
recipe.setFactoryMethod("create");
recipe.setProperty("b", "b");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
assertNotNull(recipe.create());
recipe = new BeanRecipe("c", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory()));
recipe.setFactoryMethod("create");
recipe.setProperty("c", "c");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
assertNotNull(recipe.create());
recipe = new BeanRecipe("d", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory()));
recipe.setFactoryMethod("create");
recipe.setProperty("d", "d");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
try {
assertNotNull(recipe.create());
fail("Should have thrown an exception");
} catch (ComponentDefinitionException e) {
// ok
}
recipe = new BeanRecipe("a", container, null, false, false, false);
recipe.setFactoryComponent(new PassThroughRecipe("factory", new Factory()));
recipe.setFactoryMethod("create");
recipe.setInitMethod("init");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
assertNotNull(recipe.create());
}
private Set<Method> applyStaticHidingRules(Collection<Method> methods) {
try {
Method m = TypeInference.class.getDeclaredMethod("applyStaticHidingRules", Collection.class);
m.setAccessible(true);
return new HashSet<Method>((List<Method>) m.invoke(null, methods));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 9,421 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/container/TypeInferenceTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.TestBlueprintContainer;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.pojos.DummyServiceTrackerCustomizer;
import org.apache.aries.blueprint.pojos.PojoA;
import org.apache.aries.blueprint.utils.generics.OwbParametrizedTypeImpl;
import org.apache.aries.blueprint.utils.generics.TypeInference;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.util.tracker.ServiceTracker;
import java.lang.reflect.Constructor;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertNotNull;
public class TypeInferenceTest {
private final Converter converter;
public TypeInferenceTest() throws Exception {
converter = new AggregateConverter(new TestBlueprintContainer(null));
}
@Test
public void testSimple() {
TypeInference.Match<Constructor<?>> match = TypeInference.findMatchingConstructors(
ServiceTracker.class,
Arrays.asList(
new TypeInference.TypedObject(BundleContext.class, null),
new TypeInference.TypedObject(new OwbParametrizedTypeImpl(null, Class.class, PojoA.class), PojoA.class),
new TypeInference.TypedObject(DummyServiceTrackerCustomizer.class, null)),
new TIConverter(),
false)
.get(0);
assertNotNull(match);
}
@Test
public void testReorder() {
TypeInference.Match<Constructor<?>> match = TypeInference.findMatchingConstructors(
ServiceTracker.class,
Arrays.asList(
new TypeInference.TypedObject(new OwbParametrizedTypeImpl(null, Class.class, PojoA.class), PojoA.class),
new TypeInference.TypedObject(BundleContext.class, null),
new TypeInference.TypedObject(DummyServiceTrackerCustomizer.class, null)),
new TIConverter(),
true)
.get(0);
assertNotNull(match);
}
@Test
public void testParameterWithNullCollections() {
BlueprintContainerImpl container = new BlueprintContainerImpl(null, null, null, null, null, null, null, null, null, null);
BeanRecipe recipe = new BeanRecipe("sessionDef", container, FactoryWithList.class, false, false, false);
recipe.setArguments(Collections.singletonList(null));
recipe.setArgTypes(Collections.<String>singletonList(null));
recipe.setFactoryMethod("init");
ExecutionContext.Holder.setContext(new BlueprintRepository(container));
recipe.create();
}
class TIConverter implements TypeInference.Converter {
public TypeInference.TypedObject convert(TypeInference.TypedObject from, Type to) throws Exception {
Object arg = from.getValue();
arg = converter.convert(arg, new GenericType(to));
return new TypeInference.TypedObject(to, arg);
}
}
public static class FactoryWithList {
public static String init(List<Integer> ints) {
return "Hello!";
}
}
}
| 9,422 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/InterfaceA.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public interface InterfaceA {
}
| 9,423 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PojoGenerics2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PojoGenerics2 {
public static class MyClass<T> {
private final MyObject<? extends T> object;
public MyClass(final MyObject<? extends T> object)
{
this.object = object;
}
}
public static class Tata extends MyClass<String> {
public Tata(MyObject<? extends String> object) {
super(object);
}
}
public static class MyObject<T> {
}
public static class Toto extends MyObject<String> {
}
}
| 9,424 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PojoRecursive.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import org.osgi.service.blueprint.container.BlueprintContainer;
public class PojoRecursive {
private BlueprintContainer container;
private String component;
public PojoRecursive(BlueprintContainer container, String component) {
this.container = container;
this.component = component;
}
public PojoRecursive(BlueprintContainer container, String component, int foo) {
this.container = container;
this.component = component;
container.getComponentInstance(component);
}
public void setFoo(int foo) {
container.getComponentInstance(component);
}
public void init() {
container.getComponentInstance(component);
}
}
| 9,425 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/BeanF.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class BeanF {
private Boolean wrapped;
private Boolean prim;
public BeanF(Boolean wrapped) {
this.wrapped = wrapped;
}
public BeanF(boolean prim) {
this.prim = prim;
}
public Boolean getWrapped() {
return wrapped;
}
public Boolean getPrim() {
return prim;
}
}
| 9,426 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PojoB.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.net.URI;
import java.util.List;
public class PojoB {
private List<Object> objects;
private URI uri;
private int number;
private BeanD bean;
private boolean initCalled;
private boolean destroyCalled;
public PojoB() {
}
public PojoB(URI uri, int number) {
this.uri = uri;
this.number = number;
}
public URI getUri() {
return uri;
}
public void setUri(URI uri) {
this.uri = uri;
}
public List<Object> getObjects() {
return objects;
}
public void setObjects(List<Object> objects) {
this.objects = objects;
}
public void init() {
initCalled = true;
}
public boolean getInitCalled() {
return initCalled;
}
public void destroy() {
destroyCalled = true;
}
public boolean getDestroyCalled() {
return destroyCalled;
}
public int getNumber() {
return number;
}
public BeanD getBean() {
if (bean == null) {
bean = new BeanD();
}
return bean;
}
public static PojoB createStatic(URI uri, int number) {
return new PojoB(URI.create(uri + "-static"), number);
}
public PojoB createDynamic(URI uri, int number) {
return new PojoB(URI.create(uri + "-dynamic"), number);
}
}
| 9,427 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/ConverterA.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.io.File;
import java.net.URI;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.container.Converter;
public class ConverterA implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return (fromValue instanceof String && toType.getRawClass() == File.class)
|| fromValue instanceof PojoB && toType.getRawClass() == URI.class;
}
public Object convert(Object source, ReifiedType toType) throws Exception {
if (source instanceof String) {
return new File((String) source);
} else if (source instanceof PojoB) {
return ((PojoB)source).getUri();
}
throw new Exception("Unable to convert from " + (source != null ? source.getClass().getName() : "<null>") + " to " + File.class.getName());
}
}
| 9,428 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/FITestBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class FITestBean {
private String attr;
private String upperCaseAttr;
private FITestSubBean bean = new FITestSubBean();
public String getAttr() { return attr; }
public String getUpperCaseAttr() { return upperCaseAttr; }
public void setUpperCaseAttr(String val) { upperCaseAttr = val.toUpperCase(); }
public String getBeanName() { return bean.getName(); }
}
| 9,429 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/ListenerA.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import org.osgi.framework.ServiceReference;
public class ListenerA {
public void bind(ServiceReference ref) {
}
public void unbind(ServiceReference ref) {
}
}
| 9,430 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/SimpleBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class SimpleBean {
public static class Nested {
}
}
| 9,431 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PojoC.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class PojoC {
private final Service service;
public PojoC(Service service) {
this.service = service;
}
public Service getService() {
return service;
}
}
| 9,432 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PojoGenerics.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PojoGenerics {
private List<Integer> list;
private Set<Long> set;
private Map<Short, Boolean> map;
public PojoGenerics() {
}
public PojoGenerics(List<Integer> list) {
this.list = list;
}
public PojoGenerics(Set<Long> set) {
this.set = set;
}
public PojoGenerics(Map<Short, Boolean> map) {
this.map = map;
}
public List<Integer> getList() {
return list;
}
public void setList(List<Integer> list) {
this.list = list;
}
public Set<Long> getSet() {
return set;
}
public void setSet(Set<Long> set) {
this.set = set;
}
public Map<Short, Boolean> getMap() {
return map;
}
public void setMap(Map<Short, Boolean> map) {
this.map = map;
}
public void start() {
System.out.println("Starting component " + this);
}
public void stop() {
System.out.println("Stopping component " + this);
}
}
| 9,433 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PrimaveraFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
interface GenericFactory<T,U> {
T getObject();
T getObject(U value);
}
public class PrimaveraFactory implements GenericFactory<Primavera,String> {
public Primavera getObject() {
return new Primavera();
}
public Primavera getObject(String value) {
Primavera res = new Primavera();
res.setProperty(value);
return res;
}
}
| 9,434 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/BeanD.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import org.apache.aries.blueprint.CallbackTracker;
import org.apache.aries.blueprint.CallbackTracker.Callback;
public class BeanD {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void init() {
CallbackTracker.add(new Callback(Callback.INIT, this));
}
public void destroy() {
CallbackTracker.add(new Callback(Callback.DESTROY, this));
}
}
| 9,435 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/NonStandardSetter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class NonStandardSetter {
private String a;
private String b;
public NonStandardSetter() {
}
public String a() {
return this.a;
}
public NonStandardSetter a(String a) {
this.a = a;
return this;
}
public String b() {
return this.b;
}
public NonStandardSetter b(String b) {
this.b = b;
return this;
}
}
| 9,436 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/AmbiguousPojo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.util.List;
public class AmbiguousPojo {
private int sum;
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
public void setSum(List<Integer> numbers) {
this.sum = 0;
for (int i : numbers) {
this.sum += i;
}
}
}
| 9,437 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/Service.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public interface Service {
int getInt();
PojoA getPojoA();
}
| 9,438 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/Multiple.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.util.Map;
import java.util.Properties;
public class Multiple {
private int intValue = -1;
private Integer integerValue = null;
private String stringValue = null;
private Map map;
private Properties properties;
public Multiple() {
}
public Multiple(Map map) {
this.map = map;
}
public Multiple(Properties props, String disambiguator) {
this.properties = props;
}
public Multiple(String arg) {
stringValue = arg;
}
public Multiple(int arg) {
intValue = arg;
}
public Multiple(Integer arg) {
integerValue = arg;
}
public Map getMap() {
return map;
}
public Properties getProperties() {
return properties;
}
public int getInt() {
return intValue;
}
public Integer getInteger() {
return integerValue;
}
public String getString() {
return stringValue;
}
public void setAmbiguous(int v) {
}
public void setAmbiguous(Object v) {
}
public static Multiple create(String arg1, Integer arg2) {
return new Multiple(arg2.intValue());
}
public static Multiple create(String arg1, Boolean arg2) {
return new Multiple(arg1 + "-boolean");
}
}
| 9,439 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PojoListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.util.Map;
import org.osgi.framework.ServiceRegistration;
public class PojoListener {
private ServiceRegistration registration;
public ServiceRegistration getService() {
return registration;
}
public void setService(ServiceRegistration registration) {
this.registration = registration;
}
public void register(PojoB pojo, Map props) {
}
public void unregister(PojoB pojo, Map props) {
}
}
| 9,440 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/ConverterB.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.net.URI;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.container.Converter;
public class ConverterB implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return fromValue instanceof String && toType.getRawClass() == URI.class;
}
public Object convert(Object source, ReifiedType toType) throws Exception {
if (source instanceof String) {
return new URI((String) source);
}
throw new Exception("Unable to convert from " + (source != null ? source.getClass().getName() : "<null>") + " to " + URI.class.getName());
}
} | 9,441 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/VarArg.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class VarArg {
public final String[] args;
public VarArg(String... args) {
this.args = args;
}
}
| 9,442 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/CachePojos.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class CachePojos {
public interface BasicCache<K, V> {
}
public interface Cache<K, V> extends BasicCache<K, V> {
}
public interface CacheContainer extends BasicCacheContainer {
<K, V> Cache<K, V> getCache();
<K, V> Cache<K, V> getCache(String var1);
}
public interface BasicCacheContainer {
<K, V> BasicCache<K, V> getCache();
<K, V> BasicCache<K, V> getCache(String var1);
}
public static class SimpleCacheContainerFactory {
public static CacheContainer create() {
return (CacheContainer) Proxy.newProxyInstance(
SimpleCacheContainerFactory.class.getClassLoader(),
new Class<?>[] { CacheContainer.class },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return new Cache() {};
}
});
}
}
}
| 9,443 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PojoA.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class PojoA implements InterfaceA {
private PojoB pojob;
private List list;
private Set set;
private Map map;
private Number number;
private Properties props;
private Object[] array;
private int[] intArray;
private Number[] numberArray;
public PojoA() {
}
public PojoA(PojoB pojob) {
this.pojob = pojob;
}
public PojoB getPojob() {
return pojob;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Set getSet() {
return set;
}
public void setSet(Set set) {
this.set = set;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public Properties getProps() {
return props;
}
public void setProps(Properties props) {
this.props = props;
}
public void setPojob(PojoB pojob) {
this.pojob = pojob;
}
public void setNumber(Number number) {
this.number = number;
}
public Number getNumber() {
return number;
}
public void setArray(Object[] array) {
this.array = array;
}
public Object[] getArray() {
return array;
}
public int[] getIntArray() {
return intArray;
}
public void setIntArray(int[] array) {
intArray = array;
}
public Number[] getNumberArray() {
return numberArray;
}
public void setNumberArray(Number[] numberArray) {
this.numberArray = numberArray;
}
public void start() {
System.out.println("Starting component " + this);
}
public void stop() {
System.out.println("Stopping component " + this);
}
}
| 9,444 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/BeanE.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import org.apache.aries.blueprint.CallbackTracker;
import org.apache.aries.blueprint.CallbackTracker.Callback;
public class BeanE {
public BeanE(BeanC c) {
}
public void init() {
CallbackTracker.add(new Callback(Callback.INIT, this));
}
public void destroy() {
CallbackTracker.add(new Callback(Callback.DESTROY, this));
}
}
| 9,445 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/PojoCircular.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class PojoCircular {
private PojoCircular circular;
public PojoCircular() {
}
public PojoCircular(PojoCircular circular) {
this.circular = circular;
}
public PojoCircular getCircular() {
return circular;
}
public void setCircular(PojoCircular circular) {
this.circular = circular;
}
public void init() {
}
}
| 9,446 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/BeanC.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import org.apache.aries.blueprint.CallbackTracker;
import org.apache.aries.blueprint.CallbackTracker.Callback;
public class BeanC {
public void init() {
CallbackTracker.add(new Callback(Callback.INIT, this));
}
public void destroy() {
CallbackTracker.add(new Callback(Callback.DESTROY, this));
}
}
| 9,447 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/Overload.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class Overload {
public static class X {
}
public static class Y extends X {
}
public static class A {
private X x;
public X getX() { return x; }
public void setX(X x) { this.x = x; }
}
public static class B extends A {
public void setX(Y y) { super.setX(y); } // Y extends X
}
}
| 9,448 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/DummyServiceTrackerCustomizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
public class DummyServiceTrackerCustomizer implements ServiceTrackerCustomizer<PojoA, PojoB> {
@Override
public PojoB addingService(ServiceReference<PojoA> reference) {
return null;
}
@Override
public void modifiedService(ServiceReference<PojoA> reference, PojoB service) {
}
@Override
public void removedService(ServiceReference<PojoA> reference, PojoB service) {
}
}
| 9,449 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/Primavera.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
interface Product<T> {
void setProperty(T value);
}
public class Primavera implements Product<String> {
public String prop;
public void setProperty(String value) {
prop = value;
}
}
| 9,450 |
0 | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/pojos/FITestSubBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pojos;
public class FITestSubBean {
private String name;
public String getName() {
return name;
}
}
| 9,451 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/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;
/**
* @deprecated - use org.apache.aries.blueprint.services.ExtendedBlueprintContainer
* Will be removed in a future version of Aries Blueprint
*/
@Deprecated
public interface ExtendedBlueprintContainer extends org.apache.aries.blueprint.services.ExtendedBlueprintContainer {
}
| 9,452 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/PassThroughRecipe.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.Collections;
import java.util.List;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
/**
* @version $Rev$ $Date$
*/
public class PassThroughRecipe extends AbstractRecipe {
private Object object;
public PassThroughRecipe(String id, Object object) {
super(id);
this.prototype = false;
this.object = object;
}
protected Object internalCreate() throws ComponentDefinitionException {
return object;
}
public List<Recipe> getDependencies() {
return Collections.emptyList();
}
@Override
public String toString() {
return "EnvironmentRecipe[" +
"name='" + name + '\'' +
", object=" + object +
']';
}
}
| 9,453 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/IdRefRecipe.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.Collections;
import java.util.List;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.NoSuchComponentException;
/*
* The IdRefRecipe is used to inject the reference name into the object (as a String).
* The IdRefRecipe ensures the actual reference object exists before the reference name is injected.
*/
public class IdRefRecipe extends AbstractRecipe {
private String idRef;
public IdRefRecipe(String name, String idRef) {
super(name);
if (idRef == null) throw new NullPointerException("idRef is null");
this.idRef = idRef;
}
public String getIdRef() {
return idRef;
}
public List<Recipe> getDependencies() {
Recipe recipe = ExecutionContext.Holder.getContext().getRecipe(idRef);
if (recipe != null) {
return Collections.singletonList(recipe);
} else {
return Collections.emptyList();
}
}
protected Object internalCreate() throws ComponentDefinitionException {
ExecutionContext context = ExecutionContext.Holder.getContext();
if (!context.containsObject(idRef)) {
throw new NoSuchComponentException(idRef);
}
return idRef;
}
@Override
public String toString() {
return "IdRefRecipe[" +
"name='" + name + '\'' +
", idRef='" + idRef + '\'' +
']';
}
}
| 9,454 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/ArrayRecipe.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
/**
* @version $Rev$ $Date$
*/
public class ArrayRecipe extends AbstractRecipe {
private final List<Recipe> list;
private final Object type;
public ArrayRecipe(String name, Object type) {
super(name);
this.type = type;
this.list = new ArrayList<Recipe>();
}
public List<Recipe> getDependencies() {
List<Recipe> nestedRecipes = new ArrayList<Recipe>(list.size());
for (Recipe recipe : list) {
if (recipe != null) {
nestedRecipes.add(recipe);
}
}
return nestedRecipes;
}
protected Object internalCreate() throws ComponentDefinitionException {
ReifiedType type;
if (this.type instanceof Class) {
type = new ReifiedType((Class) this.type);
} else if (this.type instanceof String) {
type = loadType((String) this.type);
} else {
type = new ReifiedType(Object.class);
}
// create array instance
Object array;
try {
array = Array.newInstance(type.getRawClass(), list.size());
} catch (Exception e) {
throw new ComponentDefinitionException("Error while creating array instance: " + type);
}
int index = 0;
for (Recipe recipe : list) {
Object value;
if (recipe != null) {
try {
value = convert(recipe.create(), type);
} catch (Exception e) {
throw new ComponentDefinitionException("Unable to convert value " + recipe + " to type " + type, e);
}
} else {
value = null;
}
Array.set(array, index, value);
index++;
}
return array;
}
public void add(Recipe value) {
list.add(value);
}
}
| 9,455 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/CollectionRecipe.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
/**
* @version $Rev$ $Date$
*/
public class CollectionRecipe extends AbstractRecipe {
private final List<Recipe> list;
private final Class<?> collectionTypeClass;
private final String defaultValueType;
public CollectionRecipe(String name, Class<?> collectionType, String valueType) {
super(name);
if (collectionType == null) throw new NullPointerException("type is null");
this.collectionTypeClass = collectionType;
this.defaultValueType = (valueType != null) ? valueType : Object.class.getName();
this.list = new ArrayList<Recipe>();
}
public List<Recipe> getDependencies() {
List<Recipe> nestedRecipes = new ArrayList<Recipe>(list.size());
for (Recipe recipe : list) {
if (recipe != null) {
nestedRecipes.add(recipe);
}
}
return nestedRecipes;
}
protected Object internalCreate() throws ComponentDefinitionException {
Class type = getCollection(collectionTypeClass);
if (!ReflectionUtils.hasDefaultConstructor(type)) {
throw new ComponentDefinitionException("Type does not have a default constructor " + type.getName());
}
// create collection instance
Object o;
try {
o = type.newInstance();
} catch (Exception e) {
throw new ComponentDefinitionException("Error while creating collection instance: " + type.getName());
}
if (!(o instanceof Collection)) {
throw new ComponentDefinitionException("Specified collection type does not implement the Collection interface: " + type.getName());
}
Collection instance = (Collection) o;
ReifiedType defaultConversionType = loadType(defaultValueType);
Type conversionType = null;
for (Recipe recipe : list) {
Object value;
if (recipe != null) {
try {
conversionType = defaultConversionType.getRawClass();
if (recipe instanceof ValueRecipe) {
conversionType = ((ValueRecipe) recipe).getValueType();
}
value = convert(recipe.create(), conversionType);
} catch (Exception e) {
throw new ComponentDefinitionException("Unable to convert value " + recipe + " to type " + conversionType, e);
}
} else {
value = null;
}
instance.add(value);
}
return instance;
}
public void add(Recipe value) {
list.add(value);
}
public static Class getCollection(Class type) {
if (ReflectionUtils.hasDefaultConstructor(type)) {
return type;
} else if (SortedSet.class.isAssignableFrom(type)) {
return TreeSet.class;
} else if (Set.class.isAssignableFrom(type)) {
return LinkedHashSet.class;
} else if (List.class.isAssignableFrom(type)) {
return ArrayList.class;
} else if (Queue.class.isAssignableFrom(type)) {
return LinkedList.class;
} else {
return ArrayList.class;
}
}
}
| 9,456 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/CircularDependencyException.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.List;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
public class CircularDependencyException extends ComponentDefinitionException {
private final List<Recipe> circularDependency;
public CircularDependencyException(List<Recipe> circularDependency) {
super(circularDependency.toString());
this.circularDependency = circularDependency;
}
public CircularDependencyException(String message, List<Recipe> circularDependency) {
super(message + ": " + circularDependency);
this.circularDependency = circularDependency;
}
public CircularDependencyException(String message, Throwable cause, List<Recipe> circularDependency) {
super(message + ": " + circularDependency, cause);
this.circularDependency = circularDependency;
}
public CircularDependencyException(Throwable cause, List<Recipe> circularDependency) {
super(circularDependency.toString(), cause);
this.circularDependency = circularDependency;
}
public List<Recipe> getCircularDependency() {
return circularDependency;
}
}
| 9,457 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/ExecutionContext.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.concurrent.Future;
import org.osgi.service.blueprint.container.ReifiedType;
public interface ExecutionContext {
final class Holder {
private static final ThreadLocal<ExecutionContext> context = new ThreadLocal<ExecutionContext>();
private Holder() {
}
public static ExecutionContext getContext() {
ExecutionContext executionContext = context.get();
if (executionContext == null) {
throw new IllegalStateException("Execution container has not been set");
}
return executionContext;
}
public static ExecutionContext setContext(ExecutionContext newContext) {
ExecutionContext oldContext = context.get();
context.set(newContext);
return oldContext;
}
}
/**
* Adds a recipe to the top of the execution stack. If the recipe is already on
* the stack, a CircularDependencyException is thrown.
* @param recipe the recipe to add to the stack
* @throws CircularDependencyException if the recipe is already on the stack
*/
void push(Recipe recipe) throws CircularDependencyException;
/**
* Removes the top recipe from the execution stack.
* @return the top recipe on the stack
*/
Recipe pop();
/**
* Does this context contain a object with the specified name.
*
* @param name the unique name of the object instance
* @return true if this context contain a object with the specified name
*/
boolean containsObject(String name);
/**
* Gets the object or recipe with the specified name from the repository.
*
* @param name the unique name of the object instance
* @return the object instance, a recipe to build the object or null
*/
Object getObject(String name);
/**
* Try to add a full object and return the already registered future if available
* @param name
* @param object
* @return
*/
Future<Object> addFullObject(String name, Future<Object> object);
void addPartialObject(String name, Object object);
Object getPartialObject(String name);
void removePartialObject(String name);
Object convert(Object value, ReifiedType type) throws Exception;
boolean canConvert(Object value, ReifiedType type);
Class loadClass(String className) throws ClassNotFoundException;
Recipe getRecipe(String name);
}
| 9,458 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/MapRecipe.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
/**
* @version $Rev$ $Date$
*/
public class MapRecipe extends AbstractRecipe {
private final List<Recipe[]> entries;
private final Class<?> typeClass;
private final Object keyType;
private final Object valueType;
public MapRecipe(String name, Class<?> type, Object keyType, Object valueType) {
super(name);
if (type == null) throw new NullPointerException("type is null");
this.typeClass = type;
this.entries = new ArrayList<Recipe[]>();
this.keyType = keyType;
this.valueType = valueType;
}
public List<Recipe> getDependencies() {
List<Recipe> nestedRecipes = new ArrayList<Recipe>(entries.size() * 2);
for (Recipe[] entry : entries) {
nestedRecipes.add(entry[0]);
if (entry[1] != null) {
nestedRecipes.add(entry[1]);
}
}
return nestedRecipes;
}
private ReifiedType getType(Object o) {
ReifiedType type;
if (o instanceof Class) {
type = new ReifiedType((Class) o);
} else if (o instanceof String) {
type = loadType((String) o);
} else {
type = new ReifiedType(Object.class);
}
return type;
}
protected Object internalCreate() throws ComponentDefinitionException {
Class<?> mapType = getMap(typeClass);
if (!ReflectionUtils.hasDefaultConstructor(mapType)) {
throw new ComponentDefinitionException("Type does not have a default constructor " + mapType.getName());
}
Object o;
try {
o = mapType.newInstance();
} catch (Exception e) {
throw new ComponentDefinitionException("Error while creating set instance: " + mapType.getName());
}
Map instance;
if (o instanceof Map) {
instance = (Map) o;
} else if (o instanceof Dictionary) {
instance = new DummyDictionaryAsMap((Dictionary) o);
} else {
throw new ComponentDefinitionException("Specified map type does not implement the Map interface: " + mapType.getName());
}
ReifiedType defaultConvertKeyType = getType(keyType);
ReifiedType defaultConvertValueType = getType(valueType);
// add map entries
try {
for (Recipe[] entry : entries) {
ReifiedType convertKeyType = workOutConversionType(entry[0], defaultConvertKeyType);
Object key = convert(entry[0].create(), convertKeyType);
// Each entry may have its own types
ReifiedType convertValueType = workOutConversionType(entry[1], defaultConvertValueType);
Object value = entry[1] != null ? convert(entry[1].create(), convertValueType) : null;
instance.put(key, value);
}
} catch (Exception e) {
throw new ComponentDefinitionException(e);
}
return instance;
}
protected ReifiedType workOutConversionType(Recipe entry, ReifiedType defaultType) {
if (entry instanceof ValueRecipe) {
return getType(((ValueRecipe) entry).getValueType());
} else {
return defaultType;
}
}
public void put(Recipe key, Recipe value) {
if (key == null) throw new NullPointerException("key is null");
entries.add(new Recipe[]{key, value});
}
public void putAll(Map<Recipe, Recipe> map) {
if (map == null) throw new NullPointerException("map is null");
for (Map.Entry<Recipe, Recipe> entry : map.entrySet()) {
Recipe key = entry.getKey();
Recipe value = entry.getValue();
put(key, value);
}
}
public static Class<?> getMap(Class<?> type) {
if (ReflectionUtils.hasDefaultConstructor(type)) {
return type;
} else if (SortedMap.class.isAssignableFrom(type)) {
return TreeMap.class;
} else if (ConcurrentMap.class.isAssignableFrom(type)) {
return ConcurrentHashMap.class;
} else {
return LinkedHashMap.class;
}
}
public static class DummyDictionaryAsMap extends AbstractMap {
private final Dictionary dictionary;
public DummyDictionaryAsMap(Dictionary dictionary) {
this.dictionary = dictionary;
}
@Override
public Object put(Object key, Object value) {
return dictionary.put(key, value);
}
public Set entrySet() {
throw new UnsupportedOperationException();
}
}
}
| 9,459 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/ComponentFactoryRecipe.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.List;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.ext.ComponentFactoryMetadata;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
/**
* Pass-through recipe that allows custom bean manager (represented by a ComponentFactoryMetadata instance)
* to fit into the container lifecycle.
*
* @param <T>
*/
public class ComponentFactoryRecipe<T extends ComponentFactoryMetadata> extends AbstractRecipe {
private T metadata;
private List<Recipe> dependencies;
public ComponentFactoryRecipe(String name, T metadata,
ExtendedBlueprintContainer container, List<Recipe> dependencies) {
super(name);
this.metadata = metadata;
this.dependencies = dependencies;
metadata.init(container);
}
@Override
protected Object internalCreate() throws ComponentDefinitionException {
return metadata.create();
}
public List<Recipe> getDependencies() {
return dependencies;
}
@Override
public void destroy(Object instance) {
metadata.destroy(instance);
}
protected T getMetadata() {
return metadata;
}
}
| 9,460 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/Repository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
public interface Repository {
/**
* Returns the set of all known object names (recipes, instances or default objects)
* @return
*/
Set<String> getNames();
/**
* Return the singleton instance for the given name.
* This method will not create the object if it has not been created yet.
*
* @param name
* @return the instance or <code>null</code>
*/
Object getInstance(String name);
/**
* Return the recipe for the given name.
*
* @param name
* @return the recipe or <code>null</code>
*/
Recipe getRecipe(String name);
void putRecipe(String name, Recipe recipe);
/**
* Remove an uninstantiated recipe
* @param name
* @throws ComponentDefinitionException if the recipe is already instantiated
*/
void removeRecipe(String name);
Object create(String name) throws ComponentDefinitionException;
Object create(String name, Collection<Class<?>> proxyInterfaces) throws ComponentDefinitionException;
void createAll(Collection<String> names) throws ComponentDefinitionException;
Map<String, Object> createAll(Collection<String> names, Collection<Class<?>> proxyInterfaces) throws ComponentDefinitionException;
<T> List<T> getAllRecipes(Class<T> clazz, String... names);
Set<Recipe> getAllRecipes(String... names);
void destroy();
}
| 9,461 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/Recipe.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.List;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
/**
* The <code>Recipe</code> interface abstracts the creation of objects
*
* @version $Rev$ $Date$
*/
public interface Recipe {
/**
* Get the unique name for this recipe.
*
* @return the unique name for this recipe.
*/
String getName();
/**
* Get the list of constructor dependencies, i.e. explicit and
* argument dependencies. These dependencies must be satisfied
* before the an object can be created.
*
* @return a list of constructor dependencies
*/
List<Recipe> getConstructorDependencies();
/**
* Get the list of nested recipes, i.e. all dependencies including
* constructor dependencies.
*
* @return a list of dependencies
*/
List<Recipe> getDependencies();
/**
* Create an instance for this recipe.
*
* @return a new instance for this recipe
* @throws ComponentDefinitionException
*/
Object create() throws ComponentDefinitionException;
/**
* Destroy an instance created by this recipe
*
* @param instance the instance to be destroyed
*/
void destroy(Object instance);
}
| 9,462 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/RefRecipe.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.Collections;
import java.util.List;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.NoSuchComponentException;
public class RefRecipe extends AbstractRecipe {
private String idRef;
public RefRecipe(String name, String idRef) {
super(name);
this.idRef = idRef;
}
public String getIdRef() {
return idRef;
}
public void setIdRef(String name) {
this.idRef = name;
}
public List<Recipe> getDependencies() {
Recipe recipe = ExecutionContext.Holder.getContext().getRecipe(idRef);
if (recipe != null) {
return Collections.singletonList(recipe);
} else {
return Collections.emptyList();
}
}
protected Object internalCreate() throws ComponentDefinitionException {
ExecutionContext context = ExecutionContext.Holder.getContext();
if (!context.containsObject(idRef)) {
throw new NoSuchComponentException(idRef);
}
Object instance = context.getObject(idRef);
if (instance instanceof Recipe) {
Recipe recipe = (Recipe) instance;
//We do not convert this, it might be an unwrappered bean, but we don't know what type
//it needs to be yet. The property setter or factory-ref in the Bean recipe will do this will do this
instance = recipe.create();
}
return instance;
}
@Override
public String toString() {
return "RefRecipe[" +
"name='" + name + '\'' +
", idRef='" + idRef + '\'' +
']';
}
}
| 9,463 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/AbstractRecipe.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import org.apache.aries.blueprint.container.GenericType;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.ReifiedType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractRecipe implements Recipe {
private static final Logger LOGGER = LoggerFactory
.getLogger(AbstractRecipe.class);
protected final String name;
protected boolean prototype = true;
protected AbstractRecipe(String name) {
if (name == null)
throw new NullPointerException("name is null");
this.name = name;
}
public String getName() {
return name;
}
public boolean isPrototype() {
return prototype;
}
public void setPrototype(boolean prototype) {
this.prototype = prototype;
}
public final Object create() throws ComponentDefinitionException {
// Ensure a container has been set
ExecutionContext context = ExecutionContext.Holder.getContext();
// if this recipe has already been executed in this context, return the
// currently registered value
Object result = context.getPartialObject(name);
if (result != null) {
return result;
}
// execute the recipe
context.push(this);
boolean didCreate = false;
try {
if (!prototype) {
FutureTask<Object> objectCreation = new FutureTask<Object>(
new Callable<Object>() {
public Object call()
throws ComponentDefinitionException {
return internalCreate();
}
});
Future<Object> resultFuture = context.addFullObject(name,
objectCreation);
// are we the first to try to create it
if (resultFuture == null) {
didCreate = true;
objectCreation.run();
resultFuture = objectCreation;
}
try {
result = resultFuture.get();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
} catch (ExecutionException ee) {
if (ee.getCause() instanceof ComponentDefinitionException)
throw (ComponentDefinitionException) ee.getCause();
else if (ee.getCause() instanceof RuntimeException)
throw (RuntimeException) ee.getCause();
else
throw (Error) ee.getCause();
}
} else {
result = internalCreate();
}
} finally {
if (didCreate)
context.removePartialObject(name);
Recipe popped = context.pop();
if (popped != this) {
// noinspection ThrowFromFinallyBlock
throw new IllegalStateException(
"Internal Error: recipe stack is corrupt:"
+ " Expected " + this
+ " to be popped of the stack but was "
+ popped);
}
}
return result;
}
protected abstract Object internalCreate()
throws ComponentDefinitionException;
protected void addPartialObject(Object obj) {
if (!prototype) {
ExecutionContext.Holder.getContext().addPartialObject(name, obj);
}
}
protected boolean canConvert(Object obj, ReifiedType type) {
return ExecutionContext.Holder.getContext().canConvert(obj, type);
}
protected Object convert(Object obj, ReifiedType type) throws Exception {
return ExecutionContext.Holder.getContext().convert(obj, type);
}
protected Object convert(Object obj, Type type) throws Exception {
return ExecutionContext.Holder.getContext().convert(obj, new GenericType(type));
}
protected Class loadClass(String className) {
ReifiedType t = loadType(className, null);
return t != null ? t.getRawClass() : null;
}
protected ReifiedType loadType(String typeName) {
return loadType(typeName, null);
}
protected ReifiedType loadType(String typeName, ClassLoader fromClassLoader) {
if (typeName == null) {
return null;
}
return doLoadType(typeName, fromClassLoader, true, false);
}
private ReifiedType doLoadType(String typeName,
ClassLoader fromClassLoader, boolean checkNestedIfFailed,
boolean retry) {
try {
return GenericType.parse(typeName,
fromClassLoader != null ? fromClassLoader
: ExecutionContext.Holder.getContext());
} catch (ClassNotFoundException e) {
String errorMessage = "Unable to load class " + typeName
+ " from recipe " + this;
if (checkNestedIfFailed) {
int lastDot = typeName.lastIndexOf('.');
if (lastDot > 0 && lastDot < typeName.length()) {
String nestedTypeName = typeName.substring(0, lastDot)
+ "$" + typeName.substring(lastDot + 1);
LOGGER.debug(errorMessage
+ ", trying to load a nested class "
+ nestedTypeName);
try {
return doLoadType(nestedTypeName, fromClassLoader,
false, true);
} catch (ComponentDefinitionException e2) {
// ignore, the recursive call will throw this exception,
// but ultimately the exception referencing the original
// typeName has to be thrown
}
}
}
if (!retry) {
LOGGER.error(errorMessage);
}
throw new ComponentDefinitionException(errorMessage, e);
}
}
public void destroy(Object instance) {
}
public List<Recipe> getConstructorDependencies() {
return Collections.emptyList();
}
public String toString() {
return getClass().getSimpleName() + "[" + "name='" + name + '\'' + ']';
}
}
| 9,464 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/DependentComponentFactoryRecipe.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.container.SatisfiableRecipe;
import org.apache.aries.blueprint.ext.DependentComponentFactoryMetadata;
/**
* Extends ComponentFactoryRecipe to support the dependency management (SatisfiableRecipe) for custom
* bean managers (DependentComponentFactoryMetadata instances in this case).
*/
public class DependentComponentFactoryRecipe extends ComponentFactoryRecipe<DependentComponentFactoryMetadata>
implements SatisfiableRecipe, DependentComponentFactoryMetadata.SatisfactionCallback {
private SatisfactionListener listener;
private AtomicBoolean started = new AtomicBoolean(false);
public DependentComponentFactoryRecipe(
String name, DependentComponentFactoryMetadata metadata,
ExtendedBlueprintContainer container, List<Recipe> dependencies) {
super(name, metadata, container, dependencies);
}
@Override
public boolean isStaticLifecycle() {
return false;
}
public String getOsgiFilter() {
return getMetadata().getDependencyDescriptor();
}
public boolean isSatisfied() {
return getMetadata().isSatisfied();
}
public void start(SatisfactionListener listener) {
if (started.compareAndSet(false, true)) {
this.listener = listener;
getMetadata().startTracking(this);
}
}
public void stop() {
if (started.compareAndSet(true, false)) {
listener = null;
getMetadata().stopTracking();
}
}
public void notifyChanged() {
if (listener != null) {
listener.notifySatisfaction(this);
}
}
}
| 9,465 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/ValueRecipe.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.di;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import org.apache.aries.blueprint.ExtendedValueMetadata;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* This recipe will be used to create an object from a ValueMetadata.
* We need to keep the reference to the ValueMetadata so that we can lazily retrieve
* the value, allowing for placeholders or such to be used at the last moment.
*
* @version $Rev$, $Date$
*/
public class ValueRecipe extends AbstractRecipe {
private final ValueMetadata value;
private final Object type;
public ValueRecipe(String name, ValueMetadata value, Object type) {
super(name);
this.value = value;
this.type = type;
}
public List<Recipe> getDependencies() {
return Collections.emptyList();
}
@Override
protected Object internalCreate() throws ComponentDefinitionException {
try {
Type type = getValueType();
Object v = null;
if (value instanceof ExtendedValueMetadata) {
v = ((ExtendedValueMetadata) value).getValue();
}
if (v == null) {
v = value.getStringValue();
}
return convert(v, type);
} catch (Exception e) {
throw new ComponentDefinitionException(e);
}
}
protected Type getValueType() {
Type type = Object.class;
if (this.type instanceof Type) {
type = (Type) this.type;
} else if (this.type instanceof String) {
type = loadClass((String) this.type);
}
return type;
}
@Override
public String toString() {
return "ValueRecipe[" +
"name='" + name + '\'' +
", value=" + value +
", type=" + type +
']';
}
}
| 9,466 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/SingleInterceptorCollaborator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.apache.aries.blueprint.Interceptor;
import org.apache.aries.proxy.InvocationListener;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A collaborator which ensures preInvoke and postInvoke occur before and after
* method invocation
*/
public class SingleInterceptorCollaborator implements InvocationListener, Serializable {
/** Serial version UID for this class */
private static final long serialVersionUID = -58189302118314469L;
private static final Logger LOGGER = LoggerFactory
.getLogger(Collaborator.class);
private transient Interceptor interceptor;
private transient ComponentMetadata cm;
private static final Object NON_INVOKED = new Object();
public SingleInterceptorCollaborator(ComponentMetadata cm, Interceptor interceptor) {
this.cm = cm;
this.interceptor = interceptor;
}
/**
* Invoke the preCall method on the interceptor
*/
public Object preInvoke(Object o, Method m, Object[] parameters)
throws Throwable {
Object callToken = NON_INVOKED;
try {
callToken = interceptor.preCall(cm, m, parameters);
} catch (Throwable t) {
// using null token here to be consistent with what Collaborator does
postInvokeExceptionalReturn(null, o, m, t);
throw t;
}
return callToken;
}
/**
* Called when the method is called and returned normally
*/
public void postInvoke(Object token, Object o, Method method,
Object returnType) throws Throwable {
if (token != NON_INVOKED) {
try {
interceptor.postCallWithReturn(cm, method, returnType, token);
} catch (Throwable t) {
LOGGER.debug("postCallInterceptorWithReturn", t);
throw t;
}
}
}
/**
* Called when the method is called and returned with an exception
*/
public void postInvokeExceptionalReturn(Object token, Object o, Method method,
Throwable exception) throws Throwable {
try {
interceptor.postCallWithException(cm, method, exception, token);
} catch (Throwable t) {
// log the exception
LOGGER.debug("postCallInterceptorWithException", t);
throw t;
}
}
} | 9,467 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/CollaboratorFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy;
import org.apache.aries.blueprint.Interceptor;
import org.apache.aries.proxy.InvocationListener;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import java.util.List;
public class CollaboratorFactory {
public static InvocationListener create(ComponentMetadata componentMetadata, List<Interceptor> interceptors) {
if (interceptors.size() == 1) {
return new SingleInterceptorCollaborator(componentMetadata, interceptors.get(0));
} else {
return new Collaborator(componentMetadata, interceptors);
}
}
}
| 9,468 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/Collaborator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import org.apache.aries.blueprint.Interceptor;
import org.apache.aries.proxy.InvocationListener;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A collaborator which ensures preInvoke and postInvoke occur before and after
* method invocation
*/
public class Collaborator implements InvocationListener, Serializable {
/** Serial version UID for this class */
private static final long serialVersionUID = -58189302118314469L;
private static final Logger LOGGER = LoggerFactory
.getLogger(Collaborator.class);
private transient List<Interceptor> interceptors = null;
private transient ComponentMetadata cm = null;
public Collaborator(ComponentMetadata cm, List<Interceptor> interceptors) {
this.cm = cm;
this.interceptors = interceptors;
}
/**
* Invoke the preCall method on the interceptor
*
* @param o : The Object being invoked
* @param m : method
* @param parameters : method paramters
* @throws Throwable
*/
public Object preInvoke(Object o, Method m, Object[] parameters)
throws Throwable {
Deque<StackElement> stack = new ArrayDeque<StackElement>(interceptors.size());
if (interceptors != null) {
try {
for (Interceptor im : interceptors) {
Collaborator.StackElement se = new StackElement(im);
// should we do this before or after the preCall ?
stack.push(se);
// allow exceptions to propagate
se.setPreCallToken(im.preCall(cm, m, parameters));
}
} catch (Throwable t) {
postInvokeExceptionalReturn(stack, o, m, t);
throw t;
}
}
return stack;
}
/**
* Called when the method is called and returned normally
*/
public void postInvoke(Object token, Object o, Method method,
Object returnType) throws Throwable {
Deque<StackElement> calledInterceptors =
(Deque<StackElement>) token;
if (calledInterceptors != null) {
while (!calledInterceptors.isEmpty()) {
Collaborator.StackElement se = calledInterceptors.pop();
try {
se.interceptor.postCallWithReturn(cm, method, returnType, se
.getPreCallToken());
} catch (Throwable t) {
LOGGER.debug("postCallInterceptorWithReturn", t);
// propagate this to invoke ... further interceptors will be
// called via the postCallInterceptorWithException method
throw t;
}
} // end while
}
}
/**
* Called when the method is called and returned with an exception
*/
public void postInvokeExceptionalReturn(Object token, Object o, Method method,
Throwable exception) throws Throwable {
Throwable tobeRethrown = null;
Deque<StackElement> calledInterceptors =
(Deque<StackElement>) token;
while (!calledInterceptors.isEmpty()) {
Collaborator.StackElement se = calledInterceptors.pop();
try {
se.interceptor.postCallWithException(cm, method, exception, se
.getPreCallToken());
} catch (Throwable t) {
// log the exception
LOGGER.debug("postCallInterceptorWithException", t);
if (tobeRethrown == null) {
tobeRethrown = t;
} else {
LOGGER.warn("Discarding post-call with interceptor exception", t);
}
}
} // end while
if (tobeRethrown != null)
throw tobeRethrown;
}
// info to store on interceptor stack during invoke
private static class StackElement {
private final Interceptor interceptor;
private Object preCallToken;
private StackElement(Interceptor i) {
interceptor = i;
}
private void setPreCallToken(Object preCallToken) {
this.preCallToken = preCallToken;
}
private Object getPreCallToken() {
return preCallToken;
}
}
} | 9,469 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/ProxyUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class ProxyUtils {
public static final Callable<Object> passThrough(final Object target) {
return new Callable<Object>() {
public Object call() throws Exception {
return target;
}
};
}
public static final List<Class<?>> asList(Class<?>... classesArray) {
List<Class<?>> classes = new ArrayList<Class<?>>();
for (Class<?> clazz : classesArray) {
classes.add(clazz);
}
return classes;
}
public static final List<Class<?>> asList(Class<?> clazz) {
List<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(clazz);
return classes;
}
}
| 9,470 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext/AbstractPropertyPlaceholderExt.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 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.*;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Abstract class for property placeholders.
*
* @version $Rev$, $Date$
*/
public abstract class AbstractPropertyPlaceholderExt extends PropertyPlaceholder implements ComponentDefinitionRegistryProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPropertyPlaceholderExt.class);
private String placeholderPrefix = "${";
private String placeholderSuffix = "}";
private String nullValue = null;
private Pattern pattern;
private LinkedList<String> processingStack = new LinkedList<String>();
private Bundle blueprintBundle;
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 void process(ComponentDefinitionRegistry registry) throws ComponentDefinitionException {
try {
blueprintBundle = (Bundle) ((PassThroughMetadata)registry.getComponentDefinition("blueprintBundle")).getObject();
for (String name : registry.getComponentDefinitionNames()) {
processMetadata(registry.getComponentDefinition(name));
}
} finally {
processingStack.clear();
blueprintBundle = null;
}
}
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 ReferenceListMetadata) {
ReferenceListMetadata rlmd = (ReferenceListMetadata) metadata;
processingStack.add("Reference List named " + rlmd.getId() + "->");
return processRefCollectionMetadata(rlmd);
} else if (metadata instanceof ReferenceMetadata) {
ReferenceMetadata rmd = (ReferenceMetadata) metadata;
processingStack.add("Reference named " + rmd.getId() + "->");
return processReferenceMetadata(rmd);
} else if (metadata instanceof ServiceMetadata) {
ServiceMetadata smd = (ServiceMetadata) metadata;
processingStack.add("Service named " + smd.getId() + "->");
return processServiceMetadata(smd);
} 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 processServiceMetadata(ServiceMetadata component) {
try {
if(component instanceof MutableServiceMetadata) {
processingStack.add("Service Component->");
((MutableServiceMetadata) component).setServiceComponent(
(Target) processMetadata(component.getServiceComponent()));
} else {
printWarning(component, "Service Component");
processingStack.add("Service Component->");
processMetadata(component.getServiceComponent());
}
} finally {
processingStack.removeLast();
}
List<MapEntry> entries = new ArrayList<MapEntry>(component.getServiceProperties());
if(!!! entries.isEmpty()) {
try {
if(component instanceof MutableServiceMetadata) {
processingStack.add("Service Properties->");
MutableServiceMetadata msm = (MutableServiceMetadata) component;
for (MapEntry entry : entries) {
msm.removeServiceProperty(entry);
}
for (MapEntry entry : processMapEntries(entries)) {
msm.addServiceProperty(entry);
}
} else {
printWarning(component, "Service Properties");
processingStack.add("Service Properties->");
processMapEntries(entries);
}
} finally {
processingStack.removeLast();
}
}
for (RegistrationListener listener : component.getRegistrationListeners()) {
Target listenerComponent = listener.getListenerComponent();
try {
processingStack.add("Registration Listener " + listenerComponent + "->");
if(listener instanceof MutableRegistrationListener) {
((MutableRegistrationListener) listener).setListenerComponent((Target) processMetadata(listenerComponent));
} else {
//Say that we can't change this listener, but continue processing
//If the value is mutable then we may be ok!
printWarning(listener, "Service Registration Listener");
processMetadata(listenerComponent);
}
} finally {
processingStack.removeLast();
}
}
return component;
}
protected Metadata processReferenceMetadata(ReferenceMetadata component) {
return processServiceReferenceMetadata(component);
}
protected Metadata processRefCollectionMetadata(ReferenceListMetadata component) {
return processServiceReferenceMetadata(component);
}
private Metadata processServiceReferenceMetadata(ServiceReferenceMetadata component) {
if (component instanceof MutableServiceReferenceMetadata) {
ValueMetadata valueMetadata = ((MutableServiceReferenceMetadata) component).getExtendedFilter();
if (valueMetadata != null) {
((MutableServiceReferenceMetadata) component).setExtendedFilter(
doProcessValueMetadata(valueMetadata));
}
}
for (ReferenceListener listener : component.getReferenceListeners()) {
Target listenerComponent = listener.getListenerComponent();
try {
processingStack.add("Reference Listener " + listenerComponent + "->");
if(listener instanceof MutableReferenceListener) {
((MutableReferenceListener) listener).setListenerComponent((Target) processMetadata(listenerComponent));
} else {
//Say that we can't change this listener, but continue processing
//If the value is mutable then we may be ok!
printWarning(listener, "Reference Binding Listener");
processMetadata(listenerComponent);
}
} 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 doProcessValueMetadata(metadata);
}
protected ValueMetadata doProcessValueMetadata(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(" in bundle ").append(blueprintBundle.getSymbolicName()).append("/")
.append(blueprintBundle.getVersion()).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,471 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/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.Map;
import org.apache.aries.blueprint.ComponentDefinitionRegistryProcessor;
/**
* Abstract class for property placeholders. Kept for compatibility purposes.
* See: ARIES-1858 and CAMEL-12570
*
* @version $Rev$, $Date$
*/
public abstract class AbstractPropertyPlaceholder implements ComponentDefinitionRegistryProcessor {
protected abstract Object retrieveValue(String text);
public abstract Map<String, Object> getDefaultProperties();
}
| 9,472 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext/PropertyPlaceholderExt.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.ext.evaluator.PropertyEvaluator;
import org.apache.aries.blueprint.ext.evaluator.PropertyEvaluatorExt;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.felix.utils.properties.Properties;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Property placeholder that looks for properties in the System properties.
*
* @version $Rev$, $Date$
*/
public class PropertyPlaceholderExt extends AbstractPropertyPlaceholderExt {
public enum SystemProperties {
never,
fallback,
override
}
private static final Logger LOGGER = LoggerFactory.getLogger(PropertyPlaceholderExt.class);
private Map<String, Object> defaultProperties;
private Properties properties;
private List<URL> locations;
private boolean ignoreMissingLocations;
private SystemProperties systemProperties = SystemProperties.fallback;
private PropertyEvaluatorExt evaluator = null;
private ExtendedBlueprintContainer container;
public Map<String, Object> getDefaultProperties() {
return defaultProperties;
}
public void setDefaultProperties(Map<String, Object> defaultProperties) {
this.defaultProperties = defaultProperties;
}
public List<URL> getLocations() {
return locations;
}
public void setLocations(List<URL> 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 (URL url : locations) {
InputStream is = null;
try {
is = 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();
}
}
}
}
}
@Override
public void process(ComponentDefinitionRegistry registry) throws ComponentDefinitionException {
container = (ExtendedBlueprintContainer) ((PassThroughMetadata) registry.getComponentDefinition("blueprintContainer")).getObject();
super.process(registry);
}
protected Object getProperty(String val) {
LOGGER.debug("Retrieving property {}", val);
Object v = null;
if (v == null && systemProperties == SystemProperties.override) {
v = getSystemProperty(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 = getSystemProperty(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;
}
protected String getSystemProperty(String val) {
if (val.startsWith("env:")) {
return System.getenv(val.substring("env:".length()));
}
if (val.startsWith("static:")) {
val = val.substring("static:".length());
int idx = val.indexOf('#');
if (idx <= 0 || idx == val.length() - 1) {
throw new IllegalArgumentException("Bad syntax: " + val);
}
String clazz = val.substring(0, idx);
String name = val.substring(idx + 1);
try {
Class cl = container.loadClass(clazz);
Field field = null;
try {
field = cl.getField(name);
} catch (NoSuchFieldException e) {
while (field == null && cl != null) {
try {
field = cl.getDeclaredField(name);
} catch (NoSuchFieldException t) {
cl = cl.getSuperclass();
}
}
}
if (field == null) {
throw new NoSuchFieldException(name);
}
Object obj = field.get(null);
return obj != null ? obj.toString() : null;
} catch (Throwable t) {
LOGGER.warn("Unable to retrieve static field: " + val + " (" + t + ")");
}
}
return System.getProperty(val);
}
@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,473 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext/PlaceholdersUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.ExtendedBeanMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
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.ComponentMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* Utility for placeholders parsing / validation
*
* @version $Rev$, $Date$
*/
public class PlaceholdersUtils {
public static void validatePlaceholder(MutableBeanMetadata metadata, ComponentDefinitionRegistry registry) {
String prefix = getPlaceholderProperty(metadata, "placeholderPrefix");
String suffix = getPlaceholderProperty(metadata, "placeholderSuffix");
for (String id : registry.getComponentDefinitionNames()) {
ComponentMetadata component = registry.getComponentDefinition(id);
if (component instanceof ExtendedBeanMetadata) {
ExtendedBeanMetadata bean = (ExtendedBeanMetadata) component;
if (bean.getRuntimeClass() != null && AbstractPropertyPlaceholderExt.class.isAssignableFrom(bean.getRuntimeClass())) {
String otherPrefix = getPlaceholderProperty(bean, "placeholderPrefix");
String otherSuffix = getPlaceholderProperty(bean, "placeholderSuffix");
if (prefix.equals(otherPrefix) && suffix.equals(otherSuffix)) {
throw new ComponentDefinitionException("Multiple placeholders with the same prefix and suffix are not allowed");
}
}
}
}
}
private static String getPlaceholderProperty(BeanMetadata bean, String name) {
for (BeanProperty property : bean.getProperties()) {
if (name.equals(property.getName())) {
ValueMetadata value = (ValueMetadata) property.getValue();
return value.getStringValue();
}
}
return null;
}
}
| 9,474 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/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;
/**
* Property placeholder that looks for properties in the System properties. Kept for compatibility purposes.
* See: ARIES-1858 and CAMEL-12570
*
* @version $Rev$, $Date$
*/
public abstract class PropertyPlaceholder extends AbstractPropertyPlaceholder {
}
| 9,475 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext/ComponentFactoryMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Target;
/**
* Custom metadata that can acts like a built-in bean manager
* for the component life-cycle events create and destroy.
*/
public interface ComponentFactoryMetadata extends ComponentMetadata, Target {
/**
* Prime the underlying bean manager with the blueprint container
* @param container
*/
void init(ExtendedBlueprintContainer container);
/**
* Create an instance
* @return
* @throws ComponentDefinitionException
*/
Object create() throws ComponentDefinitionException;
/**
* Destroy an instance previously created
* @param instance
*/
void destroy(Object instance);
}
| 9,476 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext/DependentComponentFactoryMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* Metadata for custom components that need to plug in to the
* Blueprint container lifecycle for beans
*/
public interface DependentComponentFactoryMetadata extends ComponentFactoryMetadata {
/**
* Interface that allows to notify the container when the dependencies of the component
* become satisfied or unsatified.
*/
interface SatisfactionCallback {
/**
* Alert the container that the satisfaction status has changed. isSatisfied() should reflect this.
*/
void notifyChanged();
}
/**
* Start tracking the dependencies for this component.
* @param observer The container callback for alerting the container of status changes
*/
void startTracking(SatisfactionCallback observer);
/**
* Stop tracking the dependencies for this component.
*/
void stopTracking();
/**
* Return a string representation of the dependencies of this component. This will be used
* in diagnostics as well as the GRACE_PERIOD event.
* @return
*/
String getDependencyDescriptor();
/**
* Are all dependencies of this component satisfied?
* @return
*/
boolean isSatisfied();
}
| 9,477 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext | Create_ds/aries/blueprint/blueprint-core/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.ExtendedReferenceListMetadata;
import org.apache.aries.blueprint.ExtendedReferenceMetadata;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.container.NullProxy;
import org.apache.aries.blueprint.ext.PlaceholdersUtils;
import org.apache.aries.blueprint.ext.PropertyPlaceholderExt;
import org.apache.aries.blueprint.ext.evaluator.PropertyEvaluatorExt;
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.framework.BundleContext;
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";
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 Logger LOGGER = LoggerFactory.getLogger(ExtNamespaceHandler.class);
private int idCounter;
private BundleContext ctx;
public void setBundleContext(BundleContext bc) {
this.ctx = bc;
}
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(
PropertyPlaceholderExt.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, REFERENCE)) {
RefMetadata rd = context.parseElement(RefMetadata.class, context.getEnclosingComponent(), element);
return createReference(context, rd.getComponentId());
} 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 Element && nodeNameEquals(node, REFERENCE)) {
RefMetadata rd = context.parseElement(RefMetadata.class, component, (Element) node);
return createReference(context, rd.getComponentId());
} 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(PropertyPlaceholderExt.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));
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) {
metadata.addProperty("evaluator", createReference(context, evaluator));
}
// 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));
}
PlaceholdersUtils.validatePlaceholder(metadata, context.getComponentDefinitionRegistry());
return metadata;
}
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 MutableReferenceMetadata createReference(ParserContext context, String value) {
MutableReferenceMetadata m = context.createMetadata(MutableReferenceMetadata.class);
// use the class instance directly rather than loading the class from the specified the interface name.
m.setRuntimeInterface(PropertyEvaluatorExt.class);
m.setFilter("(org.apache.aries.blueprint.ext.evaluator.name=" + value + ")");
m.setBundleContext(ctx);
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,478 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext/evaluator/PropertyEvaluator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.evaluator;
import java.util.Dictionary;
@Deprecated
public interface PropertyEvaluator {
String evaluate(String expression, Dictionary<String, String> properties);
}
| 9,479 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext/evaluator/PropertyEvaluatorExt.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.evaluator;
import java.util.Map;
public interface PropertyEvaluatorExt {
Object evaluate(String expression, Map<String, Object> properties);
}
| 9,480 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/namespace/NamespaceHandlerRegistryImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.namespace;
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import static javax.xml.XMLConstants.XML_NS_URI;
import static org.apache.aries.blueprint.parser.Parser.BLUEPRINT_NAMESPACE;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
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.ParserContext;
import org.apache.aries.blueprint.container.NamespaceHandlerRegistry;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.SAXException;
/**
* Default implementation of the NamespaceHandlerRegistry.
*
* This registry will track NamespaceHandler objects in the OSGi registry and make
* them available, calling listeners when handlers are registered or unregistered.
*
* @version $Rev$, $Date$
*/
public class NamespaceHandlerRegistryImpl implements NamespaceHandlerRegistry, ServiceTrackerCustomizer {
public static final String NAMESPACE = "osgi.service.blueprint.namespace";
private static final Logger LOGGER = LoggerFactory.getLogger(NamespaceHandlerRegistryImpl.class);
// The bundle context is thread safe
private final BundleContext bundleContext;
// The service tracker is thread safe
private final ServiceTracker tracker;
// The handlers map is concurrent
private final ConcurrentHashMap<URI, CopyOnWriteArraySet<NamespaceHandler>> handlers =
new ConcurrentHashMap<URI, CopyOnWriteArraySet<NamespaceHandler>>();
// Access to the LRU schemas map is synchronized on itself
private final LRUMap<Map<URI, NamespaceHandler>, Reference<Schema>> schemas =
new LRUMap<Map<URI, NamespaceHandler>, Reference<Schema>>(10);
// Access to this factory is synchronized on itself
private final SchemaFactory schemaFactory =
SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
// Access to this variable is must be synchronized on itself
private final ArrayList<NamespaceHandlerSetImpl> sets =
new ArrayList<NamespaceHandlerSetImpl>();
public NamespaceHandlerRegistryImpl(BundleContext bundleContext) {
this.bundleContext = bundleContext;
tracker = new ServiceTracker(bundleContext, NamespaceHandler.class.getName(), this);
tracker.open();
}
public Object addingService(ServiceReference reference) {
LOGGER.debug("Adding NamespaceHandler " + reference.toString());
NamespaceHandler handler = (NamespaceHandler) bundleContext.getService(reference);
if (handler != null) {
try {
Map<String, Object> props = new HashMap<String, Object>();
for (String name : reference.getPropertyKeys()) {
props.put(name, reference.getProperty(name));
}
registerHandler(handler, props);
} catch (Exception e) {
LOGGER.warn("Error registering NamespaceHandler", e);
}
} else {
Bundle bundle = reference.getBundle();
// If bundle is null, the service has already been unregistered,
// so do nothing in that case
if (bundle != null) {
LOGGER.warn("Error resolving NamespaceHandler, null Service obtained from tracked ServiceReference {} for bundle {}/{}",
reference.toString(), reference.getBundle().getSymbolicName(), reference.getBundle().getVersion());
}
}
return handler;
}
public void modifiedService(ServiceReference reference, Object service) {
removedService(reference, service);
addingService(reference);
}
public void removedService(ServiceReference reference, Object service) {
try {
LOGGER.debug("Removing NamespaceHandler " + reference.toString());
NamespaceHandler handler = (NamespaceHandler) service;
Map<String, Object> props = new HashMap<String, Object>();
for (String name : reference.getPropertyKeys()) {
props.put(name, reference.getProperty(name));
}
unregisterHandler(handler, props);
} catch (Exception e) {
LOGGER.warn("Error unregistering NamespaceHandler", e);
}
}
public void registerHandler(NamespaceHandler handler, Map properties) {
List<URI> namespaces = getNamespaces(properties);
for (URI uri : namespaces) {
CopyOnWriteArraySet<NamespaceHandler> h = handlers.putIfAbsent(uri, new CopyOnWriteArraySet<NamespaceHandler>());
if (h == null) {
h = handlers.get(uri);
}
if (h.add(handler)) {
List<NamespaceHandlerSetImpl> sets;
synchronized (this.sets) {
sets = new ArrayList<NamespaceHandlerSetImpl>(this.sets);
}
for (NamespaceHandlerSetImpl s : sets) {
s.registerHandler(uri, handler);
}
}
}
}
public void unregisterHandler(NamespaceHandler handler, Map properties) {
List<URI> namespaces = getNamespaces(properties);
for (URI uri : namespaces) {
CopyOnWriteArraySet<NamespaceHandler> h = handlers.get(uri);
if (!h.remove(handler)) {
continue;
}
List<NamespaceHandlerSetImpl> sets;
synchronized (this.sets) {
sets = new ArrayList<NamespaceHandlerSetImpl>(this.sets);
}
for (NamespaceHandlerSetImpl s : sets) {
s.unregisterHandler(uri, handler);
}
}
removeSchemasFor(handler);
}
private static List<URI> getNamespaces(Map properties) {
Object ns = properties != null ? properties.get(NAMESPACE) : null;
if (ns == null) {
throw new IllegalArgumentException("NamespaceHandler service does not have an associated "
+ NAMESPACE + " property defined");
} else if (ns instanceof URI[]) {
return Arrays.asList((URI[]) ns);
} else if (ns instanceof URI) {
return Collections.singletonList((URI) ns);
} else if (ns instanceof String) {
return Collections.singletonList(URI.create((String) ns));
} else if (ns instanceof String[]) {
String[] strings = (String[]) ns;
List<URI> namespaces = new ArrayList<URI>(strings.length);
for (String string : strings) {
namespaces.add(URI.create(string));
}
return namespaces;
} else if (ns instanceof Collection) {
Collection col = (Collection) ns;
List<URI> namespaces = new ArrayList<URI>(col.size());
for (Object o : col) {
namespaces.add(toURI(o));
}
return namespaces;
} else if (ns instanceof Object[]) {
Object[] array = (Object[]) ns;
List<URI> namespaces = new ArrayList<URI>(array.length);
for (Object o : array) {
namespaces.add(toURI(o));
}
return namespaces;
} else {
throw new IllegalArgumentException("NamespaceHandler service has an associated "
+ NAMESPACE + " property defined which can not be converted to an array of URI");
}
}
private static URI toURI(Object o) {
if (o instanceof URI) {
return (URI) o;
} else if (o instanceof String) {
return URI.create((String) o);
} else {
throw new IllegalArgumentException("NamespaceHandler service has an associated "
+ NAMESPACE + " property defined which can not be converted to an array of URI");
}
}
public NamespaceHandlerSet getNamespaceHandlers(Set<URI> uris, Bundle bundle) {
NamespaceHandlerSetImpl s;
synchronized (sets) {
s = new NamespaceHandlerSetImpl(uris, bundle);
sets.add(s);
}
return s;
}
public void destroy() {
tracker.close();
}
private Schema getExistingSchema(Map<URI, NamespaceHandler> handlers) {
synchronized (schemas) {
for (Map<URI, NamespaceHandler> key : schemas.keySet()) {
boolean found = true;
for (URI uri : handlers.keySet()) {
if (!handlers.get(uri).equals(key.get(uri))) {
found = false;
break;
}
}
if (found) {
return schemas.get(key).get();
}
}
return null;
}
}
private void removeSchemasFor(NamespaceHandler handler) {
synchronized (schemas) {
List<Map<URI, NamespaceHandler>> keys = new ArrayList<Map<URI, NamespaceHandler>>();
for (Map<URI, NamespaceHandler> key : schemas.keySet()) {
if (key.values().contains(handler)) {
keys.add(key);
}
}
for (Map<URI, NamespaceHandler> key : keys) {
schemas.remove(key);
}
}
}
private void cacheSchema(Map<URI, NamespaceHandler> handlers, Schema schema) {
synchronized (schemas) {
// Remove schemas that are fully included
for (Iterator<Map<URI, NamespaceHandler>> iterator = schemas.keySet().iterator(); iterator.hasNext();) {
Map<URI, NamespaceHandler> key = iterator.next();
boolean found = true;
for (URI uri : key.keySet()) {
if (!key.get(uri).equals(handlers.get(uri))) {
found = false;
break;
}
}
if (found) {
iterator.remove();
break;
}
}
// Add our new schema
schemas.put(handlers, new SoftReference<Schema>(schema));
}
}
private static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
// Ignore
}
}
private static class SourceLSInput implements LSInput {
private final StreamSource source;
public SourceLSInput(StreamSource source) {
this.source = source;
}
public Reader getCharacterStream() {
return null;
}
public void setCharacterStream(Reader characterStream) {
}
public InputStream getByteStream() {
return source.getInputStream();
}
public void setByteStream(InputStream byteStream) {
}
public String getStringData() {
return null;
}
public void setStringData(String stringData) {
}
public String getSystemId() {
return source.getSystemId();
}
public void setSystemId(String systemId) {
}
public String getPublicId() {
return null;
}
public void setPublicId(String publicId) {
}
public String getBaseURI() {
return null;
}
public void setBaseURI(String baseURI) {
}
public String getEncoding() {
return null;
}
public void setEncoding(String encoding) {
}
public boolean getCertifiedText() {
return false;
}
public void setCertifiedText(boolean certifiedText) {
}
}
protected class NamespaceHandlerSetImpl implements NamespaceHandlerSet {
private final List<Listener> listeners;
private final Bundle bundle;
private final Set<URI> namespaces;
private final Map<URI, NamespaceHandler> handlers;
private final Properties schemaMap = new Properties();
private Schema schema;
public NamespaceHandlerSetImpl(Set<URI> namespaces, Bundle bundle) {
this.listeners = new CopyOnWriteArrayList<Listener>();
this.namespaces = new HashSet<URI>(namespaces);
this.bundle = bundle;
handlers = new ConcurrentHashMap<URI, NamespaceHandler>();
for (URI ns : namespaces) {
findCompatibleNamespaceHandler(ns);
}
URL url = bundle.getResource("OSGI-INF/blueprint/schema.map");
if (url != null) {
InputStream ins = null;
try {
ins = url.openStream();
schemaMap.load(ins);
} catch (IOException ex) {
ex.printStackTrace();
//ignore
} finally {
closeQuietly(ins);
}
}
for (Object ns : schemaMap.keySet()) {
try {
this.namespaces.remove(new URI(ns.toString()));
} catch (URISyntaxException e) {
//ignore
}
}
}
public boolean isComplete() {
return handlers.size() == namespaces.size();
}
public Set<URI> getNamespaces() {
return namespaces;
}
public NamespaceHandler getNamespaceHandler(URI namespace) {
return handlers.get(namespace);
}
public Schema getSchema() throws SAXException, IOException {
return getSchema(null);
}
public Schema getSchema(Map<String, String> locations) throws SAXException, IOException {
if (!isComplete()) {
throw new IllegalStateException("NamespaceHandlerSet is not complete");
}
if (schema == null) {
schema = doGetSchema(locations);
}
return schema;
}
private Schema doGetSchema(Map<String, String> locations) throws IOException, SAXException {
if (schemaMap != null && !schemaMap.isEmpty()) {
return createSchema(locations);
}
// Find a schema that can handle all the requested namespaces
// If it contains additional namespaces, it should not be a problem since
// they won't be used at all
Schema schema = getExistingSchema(handlers);
if (schema == null) {
// Create schema
schema = createSchema(locations);
cacheSchema(handlers, schema);
}
return schema;
}
private class Loader implements LSResourceResolver, Closeable {
final List<StreamSource> sources = new ArrayList<StreamSource>();
final Map<String, URL> loaded = new HashMap<String, URL>();
final Map<String, String> namespaces = new HashMap<String, String>();
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
// Compute id
String id;
String prevNamespace = baseURI != null ? namespaces.get(baseURI) : null;
if (namespaceURI != null && prevNamespace != null && namespaceURI.equals(prevNamespace)) {
// This is an include
id = getId(type, namespaceURI, publicId, systemId);
} else {
id = getId(type, namespaceURI, publicId, null);
}
// Check if it has already been loaded
if (loaded.containsKey(id)) {
return createLSInput(loaded.get(id), id, namespaceURI);
}
// Schema map
//-----------
// Use provided schema map to find the resource.
// If the schema map contains the namespaceURI, publicId or systemId,
// load the corresponding resource directly from the bundle.
String loc = null;
if (namespaceURI != null) {
loc = schemaMap.getProperty(namespaceURI);
}
if (loc == null && publicId != null) {
loc = schemaMap.getProperty(publicId);
}
if (loc == null && systemId != null) {
loc = schemaMap.getProperty(systemId);
}
if (loc != null) {
URL url = bundle.getResource(loc);
if (url != null) {
return createLSInput(url, id, namespaceURI);
}
}
// Relative uris
//---------------
// For relative uris, don't use the namespace handlers, but simply resolve the uri
// and use that one directly to load the resource.
String resolved = resolveIfRelative(systemId, baseURI);
if (resolved != null) {
URL url;
try {
url = new URL(resolved);
} catch (IOException e) {
throw new RuntimeException(e);
}
return createLSInput(url, id, namespaceURI);
}
// Only support xml schemas from now on
if (namespaceURI == null || !W3C_XML_SCHEMA_NS_URI.equals(type)) {
return null;
}
// We are now loading a schema, or schema part with
// * notNull(namespaceURI)
// * null(systemId) or absolute(systemId)
URI nsUri = URI.create(namespaceURI);
String rid = systemId != null ? systemId : namespaceURI;
NamespaceHandler h = getNamespaceHandler(nsUri);
// This is a resource from a known namespace
if (h != null) {
URL url = h.getSchemaLocation(rid);
if (isCorrectUrl(url)) {
return createLSInput(url, id, namespaceURI);
}
}
else {
// Ask known handlers if they have this schema
for (NamespaceHandler hd : handlers.values()) {
URL url = hd.getSchemaLocation(rid);
if (isCorrectUrl(url)) {
return createLSInput(url, id, namespaceURI);
}
}
// Find a compatible namespace handler
h = findCompatibleNamespaceHandler(nsUri);
if (h != null) {
URL url = h.getSchemaLocation(namespaceURI);
if (url == null) {
url = h.getSchemaLocation(rid);
}
if (isCorrectUrl(url)) {
LOGGER.warn("Dynamically adding namespace handler {} to {}/{}", nsUri, bundle.getSymbolicName(), bundle.getVersion());
return createLSInput(url, id, namespaceURI);
}
}
}
LOGGER.warn("Unable to find namespace handler for {}", namespaceURI);
return null;
}
public String getId(String type, String namespaceURI, String publicId, String systemId) {
return type + "|" + namespaceURI + "|" + publicId + "|" + systemId;
}
public StreamSource use(URL resource, String id, String namespace) throws IOException {
String url = resource.toExternalForm();
StreamSource ss = new StreamSource(resource.openStream(), url);
sources.add(ss);
loaded.put(id, resource);
namespaces.put(url, namespace);
return ss;
}
@Override
public void close() {
for (StreamSource source : sources) {
closeQuietly(source.getInputStream());
}
}
public Source[] getSources() {
return sources.toArray(new Source[sources.size()]);
}
private boolean isCorrectUrl(URL url) {
return url != null && !loaded.values().contains(url);
}
private String resolveIfRelative(String systemId, String baseURI) {
if (baseURI != null && systemId != null) {
URI sId = URI.create(systemId);
if (!sId.isAbsolute()) {
URI resolved = URI.create(baseURI).resolve(sId);
if (resolved.isAbsolute()) {
return resolved.toString();
} else {
try {
return new URL(new URL(baseURI), systemId).toString();
} catch (MalformedURLException e) {
LOGGER.warn("Can't resolve " + systemId + " against " + baseURI);
return null;
}
}
}
}
return null;
}
private LSInput createLSInput(URL url, String id, String namespace) {
try {
return new SourceLSInput(use(url, id, namespace));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private Schema createSchema(Map<String, String> locations) throws IOException, SAXException {
Loader loader = new Loader();
try {
loader.use(getClass().getResource("/org/osgi/service/blueprint/blueprint.xsd"),
loader.getId(W3C_XML_SCHEMA_NS_URI, BLUEPRINT_NAMESPACE, null, null),
BLUEPRINT_NAMESPACE);
loader.use(getClass().getResource("/org/apache/aries/blueprint/ext/impl/xml.xsd"),
loader.getId(W3C_XML_SCHEMA_NS_URI, XML_NS_URI, null, null),
XML_NS_URI);
// Create a schema for the namespaces
for (URI ns : handlers.keySet()) {
URL url = handlers.get(ns).getSchemaLocation(ns.toString());
if (url == null && locations != null) {
String loc = locations.get(ns.toString());
if (loc != null) {
url = handlers.get(ns).getSchemaLocation(loc);
}
}
if (url == null) {
LOGGER.warn("No URL is defined for schema " + ns + ". This schema will not be validated");
} else {
loader.use(url, loader.getId(W3C_XML_SCHEMA_NS_URI, ns.toString(), null, null), ns.toString());
}
}
for (Object ns : schemaMap.values()) {
URL url = bundle.getResource(ns.toString());
if (url == null) {
LOGGER.warn("No URL is defined for schema " + ns + ". This schema will not be validated");
} else {
loader.use(url, loader.getId(W3C_XML_SCHEMA_NS_URI, ns.toString(), null, null), ns.toString());
}
}
synchronized (schemaFactory) {
schemaFactory.setResourceResolver(loader);
return schemaFactory.newSchema(loader.getSources());
}
} finally {
loader.close();
}
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public void destroy() {
synchronized (NamespaceHandlerRegistryImpl.this.sets) {
NamespaceHandlerRegistryImpl.this.sets.remove(this);
}
}
public void registerHandler(URI uri, NamespaceHandler handler) {
if (namespaces.contains(uri) && handlers.get(uri) == null) {
if (findCompatibleNamespaceHandler(uri) != null) {
for (Listener listener : listeners) {
try {
listener.namespaceHandlerRegistered(uri);
} catch (Throwable t) {
LOGGER.debug("Unexpected exception when notifying a NamespaceHandler listener", t);
}
}
}
}
}
public void unregisterHandler(URI uri, NamespaceHandler handler) {
if (handlers.get(uri) == handler) {
handlers.remove(uri);
for (Listener listener : listeners) {
try {
listener.namespaceHandlerUnregistered(uri);
} catch (Throwable t) {
LOGGER.debug("Unexpected exception when notifying a NamespaceHandler listener", t);
}
}
}
}
private NamespaceHandler findCompatibleNamespaceHandler(URI ns) {
Set<NamespaceHandler> candidates = NamespaceHandlerRegistryImpl.this.handlers.get(ns);
if (candidates != null) {
for (NamespaceHandler h : candidates) {
Set<Class> classes = h.getManagedClasses();
boolean compat = true;
if (classes != null) {
Set<Class> allClasses = new HashSet<Class>();
for (Class cl : classes) {
for (Class c = cl; c != null; c = c.getSuperclass()) {
allClasses.add(c);
for (Class i : c.getInterfaces()) {
allClasses.add(i);
}
}
}
for (Class cl : allClasses) {
Class clb;
try {
clb = bundle.loadClass(cl.getName());
if (clb != cl) {
compat = false;
break;
}
} catch (ClassNotFoundException e) {
// Ignore
} catch (NoClassDefFoundError e) {
// Ignore
}
}
}
if (compat) {
namespaces.add(ns);
handlers.put(ns, wrapIfNeeded(h));
return h;
}
}
}
return null;
}
}
/**
* Wrap the handler if needed to fix its behavior.
* When asked for a schema location, some simple handlers always return
* the same url, whatever the asked location is. This can lead to lots
* of problems, so we need to verify and fix those behaviors.
*/
private static NamespaceHandler wrapIfNeeded(final NamespaceHandler handler) {
URL result = null;
try {
result = handler.getSchemaLocation("");
} catch (Throwable t) {
// Ignore
}
if (result != null) {
LOGGER.warn("NamespaceHandler " + handler.getClass().getName() + " is behaving badly and should be fixed");
final URL res = result;
return new NamespaceHandler() {
final ConcurrentMap<String, Boolean> cache = new ConcurrentHashMap<String, Boolean>();
@Override
public URL getSchemaLocation(String s) {
URL url = handler.getSchemaLocation(s);
if (url != null && url.equals(res)) {
Boolean v, newValue;
Boolean valid = ((v = cache.get(s)) == null &&
(newValue = isValidSchema(s, url)) != null &&
(v = cache.putIfAbsent(s, newValue)) == null) ? newValue : v;
return valid ? url : null;
}
return url;
}
@Override
public Set<Class> getManagedClasses() {
return handler.getManagedClasses();
}
@Override
public Metadata parse(Element element, ParserContext parserContext) {
return handler.parse(element, parserContext);
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata componentMetadata, ParserContext parserContext) {
return handler.decorate(node, componentMetadata, parserContext);
}
private boolean isValidSchema(String ns, URL url) {
try {
InputStream is = url.openStream();
try {
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is);
try {
reader.nextTag();
String nsuri = reader.getNamespaceURI();
String name = reader.getLocalName();
if ("http://www.w3.org/2001/XMLSchema".equals(nsuri) && "schema".equals(name)) {
String target = reader.getAttributeValue(null, "targetNamespace");
if (ns.equals(target)) {
return true;
}
}
} finally {
reader.close();
}
} finally {
is.close();
}
} catch (Throwable t) {
// Ignore
}
return false;
}
};
} else {
return handler;
}
}
public static class LRUMap<K, V> extends AbstractMap<K, V> {
private final int bound;
private final LinkedList<Entry<K, V>> entries = new LinkedList<Entry<K, V>>();
private static class LRUEntry<K, V> implements Entry<K, V> {
private final K key;
private final V value;
private LRUEntry(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
throw new UnsupportedOperationException();
}
}
private LRUMap(int bound) {
this.bound = bound;
}
public V get(Object key) {
if (key == null) {
throw new NullPointerException();
}
for (Entry<K, V> e : entries) {
if (e.getKey().equals(key)) {
entries.remove(e);
entries.addFirst(e);
return e.getValue();
}
}
return null;
}
public V put(K key, V value) {
if (key == null) {
throw new NullPointerException();
}
V old = null;
for (Entry<K, V> e : entries) {
if (e.getKey().equals(key)) {
entries.remove(e);
old = e.getValue();
break;
}
}
if (value != null) {
entries.addFirst(new LRUEntry<K, V>(key, value));
while (entries.size() > bound) {
entries.removeLast();
}
}
return old;
}
public Set<Entry<K, V>> entrySet() {
return new AbstractSet<Entry<K, V>>() {
public Iterator<Entry<K, V>> iterator() {
return entries.iterator();
}
public int size() {
return entries.size();
}
};
}
}
}
| 9,481 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/namespace/MissingNamespaceException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.namespace;
import java.net.URI;
public class MissingNamespaceException extends RuntimeException {
private final URI namespace;
public MissingNamespaceException(URI namespace) {
this.namespace = namespace;
}
public URI getNamespace() {
return namespace;
}
}
| 9,482 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/ServiceListener.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServiceListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceListener.class);
private Object listener;
private String registerMethod;
private String unregisterMethod;
private ExtendedBlueprintContainer blueprintContainer;
private List<Method> registerMethods;
private List<Method> unregisterMethods;
private boolean initialized = false;
public void setListener(Object listener) {
this.listener = listener;
}
public void setRegisterMethod(String method) {
this.registerMethod = method;
}
public void setUnregisterMethod(String method) {
this.unregisterMethod = method;
}
public void setBlueprintContainer(ExtendedBlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public void register(Object service, Map properties) {
init(service);
invokeMethod(registerMethods, service, properties);
}
public void unregister(Object service, Map properties) {
init(service);
invokeMethod(unregisterMethods, service, properties);
}
private synchronized void init(Object service) {
if (initialized) {
return;
}
Class[] paramTypes = new Class[] { service != null ? service.getClass() : null, Map.class };
Class listenerClass = listener.getClass();
if (registerMethod != null) {
registerMethods = ReflectionUtils.findCompatibleMethods(listenerClass, registerMethod, paramTypes);
if (registerMethods.size() == 0) {
throw new ComponentDefinitionException("No matching methods found for listener registration method: " + registerMethod);
}
LOGGER.debug("Found register methods: {}", registerMethods);
}
if (unregisterMethod != null) {
unregisterMethods = ReflectionUtils.findCompatibleMethods(listenerClass, unregisterMethod, paramTypes);
if (unregisterMethods.size() == 0) {
throw new ComponentDefinitionException("No matching methods found for listener unregistration method: " + unregisterMethod);
}
LOGGER.debug("Found unregister methods: {}", unregisterMethods);
}
initialized = true;
}
private void invokeMethod(List<Method> methods, Object service, Map properties) {
if (methods == null || methods.isEmpty()) {
return;
}
for (Method method : methods) {
try {
ReflectionUtils.invoke(blueprintContainer.getAccessControlContext(),
method, listener, service, properties);
} catch (Exception e) {
LOGGER.error("Error calling listener method " + method, e);
}
}
}
}
| 9,483 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/DynamicCollection.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
/**
* Collection that allows iterators to see addition or removals of elements while iterating.
* This collection and its iterators are thread safe but all operations happen under a
* synchronization lock, so the performance in heavy concurrency load is far from optimal.
* If such a use is needed, a CopyOnWriteArrayList may be more suited.
*
* @version $Rev$, $Date$
*/
public class DynamicCollection<E> extends AbstractCollection<E> {
protected final Object lock = new Object();
protected final List<E> storage;
protected final List<WeakReference<DynamicIterator>> iterators;
public DynamicCollection() {
this.storage = new ArrayList<E>();
this.iterators = new ArrayList<WeakReference<DynamicIterator>>();
}
public DynamicIterator iterator() {
return iterator(0);
}
public DynamicIterator iterator(int index) {
DynamicIterator iterator = createIterator(index);
synchronized (lock) {
for (Iterator<WeakReference<DynamicIterator>> it = iterators.iterator(); it.hasNext();) {
if (it.next().get() == null) {
it.remove();
}
}
iterators.add(new WeakReference<DynamicIterator>(iterator));
}
return iterator;
}
protected DynamicIterator createIterator(int index) {
return new DynamicIterator(index);
}
public int size() {
synchronized (lock) {
return storage.size();
}
}
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(Object o) {
if (o == null) {
throw new NullPointerException();
}
synchronized (lock) {
return storage.contains(o);
}
}
public Object[] toArray() {
synchronized (lock) {
return storage.toArray();
}
}
public <T> T[] toArray(T[] a) {
synchronized (lock) {
return storage.toArray(a);
}
}
public boolean containsAll(Collection<?> c) {
synchronized (lock) {
return storage.containsAll(c);
}
}
public boolean add(E o) {
if (o == null) {
throw new NullPointerException();
}
synchronized (lock) {
internalAdd(storage.size(), o);
return true;
}
}
public boolean remove(Object o) {
if (o == null) {
throw new NullPointerException();
}
synchronized (lock) {
int index = storage.indexOf(o);
return remove(index) != null;
}
}
public E get(int index) {
synchronized (lock) {
return storage.get(index);
}
}
private void internalAdd(int index, E o) {
if (o == null) {
throw new NullPointerException();
}
synchronized (lock) {
storage.add(index, o);
for (Iterator<WeakReference<DynamicIterator>> it = iterators.iterator(); it.hasNext();) {
DynamicIterator i = it.next().get();
if (i == null) {
it.remove();
} else {
i.addedIndex(index);
}
}
}
}
@Override
public void clear() {
synchronized (lock) {
storage.clear();
}
}
public E remove(int index) {
synchronized (lock) {
E o = storage.remove(index);
for (Iterator<WeakReference<DynamicIterator>> it = iterators.iterator(); it.hasNext();) {
WeakReference<DynamicIterator> r = it.next();
DynamicIterator i = r.get();
if (i == null) {
it.remove();
} else {
i.removedIndex(index);
}
}
return o;
}
}
public E first() {
synchronized (lock) {
if (storage.isEmpty()) {
throw new NoSuchElementException();
} else {
return storage.get(0);
}
}
}
public E last() {
synchronized (lock) {
if (storage.isEmpty()) {
throw new NoSuchElementException();
} else {
return storage.get(storage.size() - 1);
}
}
}
public class DynamicIterator implements ListIterator<E> {
protected int index;
protected boolean hasNextCalled;
protected E next;
protected boolean hasPreviousCalled;
protected E previous;
protected E last;
public DynamicIterator() {
this(0);
}
public DynamicIterator(int index) {
this.index = index;
}
protected void removedIndex(int index) {
synchronized (lock) {
if (index < this.index || (index == this.index && (hasNextCalled || hasPreviousCalled))) {
this.index--;
}
}
}
protected void addedIndex(int index) {
synchronized (lock) {
if (index < this.index || (index == this.index && (next != null || previous != null))) {
this.index++;
}
}
}
public boolean hasNext() {
synchronized (lock) {
hasPreviousCalled = false;
hasNextCalled = true;
next = index < storage.size() ? storage.get(index) : null;
return next != null;
}
}
public boolean hasPrevious() {
synchronized (lock) {
hasPreviousCalled = true;
hasNextCalled = false;
previous = index > 0 ? storage.get(index - 1) : null;
return previous != null;
}
}
public E next() {
synchronized (lock) {
try {
if (!hasNextCalled) {
hasNext();
}
last = next;
if (next != null) {
++index;
return next;
} else {
throw new NoSuchElementException();
}
} finally {
hasPreviousCalled = false;
hasNextCalled = false;
next = null;
previous = null;
}
}
}
public E previous() {
synchronized (lock) {
try {
if (!hasPreviousCalled) {
hasPrevious();
}
last = previous;
if (previous != null) {
--index;
return previous;
} else {
throw new NoSuchElementException();
}
} finally {
hasPreviousCalled = false;
hasNextCalled = false;
next = null;
previous = null;
}
}
}
public int nextIndex() {
synchronized (lock) {
return index;
}
}
public int previousIndex() {
synchronized (lock) {
return index - 1;
}
}
public void set(E o) {
throw new UnsupportedOperationException();
}
public void add(E o) {
throw new UnsupportedOperationException();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| 9,484 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/JavaUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
/**
* @version $Rev$ $Date$
*/
public final class JavaUtils {
private JavaUtils() {
}
public static void copy(Dictionary destination, Dictionary source) {
Enumeration e = source.keys();
while (e.hasMoreElements()) {
Object key = e.nextElement();
Object value = source.get(key);
destination.put(key, value);
}
}
public static Hashtable getProperties(ServiceReference ref) {
Hashtable props = new Hashtable();
for (String key : ref.getPropertyKeys()) {
props.put(key, ref.getProperty(key));
}
return props;
}
public static Version getBundleVersion(Bundle bundle) {
Dictionary headers = bundle.getHeaders();
String version = (String) headers.get(Constants.BUNDLE_VERSION);
return (version != null) ? Version.parseVersion(version) : Version.emptyVersion;
}
}
| 9,485 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/BundleDelegatingClassLoader.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import java.io.IOException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import org.osgi.framework.Bundle;
/**
* A ClassLoader delegating to a given OSGi bundle.
*
* @version $Rev$, $Date$
* @deprecated - will be removed in a future version of Aries Blueprint
* Use AriesFrameworkUtil#getClassLoader(Bundle) and
* or AriesFrameworkUtil#getClassLoaderForced(Bundle) instead
*/
@Deprecated
public class BundleDelegatingClassLoader extends ClassLoader {
private final Bundle bundle;
private final ClassLoader classLoader;
public BundleDelegatingClassLoader(Bundle bundle) {
this(bundle, null);
}
public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) {
this.bundle = bundle;
this.classLoader = classLoader;
}
protected Class<?> findClass(final String name) throws ClassNotFoundException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
public Class<?> run() throws ClassNotFoundException {
return bundle.loadClass(name);
}
});
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
if (cause instanceof ClassNotFoundException) throw (ClassNotFoundException) cause;
else throw (RuntimeException) cause;
}
}
protected URL findResource(final String name) {
URL resource = AccessController.doPrivileged(new PrivilegedAction<URL>() {
public URL run() {
return bundle.getResource(name);
}
});
if (classLoader != null && resource == null) {
resource = classLoader.getResource(name);
}
return resource;
}
protected Enumeration<URL> findResources(final String name) throws IOException {
Enumeration<URL> urls;
try {
urls = AccessController.doPrivileged(new PrivilegedExceptionAction<Enumeration<URL>>() {
@SuppressWarnings("unchecked")
public Enumeration<URL> run() throws IOException {
return (Enumeration<URL>) bundle.getResources(name);
}
});
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
if (cause instanceof IOException) throw (IOException) cause;
else throw (RuntimeException) cause;
}
if (urls == null) {
urls = Collections.enumeration(new ArrayList<URL>());
}
return urls;
}
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class clazz;
try {
clazz = findClass(name);
}
catch (ClassNotFoundException cnfe) {
if (classLoader != null) {
try {
clazz = classLoader.loadClass(name);
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException(name + " from bundle " + bundle.getSymbolicName() + "/" + bundle.getVersion(), cnfe);
}
} else {
throw new ClassNotFoundException(name + " from bundle " + bundle.getSymbolicName() + "/" + bundle.getVersion(), cnfe);
}
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
}
public Bundle getBundle() {
return bundle;
}
}
| 9,486 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/HeaderParser.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utility class to parse a standard OSGi header with paths.
*
* @version $Rev$, $Date$
*/
public class HeaderParser {
/**
* Parse a given OSGi header into a list of paths
*
* @param header the OSGi header to parse
* @return the list of paths extracted from this header
*/
public static List<PathElement> parseHeader(String header) {
List<PathElement> elements = new ArrayList<PathElement>();
if (header == null || header.trim().length() == 0) {
return elements;
}
String[] clauses = header.split(",");
for (String clause : clauses) {
String[] tokens = clause.split(";");
if (tokens.length < 1) {
throw new IllegalArgumentException("Invalid header clause: " + clause);
}
PathElement elem = new PathElement(tokens[0].trim());
elements.add(elem);
for (int i = 1; i < tokens.length; i++) {
int pos = tokens[i].indexOf('=');
if (pos != -1) {
if (pos > 0 && tokens[i].charAt(pos - 1) == ':') {
String name = tokens[i].substring(0, pos - 1).trim();
String value = tokens[i].substring(pos + 1).trim();
elem.addDirective(name, value);
} else {
String name = tokens[i].substring(0, pos).trim();
String value = tokens[i].substring(pos + 1).trim();
elem.addAttribute(name, value);
}
} else {
elem = new PathElement(tokens[i].trim());
elements.add(elem);
}
}
}
return elements;
}
public static class PathElement {
private String path;
private Map<String, String> attributes;
private Map<String, String> directives;
public PathElement(String path) {
this.path = path;
this.attributes = new HashMap<String, String>();
this.directives = new HashMap<String, String>();
}
public String getName() {
return this.path;
}
public Map<String, String> getAttributes() {
return attributes;
}
public String getAttribute(String name) {
return attributes.get(name);
}
public void addAttribute(String name, String value) {
attributes.put(name, value);
}
public Map<String, String> getDirectives() {
return directives;
}
public String getDirective(String name) {
return directives.get(name);
}
public void addDirective(String name, String value) {
directives.put(name, value);
}
}
}
| 9,487 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/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.utils;
import org.osgi.framework.ServiceRegistration;
public final class ServiceUtil {
private ServiceUtil() {
}
public static void safeUnregisterService(ServiceRegistration<?> reg) {
if (reg != null) {
try {
reg.unregister();
} catch (IllegalStateException e) {
//This can be safely ignored
}
}
}
}
| 9,488 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/ReflectionUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import org.apache.aries.blueprint.container.GenericType;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.framework.BundleReference;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
public class ReflectionUtils {
private static Map<Class<?>, WeakReference<Method[]>> publicMethods = Collections.synchronizedMap(new WeakHashMap<Class<?>, WeakReference<Method[]>>());
private static Map<Class<?>, PropertyDescriptor[][]> beanInfos = Collections.synchronizedMap(new WeakHashMap<Class<?>, PropertyDescriptor[][]>());
public static boolean hasDefaultConstructor(Class type) {
if (!Modifier.isPublic(type.getModifiers())) {
return false;
}
if (Modifier.isAbstract(type.getModifiers())) {
return false;
}
Constructor[] constructors = type.getConstructors();
for (Constructor constructor : constructors) {
if (Modifier.isPublic(constructor.getModifiers()) &&
constructor.getParameterTypes().length == 0) {
return true;
}
}
return false;
}
public static Set<String> getImplementedInterfaces(Set<String> classes, Class clazz) {
if (clazz != null && clazz != Object.class) {
for (Class itf : clazz.getInterfaces()) {
if (Modifier.isPublic(itf.getModifiers())) {
classes.add(itf.getName());
}
getImplementedInterfaces(classes, itf);
}
getImplementedInterfaces(classes, clazz.getSuperclass());
}
return classes;
}
public static Set<Class<?>> getImplementedInterfacesAsClasses(Set<Class<?>> classes, Class<?> clazz) {
if (clazz != null && clazz != Object.class) {
for (Class<?> itf : clazz.getInterfaces()) {
if (Modifier.isPublic(itf.getModifiers())) {
classes.add(itf);
}
getImplementedInterfacesAsClasses(classes, itf);
}
getImplementedInterfacesAsClasses(classes, clazz.getSuperclass());
}
return classes;
}
public static Set<String> getSuperClasses(Set<String> classes, Class clazz) {
if (clazz != null && clazz != Object.class) {
if (Modifier.isPublic(clazz.getModifiers())) {
classes.add(clazz.getName());
}
getSuperClasses(classes, clazz.getSuperclass());
}
return classes;
}
public static Method getLifecycleMethod(Class clazz, String name) {
if (name != null) {
for (Method method : getPublicMethods(clazz)) {
if (method.getName().equals(name)
&& method.getParameterTypes().length == 0
&& Void.TYPE.equals(method.getReturnType())) {
return method;
}
}
}
return null;
}
public static Method[] getPublicMethods(Class clazz) {
WeakReference<Method[]> ref = publicMethods.get(clazz);
Method[] methods = ref != null ? ref.get() : null;
if (methods == null) {
ArrayList<Method> array = new ArrayList<Method>();
doGetPublicMethods(clazz, array);
methods = array.toArray(new Method[array.size()]);
publicMethods.put(clazz, new WeakReference<Method[]>(methods));
}
return methods;
}
private static void doGetPublicMethods(Class clazz, ArrayList<Method> methods) {
Class parent = clazz.getSuperclass();
if (parent != null) {
doGetPublicMethods(parent, methods);
}
for (Class interf : clazz.getInterfaces()) {
doGetPublicMethods(interf, methods);
}
if (Modifier.isPublic(clazz.getModifiers())) {
for (Method mth : clazz.getMethods()) {
removeByNameAndSignature(methods, mth);
methods.add(mth);
}
}
}
private static void removeByNameAndSignature(ArrayList<Method> methods, Method toRemove) {
for (int i = 0; i < methods.size(); i++) {
Method m = methods.get(i);
if (m != null &&
m.getReturnType() == toRemove.getReturnType() &&
m.getName() == toRemove.getName() &&
arrayContentsEq(m.getParameterTypes(),
toRemove.getParameterTypes())) {
methods.remove(i--);
}
}
}
private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
if (a1 == null) {
return a2 == null || a2.length == 0;
}
if (a2 == null) {
return a1.length == 0;
}
if (a1.length != a2.length) {
return false;
}
for (int i = 0; i < a1.length; i++) {
if (a1[i] != a2[i]) {
return false;
}
}
return true;
}
public static List<Method> findCompatibleMethods(Class clazz, String name, Class[] paramTypes) {
List<Method> methods = new ArrayList<Method>();
for (Method method : getPublicMethods(clazz)) {
Class[] methodParams = method.getParameterTypes();
if (name.equals(method.getName()) && Void.TYPE.equals(method.getReturnType()) && methodParams.length == paramTypes.length && !method.isBridge()) {
boolean assignable = true;
for (int i = 0; i < paramTypes.length && assignable; i++) {
assignable &= paramTypes[i] == null || methodParams[i].isAssignableFrom(paramTypes[i]);
}
if (assignable) {
methods.add(method);
}
}
}
return methods;
}
public static PropertyDescriptor[] getPropertyDescriptors(Class clazz, boolean allowFieldInjection) {
return getPropertyDescriptors(clazz, allowFieldInjection, false);
}
public static PropertyDescriptor[] getPropertyDescriptors(Class clazz, boolean allowFieldInjection, boolean allowNonStandardSetters) {
PropertyDescriptor[][] properties = beanInfos.get(clazz);
int index = (allowFieldInjection ? 0 : 2) + (allowNonStandardSetters ? 0 : 1);
if (properties == null) {
properties = new PropertyDescriptor[4][];
beanInfos.put(clazz, properties);
}
if (properties[index] == null) {
Set<String> propertyNames = new HashSet<String>();
Map<String, Method> getters = new HashMap<String, Method>();
Map<String, List<Method>> setters = new HashMap<String, List<Method>>();
Set<String> illegalProperties = new HashSet<String>();
for (Method method : getPublicMethods(clazz)) {
if (Modifier.isStatic(method.getModifiers()) || method.isBridge()) {
continue;
}
String name = method.getName();
Class<?> argTypes[] = method.getParameterTypes();
Class<?> resultType = method.getReturnType();
if (name.length() > 3 && name.startsWith("set") && resultType == Void.TYPE && argTypes.length == 1) {
name = decapitalize(name.substring(3));
if (!setters.containsKey(name)) {
setters.put(name, new ArrayList<Method>());
}
setters.get(name).add(method);
propertyNames.add(name);
} else if (name.length() > 3 && name.startsWith("get") && resultType != Void.TYPE && argTypes.length == 0) {
name = decapitalize(name.substring(3));
Method getter = getters.get(name);
if (getter == null) {
propertyNames.add(name);
getters.put(name, method);
} else if (!getter.getName().startsWith("is")
|| getter.getReturnType() != boolean.class
|| resultType != boolean.class) {
illegalProperties.add(name);
}
} else if (name.length() > 2 && name.startsWith("is") && argTypes.length == 0 && resultType == boolean.class) {
name = decapitalize(name.substring(2));
Method getter = getters.get(name);
if (getter == null) {
propertyNames.add(name);
getters.put(name, method);
} else if (!getter.getName().startsWith("get") || getter.getReturnType() != boolean.class) {
illegalProperties.add(name);
} else {
getters.put(name, method);
}
}
}
if (allowNonStandardSetters) {
for (Method method : getPublicMethods(clazz)) {
if (Modifier.isStatic(method.getModifiers()) || method.isBridge()) {
continue;
}
String name = method.getName();
Class<?> argTypes[] = method.getParameterTypes();
Class<?> resultType = method.getReturnType();
if (!name.startsWith("get") && resultType != Void.TYPE && argTypes.length == 0 && !getters.containsKey(name)) {
getters.put(name, method);
propertyNames.add(name);
} else if (!name.startsWith("set") && resultType == clazz && argTypes.length == 1) {
if (!setters.containsKey(name)) {
setters.put(name, new ArrayList<Method>());
}
setters.get(name).add(method);
propertyNames.add(name);
}
}
}
Map<String, PropertyDescriptor> props = new HashMap<String, PropertyDescriptor>();
for (String propName : propertyNames) {
props.put(propName,
new MethodPropertyDescriptor(propName, getters.get(propName), setters.get(propName)));
}
if (allowFieldInjection) {
for (Class cl = clazz; cl != null && cl != Object.class; cl = cl.getSuperclass()) {
for (Field field : cl.getDeclaredFields()) {
if (!!!Modifier.isStatic(field.getModifiers())) {
String name = decapitalize(field.getName());
PropertyDescriptor desc = props.get(name);
if (desc == null) {
props.put(name, new FieldPropertyDescriptor(name, field));
} else if (desc instanceof MethodPropertyDescriptor) {
props.put(name,
new JointPropertyDescriptor((MethodPropertyDescriptor) desc,
new FieldPropertyDescriptor(name, field)));
} else {
illegalProperties.add(name);
}
}
}
}
}
List<PropertyDescriptor> result = new ArrayList<PropertyDescriptor>();
for (PropertyDescriptor prop : props.values()) {
if (!!!illegalProperties.contains(prop.getName())) result.add(prop);
}
properties[index] = result.toArray(new PropertyDescriptor[result.size()]);
}
return properties[index];
}
private static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))) {
return name;
}
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
public static Object invoke(AccessControlContext acc, final Method method, final Object instance, final Object... args) throws Exception {
if (acc == null) {
return method.invoke(instance, args);
} else {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return method.invoke(instance, args);
}
}, acc);
} catch (PrivilegedActionException e) {
throw e.getException();
}
}
}
public static Object newInstance(AccessControlContext acc, final Class clazz) throws Exception {
if (acc == null) {
return clazz.newInstance();
} else {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return clazz.newInstance();
}
}, acc);
} catch (PrivilegedActionException e) {
throw e.getException();
}
}
}
public static Object newInstance(AccessControlContext acc, final Constructor constructor, final Object... args) throws Exception {
if (acc == null) {
return constructor.newInstance(args);
} else {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return constructor.newInstance(args);
}
}, acc);
} catch (PrivilegedActionException e) {
throw e.getException();
}
}
}
public static abstract class PropertyDescriptor {
private final String name;
public PropertyDescriptor(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract boolean allowsGet();
public abstract boolean allowsSet();
protected abstract Object internalGet(ExtendedBlueprintContainer container, Object instance) throws Exception;
protected abstract void internalSet(ExtendedBlueprintContainer container, Object instance, Object value) throws Exception;
public Object get(final Object instance, final ExtendedBlueprintContainer container) throws Exception {
if (container.getAccessControlContext() == null) {
return internalGet(container, instance);
} else {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return internalGet(container, instance);
}
}, container.getAccessControlContext());
} catch (PrivilegedActionException e) {
throw e.getException();
}
}
}
public void set(final Object instance, final Object value, final ExtendedBlueprintContainer container) throws Exception {
if (container.getAccessControlContext() == null) {
internalSet(container, instance, value);
} else {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
internalSet(container, instance, value);
return null;
}
}, container.getAccessControlContext());
} catch (PrivilegedActionException e) {
throw e.getException();
}
}
}
protected Object convert(Object obj, Type type) throws Exception {
return ExecutionContext.Holder.getContext().convert(obj, new GenericType(type));
}
}
private static class JointPropertyDescriptor extends PropertyDescriptor {
private final MethodPropertyDescriptor mpd;
private final FieldPropertyDescriptor fpd;
public JointPropertyDescriptor(MethodPropertyDescriptor mpd, FieldPropertyDescriptor fpd) {
super(mpd.getName());
this.mpd = mpd;
this.fpd = fpd;
}
@Override
public boolean allowsGet() {
return mpd.allowsGet() || fpd.allowsGet();
}
@Override
public boolean allowsSet() {
return mpd.allowsSet() || fpd.allowsSet();
}
@Override
protected Object internalGet(ExtendedBlueprintContainer container, Object instance) throws Exception {
if (mpd.allowsGet()) return mpd.internalGet(container, instance);
else if (fpd.allowsGet()) return fpd.internalGet(container, instance);
else throw new UnsupportedOperationException();
}
@Override
protected void internalSet(ExtendedBlueprintContainer container, Object instance, Object value) throws Exception {
if (mpd.allowsSet()) mpd.internalSet(container, instance, value);
else if (fpd.allowsSet()) fpd.internalSet(container, instance, value);
else throw new UnsupportedOperationException();
}
}
private static class FieldPropertyDescriptor extends PropertyDescriptor {
// instead of holding on to the java.lang.reflect.Field objects we retrieve it every time. The reason is that PropertyDescriptors are
// used as values in a WeakHashMap with the class corresponding to the field as the key
private final String fieldName;
private final WeakReference<Class<?>> declaringClass;
public FieldPropertyDescriptor(String name, Field field) {
super(name);
this.fieldName = field.getName();
this.declaringClass = new WeakReference(field.getDeclaringClass());
}
public boolean allowsGet() {
return true;
}
public boolean allowsSet() {
return true;
}
private Field getField(ExtendedBlueprintContainer container) throws ClassNotFoundException, NoSuchFieldException {
if (declaringClass.get() == null) throw new ClassNotFoundException("Declaring class was garbage collected");
return declaringClass.get().getDeclaredField(fieldName);
}
protected Object internalGet(final ExtendedBlueprintContainer container, final Object instance) throws Exception {
if (useContainersPermission(container)) {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return doInternalGet(container, instance);
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof IllegalAccessException) throw (IllegalAccessException) e;
else throw (RuntimeException) e;
}
} else {
return doInternalGet(container, instance);
}
}
private Object doInternalGet(ExtendedBlueprintContainer container, Object instance) throws Exception {
Field field = getField(container);
boolean isAccessible = field.isAccessible();
field.setAccessible(true);
try {
return field.get(instance);
} finally {
field.setAccessible(isAccessible);
}
}
protected void internalSet(final ExtendedBlueprintContainer container, final Object instance, final Object value) throws Exception {
try {
Boolean wasSet = AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
public Boolean run() throws Exception {
if (useContainersPermission(container)) {
doInternalSet(container, instance, value);
return Boolean.TRUE;
}
return Boolean.FALSE;
}
});
if(!!!wasSet) {
doInternalSet(container, instance, value);
}
} catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
private void doInternalSet(ExtendedBlueprintContainer container, Object instance, Object value) throws Exception {
Field field = getField(container);
final Object convertedValue = convert(value, field.getGenericType());
boolean isAccessible = field.isAccessible();
field.setAccessible(true);
try {
field.set(instance, convertedValue);
} finally {
field.setAccessible(isAccessible);
}
}
/**
* Determine whether the field access (in particular the call to {@link Field#setAccessible(boolean)} should be done with the Blueprint extender's
* permissions, rather than the joint (more restrictive) permissions of the extender plus the Blueprint bundle.
*
* We currently only allow this for classes that originate from inside the Blueprint bundle. Otherwise this would open a potential security hole.
* @param container
* @return
*/
private boolean useContainersPermission(ExtendedBlueprintContainer container) throws ClassNotFoundException {
if (declaringClass.get() == null) throw new ClassNotFoundException("Declaring class was garbage collected");
ClassLoader loader = declaringClass.get().getClassLoader();
if (loader == null) return false;
if (loader instanceof BundleReference) {
BundleReference ref = (BundleReference) loader;
return ref.getBundle().equals(container.getBundleContext().getBundle());
}
return false;
}
}
private static class MethodDescriptor {
private final String methodName;
private final WeakReference<Class<?>> declaringClass;
private final List<WeakReference<Class<?>>> argClasses;
public MethodDescriptor(Method method) {
methodName = method.getName();
declaringClass = new WeakReference<Class<?>>(method.getDeclaringClass());
List<WeakReference<Class<?>>> accumulator = new ArrayList<WeakReference<Class<?>>>();
for (Class<?> c : method.getParameterTypes()) {
accumulator.add(new WeakReference<Class<?>>(c));
}
argClasses = Collections.unmodifiableList(accumulator);
}
public Method getMethod(ExtendedBlueprintContainer container) throws ClassNotFoundException, NoSuchMethodException {
Class<?>[] argumentClasses = new Class<?>[argClasses.size()];
for (int i=0; i<argClasses.size(); i++) {
argumentClasses[i] = argClasses.get(i).get();
if (argumentClasses[i] == null) throw new ClassNotFoundException("Argument class was garbage collected");
}
if (declaringClass.get() == null) throw new ClassNotFoundException("Declaring class was garbage collected");
return declaringClass.get().getMethod(methodName, argumentClasses);
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(declaringClass.get()).append(".").append(methodName).append("(");
boolean first = true;
for (WeakReference<Class<?>> wcl : argClasses) {
if (!!!first) builder.append(",");
else first = false;
builder.append(wcl.get());
}
builder.append(")");
return builder.toString();
}
}
private static class MethodPropertyDescriptor extends PropertyDescriptor {
// instead of holding on to the java.lang.reflect.Method objects we retrieve it every time. The reason is that PropertyDescriptors are
// used as values in a WeakHashMap with the class corresponding to the methods as the key
private final MethodDescriptor getter;
private final Collection<MethodDescriptor> setters;
private MethodPropertyDescriptor(String name, Method getter, Collection<Method> setters) {
super(name);
this.getter = (getter != null) ? new MethodDescriptor(getter) : null;
if (setters != null) {
Collection<MethodDescriptor> accumulator = new ArrayList<MethodDescriptor>();
for (Method s : setters) accumulator.add(new MethodDescriptor(s));
this.setters = Collections.unmodifiableCollection(accumulator);
} else {
this.setters = Collections.emptyList();
}
}
public boolean allowsGet() {
return getter != null;
}
public boolean allowsSet() {
return !!!setters.isEmpty();
}
protected Object internalGet(ExtendedBlueprintContainer container, Object instance)
throws Exception {
if (getter != null) {
return getter.getMethod(container).invoke(instance);
} else {
throw new UnsupportedOperationException();
}
}
protected void internalSet(ExtendedBlueprintContainer container, Object instance, Object value) throws Exception {
Method setterMethod = findSetter(container, value);
if (setterMethod != null) {
setterMethod.invoke(instance, convert(value, resolveParameterType(instance.getClass(), setterMethod)));
} else {
throw new ComponentDefinitionException(
"No converter available to convert value "+value+" into a form applicable for the " +
"setters of property "+getName());
}
}
private Type resolveParameterType(Class<?> impl, Method setterMethod) {
Type type = setterMethod.getGenericParameterTypes()[0];
Class<?> declaringClass = setterMethod.getDeclaringClass();
TypeVariable<?>[] declaredVariables = declaringClass.getTypeParameters();
if (TypeVariable.class.isInstance(type)) {
// e.g.: "T extends Serializable"
TypeVariable variable = TypeVariable.class.cast(type);
int index = 0;
for (; index < declaredVariables.length; index++) {
// find the class declaration index...
if (variable == declaredVariables[index]) {
break;
}
}
if (index >= declaredVariables.length) {
// not found - now what...
return type;
}
// navigate from the implementation type up to the declaring super
// class to find the real generic type...
Class<?> c = impl;
while (c != null && c != declaringClass) {
Type sup = c.getGenericSuperclass();
if (sup != null && ParameterizedType.class.isInstance(sup)) {
ParameterizedType pt = ParameterizedType.class.cast(sup);
if (declaringClass == pt.getRawType()) {
Type t = pt.getActualTypeArguments()[index];
return t;
}
}
c = c.getSuperclass();
}
return type;
} else {
// not a generic type...
return type;
}
}
private Method findSetter(ExtendedBlueprintContainer container, Object value) throws Exception {
Class<?> valueType = (value == null) ? null : value.getClass();
Method getterMethod = (getter != null) ? getter.getMethod(container) : null;
Collection<Method> setterMethods = getSetters(container);
Method result = findMethodByClass(getterMethod, setterMethods, valueType);
if (result == null) result = findMethodWithConversion(setterMethods, value);
return result;
}
private Collection<Method> getSetters(ExtendedBlueprintContainer container) throws Exception {
Collection<Method> result = new ArrayList<Method>();
for (MethodDescriptor md : setters) result.add(md.getMethod(container));
return result;
}
private Method findMethodByClass(Method getterMethod, Collection<Method> setterMethods, Class<?> arg)
throws ComponentDefinitionException {
Method result = null;
if (!hasSameTypeSetter(getterMethod, setterMethods)) {
throw new ComponentDefinitionException(
"At least one Setter method has to match the type of the Getter method for property "
+ getName());
}
if (setterMethods.size() == 1) {
return setterMethods.iterator().next();
}
for (Method m : setterMethods) {
Class<?> paramType = m.getParameterTypes()[0];
if ((arg == null && Object.class.isAssignableFrom(paramType))
|| (arg != null && paramType.isAssignableFrom(arg))) {
// pick the method that has the more specific parameter if
// any
if (result != null) {
Class<?> oldParamType = result.getParameterTypes()[0];
if (paramType.isAssignableFrom(oldParamType)) {
// do nothing, result is correct
} else if (oldParamType.isAssignableFrom(paramType)) {
result = m;
} else {
throw new ComponentDefinitionException(
"Ambiguous setter method for property "
+ getName()
+ ". More than one method matches the parameter type "
+ arg);
}
} else {
result = m;
}
}
}
return result;
}
// ensure there is a setter that matches the type of the getter
private boolean hasSameTypeSetter(Method getterMethod, Collection<Method> setterMethods) {
if (getterMethod == null) {
return true;
}
Iterator<Method> it = setterMethods.iterator();
while (it.hasNext()) {
Method m = it.next();
if (m.getParameterTypes()[0].equals(getterMethod.getReturnType())) {
return true;
}
}
return false;
}
private Method findMethodWithConversion(Collection<Method> setterMethods, Object value) throws Exception {
ExecutionContext ctx = ExecutionContext.Holder.getContext();
Method matchingMethod = null;
for (Method m : setterMethods) {
Type paramType = m.getGenericParameterTypes()[0];
if (ctx.canConvert(value, new GenericType(paramType))) {
if (matchingMethod != null) {
Class<?> p1Class = matchingMethod.getParameterTypes()[0];
Class<?> p2Class = m.getParameterTypes()[0];
if(!p2Class.equals(p1Class) && p1Class.isAssignableFrom(p2Class)) {
// Keep method whose parameter type is the closest to value type
matchingMethod = m;
} else if(p2Class.equals(p1Class) || !p2Class.isAssignableFrom(p1Class)) {
throw new ComponentDefinitionException(
"Ambiguous setter method for property "
+ getName() + ". More than one method matches the parameter "
+ value + " after applying conversion.");
}
} else {
matchingMethod = m;
}
}
}
return matchingMethod;
}
public String toString() {
return "PropertyDescriptor <name: "+getName()+", getter: "+getter+", setter: "+setters;
}
}
public static Throwable getRealCause(Throwable t) {
if (t instanceof InvocationTargetException && t.getCause() != null) {
return t.getCause();
}
return t;
}
}
| 9,489 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/generics/OwbWildcardTypeImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils.generics;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
public class OwbWildcardTypeImpl implements WildcardType {
private Type[] upperBounds;
private Type[] lowerBounds;
public OwbWildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
this.upperBounds = upperBounds.clone();
this.lowerBounds = lowerBounds.clone();
}
@Override
public Type[] getUpperBounds() {
return upperBounds.clone();
}
@Override
public Type[] getLowerBounds() {
return lowerBounds.clone();
}
public String toString() {
StringBuilder buffer = new StringBuilder("?");
if (upperBounds.length > 0) {
buffer.append(" extends");
boolean first = true;
for (Type upperBound : upperBounds) {
if (first) {
first = false;
} else {
buffer.append(',');
}
buffer.append(' ');
if (upperBound instanceof Class) {
buffer.append(((Class<?>) upperBound).getSimpleName());
} else {
buffer.append(upperBound);
}
}
}
if (lowerBounds.length > 0) {
buffer.append(" super");
boolean first = true;
for (Type lowerBound : lowerBounds) {
if (first) {
first = false;
} else {
buffer.append(',');
}
buffer.append(' ');
if (lowerBound instanceof Class) {
buffer.append(((Class<?>) lowerBound).getSimpleName());
} else {
buffer.append(lowerBound);
}
}
}
return buffer.toString();
}
}
| 9,490 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/generics/GenericsUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils.generics;
import java.lang.reflect.*;
import java.util.*;
/**
* Utility classes for generic type operations.
*/
public final class GenericsUtil {
public static boolean satisfiesDependency(boolean isDelegateOrEvent, boolean isProducer, Type injectionPointType, Type beanType) {
if (beanType instanceof TypeVariable || beanType instanceof WildcardType || beanType instanceof GenericArrayType) {
return isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointType, beanType);
} else {
Type injectionPointRawType = injectionPointType instanceof ParameterizedType ? ((ParameterizedType) injectionPointType).getRawType() : injectionPointType;
Type beanRawType = beanType instanceof ParameterizedType ? ((ParameterizedType) beanType).getRawType() : beanType;
if (ClassUtil.isSame(injectionPointRawType, beanRawType)) {
return isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointType, beanType);
}
}
return false;
}
public static boolean satisfiesDependencyRaw(boolean isDelegateOrEvent, boolean isProducer, Type injectionPointType, Type beanType) {
if (beanType instanceof TypeVariable || beanType instanceof WildcardType || beanType instanceof GenericArrayType) {
return isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointType, beanType);
} else {
Type injectionPointRawType = injectionPointType instanceof ParameterizedType ? ((ParameterizedType) injectionPointType).getRawType() : injectionPointType;
Type beanRawType = beanType instanceof ParameterizedType ? ((ParameterizedType) beanType).getRawType() : beanType;
if (ClassUtil.isSame(injectionPointRawType, beanRawType)) {
return isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointRawType, beanRawType);
} else {
Class bean = (Class) beanType;
if (bean.getSuperclass() != null && ClassUtil.isRawClassEquals(injectionPointType, bean.getSuperclass())) {
return true;
}
Class<?>[] interfaces = bean.getInterfaces();
if (interfaces == null || interfaces.length == 0) {
return false;
}
for (Class<?> clazz : interfaces) {
if (ClassUtil.isRawClassEquals(injectionPointType, clazz)) {
return true;
}
}
}
}
return false;
}
/**
* 5.2.3 and 5.2.4
*/
public static boolean isAssignableFrom(boolean isDelegateOrEvent, boolean isProducer, Type requiredType, Type beanType) {
if (requiredType instanceof Class) {
return isAssignableFrom(isDelegateOrEvent, (Class<?>) requiredType, beanType);
} else if (requiredType instanceof ParameterizedType) {
return isAssignableFrom(isDelegateOrEvent, isProducer, (ParameterizedType) requiredType, beanType);
} else if (requiredType instanceof TypeVariable) {
return isAssignableFrom(isDelegateOrEvent, (TypeVariable<?>) requiredType, beanType);
} else if (requiredType instanceof GenericArrayType) {
return Class.class.isInstance(beanType) && Class.class.cast(beanType).isArray()
&& isAssignableFrom(isDelegateOrEvent, (GenericArrayType) requiredType, beanType);
} else if (requiredType instanceof WildcardType) {
return isAssignableFrom(isDelegateOrEvent, (WildcardType) requiredType, beanType);
} else {
throw new IllegalArgumentException("Unsupported type " + requiredType.getClass());
}
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, Class<?> injectionPointType, Type beanType) {
if (beanType instanceof Class) {
return isAssignableFrom(injectionPointType, (Class<?>) beanType);
} else if (beanType instanceof TypeVariable) {
return isAssignableFrom(isDelegateOrEvent, injectionPointType, (TypeVariable<?>) beanType);
} else if (beanType instanceof ParameterizedType) {
return isAssignableFrom(isDelegateOrEvent, injectionPointType, (ParameterizedType) beanType);
} else if (beanType instanceof GenericArrayType) {
return isAssignableFrom(isDelegateOrEvent, injectionPointType, (GenericArrayType) beanType);
} else if (beanType instanceof WildcardType) {
return isAssignableFrom(isDelegateOrEvent, (Type) injectionPointType, (WildcardType) beanType);
} else {
throw new IllegalArgumentException("Unsupported type " + injectionPointType.getClass());
}
}
private static boolean isAssignableFrom(Class<?> injectionPointType, Class<?> beanType) {
return ClassUtil.isClassAssignableFrom(injectionPointType, beanType);
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, Class<?> injectionPointType, TypeVariable<?> beanType) {
for (Type bounds : beanType.getBounds()) {
if (isAssignableFrom(isDelegateOrEvent, injectionPointType, bounds)) {
return true;
}
}
return false;
}
/**
* CDI Spec. 5.2.4: "A parameterized bean type is considered assignable to a raw required type
* if the raw generics are identical and all type parameters of the bean type are either unbounded type variables or java.lang.Object."
*/
private static boolean isAssignableFrom(boolean isDelegateOrEvent, Class<?> injectionPointType, ParameterizedType beanType) {
if (beanType.getRawType() != injectionPointType) {
return false; //raw generics don't match
}
if (isDelegateOrEvent) {
// for delegate and events we match 'in reverse' kind off
// @Observes ProcessInjectionPoint<?, Instance> does also match Instance<SomeBean>
return isAssignableFrom(true, injectionPointType, beanType.getRawType());
}
for (Type typeArgument : beanType.getActualTypeArguments()) {
if (typeArgument == Object.class) {
continue;
}
if (!(typeArgument instanceof TypeVariable)) {
return false; //neither object nor type variable
}
TypeVariable<?> typeVariable = (TypeVariable<?>) typeArgument;
for (Type bounds : typeVariable.getBounds()) {
if (bounds != Object.class) {
return false; //bound type variable
}
}
}
return true;
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, Class<?> injectionPointType, GenericArrayType beanType) {
return injectionPointType.isArray() && isAssignableFrom(isDelegateOrEvent, injectionPointType.getComponentType(), beanType.getGenericComponentType());
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, Type injectionPointType, WildcardType beanType) {
for (Type bounds : beanType.getLowerBounds()) {
if (!isAssignableFrom(isDelegateOrEvent, false, bounds, injectionPointType)) {
return false;
}
}
for (Type bounds : beanType.getUpperBounds()) {
if (isAssignableFrom(isDelegateOrEvent, false, injectionPointType, bounds)) {
return true;
}
}
return false;
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, boolean isProducer, ParameterizedType injectionPointType, Type beanType) {
if (beanType instanceof Class) {
return isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointType, (Class<?>) beanType);
} else if (beanType instanceof TypeVariable) {
return isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointType, (TypeVariable<?>) beanType);
} else if (beanType instanceof ParameterizedType) {
return isAssignableFrom(isDelegateOrEvent, injectionPointType, (ParameterizedType) beanType);
} else if (beanType instanceof WildcardType) {
return isAssignableFrom(isDelegateOrEvent, injectionPointType, (WildcardType) beanType);
} else if (beanType instanceof GenericArrayType) {
return false;
} else {
throw new IllegalArgumentException("Unsupported type " + beanType.getClass());
}
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, boolean isProducer, ParameterizedType injectionPointType, Class<?> beanType) {
Class<?> rawInjectionPointType = getRawType(injectionPointType);
if (rawInjectionPointType.equals(beanType)) {
if (isProducer) {
for (final Type t : injectionPointType.getActualTypeArguments()) {
if (!TypeVariable.class.isInstance(t) || !isNotBound(TypeVariable.class.cast(t).getBounds())) {
if (!Class.class.isInstance(t) || Object.class != t) {
return false;
}
}
}
}
return true;
}
if (!rawInjectionPointType.isAssignableFrom(beanType)) {
return false;
}
if (beanType.getSuperclass() != null && isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointType, beanType.getGenericSuperclass())) {
return true;
}
for (Type genericInterface : beanType.getGenericInterfaces()) {
if (isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointType, genericInterface)) {
return true;
}
}
return false;
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, boolean isProducer, ParameterizedType injectionPointType, TypeVariable<?> beanType) {
final Type[] types = beanType.getBounds();
if (isNotBound(types)) {
return true;
}
for (final Type bounds : types) {
if (isAssignableFrom(isDelegateOrEvent, isProducer, injectionPointType, bounds)) {
return true;
}
}
return false;
}
/**
* CDI Spec. 5.2.4
*/
private static boolean isAssignableFrom(boolean isDelegateOrEvent, ParameterizedType injectionPointType, ParameterizedType beanType) {
if (injectionPointType.getRawType() != beanType.getRawType()) {
return false;
}
boolean swapParams = !isDelegateOrEvent;
Type[] injectionPointTypeArguments = injectionPointType.getActualTypeArguments();
Type[] beanTypeArguments = beanType.getActualTypeArguments();
for (int i = 0; i < injectionPointTypeArguments.length; i++) {
Type injectionPointTypeArgument = injectionPointTypeArguments[i];
Type beanTypeArgument = beanTypeArguments[i];
// for this special case it's actually an 'assignable to', thus we swap the params, see CDI-389
// but this special rule does not apply to Delegate injection points...
if (swapParams &&
(injectionPointTypeArgument instanceof Class || injectionPointTypeArgument instanceof TypeVariable) &&
beanTypeArgument instanceof TypeVariable) {
final Type[] bounds = ((TypeVariable<?>) beanTypeArgument).getBounds();
final boolean isNotBound = isNotBound(bounds);
if (!isNotBound) {
for (final Type upperBound : bounds) {
if (!isAssignableFrom(true, false, upperBound, injectionPointTypeArgument)) {
return false;
}
}
}
} else if (swapParams && injectionPointTypeArgument instanceof TypeVariable) {
return false;
} else if (isDelegateOrEvent && injectionPointTypeArgument instanceof Class && beanTypeArgument instanceof Class) {
// if no wildcard type was given then we require a real exact match.
return injectionPointTypeArgument.equals(beanTypeArgument);
} else if (!isAssignableFrom(isDelegateOrEvent, false, injectionPointTypeArgument, beanTypeArgument)) {
return false;
}
}
return true;
}
private static boolean isNotBound(final Type... bounds) {
return bounds == null || bounds.length == 0 || (bounds.length == 1 && Object.class == bounds[0]);
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, TypeVariable<?> injectionPointType, Type beanType) {
for (Type bounds : injectionPointType.getBounds()) {
if (!isAssignableFrom(isDelegateOrEvent, false, bounds, beanType)) {
return false;
}
}
return true;
}
// rules are a bit different when in an array so we handle ParameterizedType manually (not reusing isAssignableFrom)
private static boolean isAssignableFrom(boolean isDelegateOrEvent, GenericArrayType injectionPointType, Type beanType) {
final Type genericComponentType = injectionPointType.getGenericComponentType();
final Class componentType = Class.class.cast(beanType).getComponentType();
if (Class.class.isInstance(genericComponentType)) {
return Class.class.cast(genericComponentType).isAssignableFrom(componentType);
}
if (ParameterizedType.class.isInstance(genericComponentType)) {
return isAssignableFrom(isDelegateOrEvent, false, ParameterizedType.class.cast(genericComponentType).getRawType(), componentType);
}
return isAssignableFrom(isDelegateOrEvent, false, genericComponentType, componentType);
}
private static boolean isAssignableFrom(boolean isDelegateOrEvent, WildcardType injectionPointType, Type beanType) {
if (beanType instanceof TypeVariable) {
return isAssignableFrom(isDelegateOrEvent, injectionPointType, (TypeVariable<?>) beanType);
}
for (Type bounds : injectionPointType.getLowerBounds()) {
if (!isAssignableFrom(isDelegateOrEvent, false, beanType, bounds)) {
return false;
}
}
for (Type bounds : injectionPointType.getUpperBounds()) {
Set<Type> beanTypeClosure = getTypeClosure(beanType);
boolean isAssignable = false;
for (Type beanSupertype : beanTypeClosure) {
if (isAssignableFrom(isDelegateOrEvent, false, bounds, beanSupertype)
|| (Class.class.isInstance(bounds)
&& ParameterizedType.class.isInstance(beanSupertype)
&& bounds == ParameterizedType.class.cast(beanSupertype).getRawType())) {
isAssignable = true;
break;
}
}
if (!isAssignable) {
return false;
}
}
return true;
}
/**
* CDI 1.1 Spec. 5.2.4, third bullet point
*/
private static boolean isAssignableFrom(boolean isDelegateOrEvent, WildcardType injectionPointType, TypeVariable<?> beanType) {
for (Type upperBound : injectionPointType.getUpperBounds()) {
for (Type bound : beanType.getBounds()) {
if (!isAssignableFrom(isDelegateOrEvent, false, upperBound, bound) && !isAssignableFrom(isDelegateOrEvent, false, bound, upperBound)) {
return false;
}
}
}
for (Type lowerBound : injectionPointType.getLowerBounds()) {
for (Type bound : beanType.getBounds()) {
if (!isAssignableFrom(isDelegateOrEvent, false, bound, lowerBound)) {
return false;
}
}
}
return true;
}
/**
* @return <tt>true</tt>, if the specified type declaration contains an unresolved type variable.
*/
public static boolean containsTypeVariable(Type type) {
if (type instanceof Class) {
return false;
} else if (type instanceof TypeVariable) {
return true;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
return containTypeVariable(parameterizedType.getActualTypeArguments());
} else if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
return containTypeVariable(wildcardType.getUpperBounds()) || containTypeVariable(wildcardType.getLowerBounds());
} else if (type instanceof GenericArrayType) {
GenericArrayType arrayType = (GenericArrayType) type;
return containsTypeVariable(arrayType.getGenericComponentType());
} else {
throw new IllegalArgumentException("Unsupported type " + type.getClass().getName());
}
}
public static boolean containTypeVariable(Collection<? extends Type> types) {
return containTypeVariable(types.toArray(new Type[types.size()]));
}
public static boolean containTypeVariable(Type[] types) {
for (Type type : types) {
if (containsTypeVariable(type)) {
return true;
}
}
return false;
}
/**
* @param type to check
* @return {@code true} if the given type contains a {@link WildcardType}
* {@code false} otherwise
*/
public static boolean containsWildcardType(Type type) {
if (!(type instanceof ParameterizedType)) {
return false;
}
for (Type typeArgument : getParameterizedType(type).getActualTypeArguments()) {
if (ClassUtil.isParametrizedType(typeArgument)) {
if (containsWildcardType(typeArgument)) {
return true;
}
} else {
if (ClassUtil.isWildCardType(typeArgument)) {
return true;
}
}
}
return false;
}
/**
* Resolves the actual type of the specified field for the type hierarchy specified by the given subclass
*/
public static Type resolveType(Class<?> subclass, Field field) {
return resolveType(field.getGenericType(), subclass, newSeenList());
}
/**
* Resolves the actual return type of the specified method for the type hierarchy specified by the given subclass
*/
public static Type resolveReturnType(Class<?> subclass, Method method) {
return resolveType(method.getGenericReturnType(), subclass, newSeenList());
}
/**
* Resolves the actual parameter generics of the specified constructor for the type hierarchy specified by the given subclass
*/
public static Type[] resolveParameterTypes(Class<?> subclass, Constructor<?> constructor) {
return resolveTypes(constructor.getGenericParameterTypes(), subclass);
}
/**
* Resolves the actual parameter generics of the specified method for the type hierarchy specified by the given subclass
*/
public static Type[] resolveParameterTypes(Class<?> subclass, Method method) {
return resolveTypes(method.getGenericParameterTypes(), subclass);
}
/**
* Resolves the actual type of the specified type for the type hierarchy specified by the given subclass
*/
public static Type resolveType(Type type, Class<?> subclass, Member member) {
return resolveType(type, subclass, newSeenList());
}
public static Type resolveType(Type type, Class<?> subclass, Member member, Collection<TypeVariable<?>> seen) {
return resolveType(type, subclass, seen);
}
public static Type resolveType(Type type, Type actualType, Collection<TypeVariable<?>> seen) {
if (type instanceof Class) {
return type;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type[] resolvedTypeArguments;
if (Enum.class.equals(parameterizedType.getRawType())) {
// Enums derive from themselves, which would create an infinite loop
// we directly escape the loop if we detect this.
resolvedTypeArguments = new Type[]{new OwbWildcardTypeImpl(new Type[]{Enum.class}, ClassUtil.NO_TYPES)};
} else {
resolvedTypeArguments = resolveTypes(parameterizedType.getActualTypeArguments(), actualType, seen);
}
return new OwbParametrizedTypeImpl(parameterizedType.getOwnerType(), parameterizedType.getRawType(), resolvedTypeArguments);
} else if (type instanceof TypeVariable) {
TypeVariable<?> variable = (TypeVariable<?>) type;
return resolveTypeVariable(variable, actualType, seen);
} else if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
Type[] upperBounds = resolveTypes(wildcardType.getUpperBounds(), actualType, seen);
Type[] lowerBounds = resolveTypes(wildcardType.getLowerBounds(), actualType, seen);
return new OwbWildcardTypeImpl(upperBounds, lowerBounds);
} else if (type instanceof GenericArrayType) {
GenericArrayType arrayType = (GenericArrayType) type;
return createArrayType(resolveType(arrayType.getGenericComponentType(), actualType, seen));
} else {
throw new IllegalArgumentException("Unsupported type " + type.getClass().getName());
}
}
public static Type[] resolveTypes(Type[] types, Type actualType, Collection<TypeVariable<?>> seen) {
Type[] resolvedTypeArguments = new Type[types.length];
for (int i = 0; i < types.length; i++) {
final Type type = resolveType(types[i], actualType, seen);
if (type != null) // means a stackoverflow was avoided, just keep what we have
{
resolvedTypeArguments[i] = type;
}
}
return resolvedTypeArguments;
}
public static Type[] resolveTypes(Type[] types, Type actualType) {
Type[] resolvedTypeArguments = new Type[types.length];
for (int i = 0; i < types.length; i++) {
resolvedTypeArguments[i] = resolveType(types[i], actualType, newSeenList());
}
return resolvedTypeArguments;
}
public static Set<Type> getTypeClosure(Class<?> type) {
return getTypeClosure(type, type);
}
public static Set<Type> getTypeClosure(Type actualType) {
return getTypeClosure(actualType, actualType);
}
/**
* Returns the type closure for the specified parameters.
* <h3>Example 1:</h3>
* <p>
* Take the following classes:
* </p>
* <code>
* public class Foo<T> {
* private T t;
* }
* public class Bar extends Foo<Number> {
* }
* </code>
* <p>
* To get the type closure of T in the context of Bar (which is {Number.class, Object.class}), you have to call this method like
* </p>
* <code>
* GenericUtil.getTypeClosure(Foo.class.getDeclaredField("t").getType(), Bar.class, Foo.class);
* </code>
* <h3>Example 2:</h3>
* <p>
* Take the following classes:
* </p>
* <code>
* public class Foo<T> {
* private T t;
* }
* public class Bar<T> extends Foo<T> {
* }
* </code>
* <p>
* To get the type closure of Bar<T> in the context of Foo<Number> (which are besides Object.class the <tt>ParameterizedType</tt>s Bar<Number> and Foo<Number>),
* you have to call this method like
* </p>
* <code>
* GenericUtil.getTypeClosure(Foo.class, new TypeLiteral<Foo<Number>>() {}.getType(), Bar.class);
* </code>
*
* @param type the type to get the closure for
* @param actualType the context to bind type variables
* @return the type closure
*/
public static Set<Type> getTypeClosure(Type type, Type actualType) {
Class<?> rawType = getRawType(type);
Class<?> actualRawType = getRawType(actualType);
if (rawType.isAssignableFrom(actualRawType) && rawType != actualRawType) {
return getTypeClosure(actualType, type);
}
if (hasTypeParameters(type)) {
type = getParameterizedType(type);
}
return getDirectTypeClosure(type, actualType);
}
public static Set<Type> getDirectTypeClosure(final Type type, final Type actualType) {
Set<Type> typeClosure = new HashSet<Type>();
typeClosure.add(Object.class);
fillTypeHierarchy(typeClosure, type, actualType);
return typeClosure;
}
private static void fillTypeHierarchy(Set<Type> set, Type type, Type actualType) {
if (type == null) {
return;
}
Type resolvedType = GenericsUtil.resolveType(type, actualType, newSeenList());
set.add(resolvedType);
Class<?> resolvedClass = GenericsUtil.getRawType(resolvedType, actualType);
if (resolvedClass.getSuperclass() != null) {
fillTypeHierarchy(set, resolvedClass.getGenericSuperclass(), resolvedType);
}
for (Type interfaceType : resolvedClass.getGenericInterfaces()) {
fillTypeHierarchy(set, interfaceType, resolvedType);
}
}
private static Collection<TypeVariable<?>> newSeenList() {
return new ArrayList<TypeVariable<?>>();
}
public static boolean hasTypeParameters(Type type) {
if (type instanceof Class) {
Class<?> classType = (Class<?>) type;
return classType.getTypeParameters().length > 0;
}
return false;
}
public static ParameterizedType getParameterizedType(Type type) {
if (type instanceof ParameterizedType) {
return (ParameterizedType) type;
} else if (type instanceof Class) {
Class<?> classType = (Class<?>) type;
return new OwbParametrizedTypeImpl(classType.getDeclaringClass(), classType, classType.getTypeParameters());
} else {
throw new IllegalArgumentException(type.getClass().getSimpleName() + " is not supported");
}
}
public static <T> Class<T> getRawType(Type type) {
return getRawType(type, null);
}
static <T> Class<T> getRawType(Type type, Type actualType) {
if (type instanceof Class) {
return (Class<T>) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
return getRawType(parameterizedType.getRawType(), actualType);
} else if (type instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) type;
Type mostSpecificType = getMostSpecificType(getRawTypes(typeVariable.getBounds(), actualType), typeVariable.getBounds());
return getRawType(mostSpecificType, actualType);
} else if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
Type mostSpecificType = getMostSpecificType(getRawTypes(wildcardType.getUpperBounds(), actualType), wildcardType.getUpperBounds());
return getRawType(mostSpecificType, actualType);
} else if (type instanceof GenericArrayType) {
GenericArrayType arrayType = (GenericArrayType) type;
return getRawType(createArrayType(getRawType(arrayType.getGenericComponentType(), actualType)), actualType);
} else {
throw new IllegalArgumentException("Unsupported type " + type.getClass().getName());
}
}
private static <T> Class<T>[] getRawTypes(Type[] types) {
return getRawTypes(types, null);
}
private static <T> Class<T>[] getRawTypes(Type[] types, Type actualType) {
Class<T>[] rawTypes = new Class[types.length];
for (int i = 0; i < types.length; i++) {
rawTypes[i] = getRawType(types[i], actualType);
}
return rawTypes;
}
private static Type getMostSpecificType(Class<?>[] types, Type[] genericTypes) {
Class<?> mostSpecificType = types[0];
int mostSpecificIndex = 0;
for (int i = 0; i < types.length; i++) {
if (mostSpecificType.isAssignableFrom(types[i])) {
mostSpecificType = types[i];
mostSpecificIndex = i;
}
}
return genericTypes[mostSpecificIndex];
}
private static Class<?>[] getClassTypes(Class<?>[] rawTypes) {
List<Class<?>> classTypes = new ArrayList<Class<?>>();
for (Class<?> rawType : rawTypes) {
if (!rawType.isInterface()) {
classTypes.add(rawType);
}
}
return classTypes.toArray(new Class[classTypes.size()]);
}
private static Type resolveTypeVariable(TypeVariable<?> variable, Type actualType, Collection<TypeVariable<?>> seen) {
if (actualType == null) {
return variable;
}
Class<?> declaringClass = getDeclaringClass(variable.getGenericDeclaration());
Class<?> actualClass = getRawType(actualType);
if (actualClass == declaringClass) {
return resolveTypeVariable(variable, variable.getGenericDeclaration(), getParameterizedType(actualType), seen);
} else if (actualClass.isAssignableFrom(declaringClass)) {
Class<?> directSubclass = getDirectSubclass(declaringClass, actualClass);
Type[] typeArguments = resolveTypeArguments(directSubclass, actualType);
Type directSubtype = new OwbParametrizedTypeImpl(directSubclass.getDeclaringClass(), directSubclass, typeArguments);
return resolveTypeVariable(variable, directSubtype, seen);
} else // if (declaringClass.isAssignableFrom(actualClass))
{
Type genericSuperclass = getGenericSuperclass(actualClass, declaringClass);
if (genericSuperclass == null) {
return variable;
} else if (genericSuperclass instanceof Class) {
// special handling for type erasure
Class<?> superclass = (Class<?>) genericSuperclass;
genericSuperclass = new OwbParametrizedTypeImpl(superclass.getDeclaringClass(), superclass, getRawTypes(superclass.getTypeParameters()));
} else {
ParameterizedType genericSupertype = getParameterizedType(genericSuperclass);
Type[] typeArguments = resolveTypeArguments(getParameterizedType(actualType), genericSupertype);
genericSuperclass = new OwbParametrizedTypeImpl(genericSupertype.getOwnerType(), genericSupertype.getRawType(), typeArguments);
}
Type resolvedType = resolveTypeVariable(variable, genericSuperclass, seen);
if (resolvedType instanceof TypeVariable) {
TypeVariable<?> resolvedTypeVariable = (TypeVariable<?>) resolvedType;
TypeVariable<?>[] typeParameters = actualClass.getTypeParameters();
for (int i = 0; i < typeParameters.length; i++) {
if (typeParameters[i].getName().equals(resolvedTypeVariable.getName())) {
resolvedType = getParameterizedType(actualType).getActualTypeArguments()[i];
break;
}
}
}
return resolvedType;
}
}
private static Class<?> getDeclaringClass(GenericDeclaration declaration) {
if (declaration instanceof Class) {
return (Class<?>) declaration;
} else if (declaration instanceof Member) {
return ((Member) declaration).getDeclaringClass();
} else {
throw new IllegalArgumentException("Unsupported type " + declaration.getClass());
}
}
private static Type resolveTypeVariable(TypeVariable<?> variable, GenericDeclaration declaration, ParameterizedType type,
Collection<TypeVariable<?>> seen) {
int index = getIndex(declaration, variable);
if (declaration instanceof Class) {
if (index >= 0) {
return type.getActualTypeArguments()[index];
} else {
index = getIndex(type, variable);
if (index >= 0) {
return declaration.getTypeParameters()[index];
}
}
} else {
if (seen.contains(variable)) {
return null;
}
seen.add(variable);
Type[] resolvedBounds = resolveTypes(declaration.getTypeParameters()[index].getBounds(), type, seen);
return OwbTypeVariableImpl.createTypeVariable(variable, resolvedBounds);
}
return variable;
}
private static int getIndex(GenericDeclaration declaration, TypeVariable<?> variable) {
Type[] typeParameters = declaration.getTypeParameters();
for (int i = 0; i < typeParameters.length; i++) {
if (typeParameters[i] instanceof TypeVariable) {
TypeVariable<?> variableArgument = (TypeVariable<?>) typeParameters[i];
if (variableArgument.getName().equals(variable.getName())) {
return i;
}
}
}
return -1;
}
private static int getIndex(ParameterizedType type, TypeVariable<?> variable) {
Type[] actualTypeArguments = type.getActualTypeArguments();
for (int i = 0; i < actualTypeArguments.length; i++) {
if (actualTypeArguments[i] instanceof TypeVariable) {
TypeVariable<?> variableArgument = (TypeVariable<?>) actualTypeArguments[i];
if (variableArgument.getName().equals(variable.getName())) {
return i;
}
}
}
return -1;
}
private static Class<?> getDirectSubclass(Class<?> declaringClass, Class<?> actualClass) {
if (actualClass.isInterface()) {
Class<?> subclass = declaringClass;
for (Class<?> iface : declaringClass.getInterfaces()) {
if (iface == actualClass) {
return subclass;
}
if (actualClass.isAssignableFrom(iface)) {
subclass = iface;
} else {
subclass = declaringClass.getSuperclass();
}
}
return getDirectSubclass(subclass, actualClass);
} else {
Class<?> directSubclass = declaringClass;
while (directSubclass.getSuperclass() != actualClass) {
directSubclass = directSubclass.getSuperclass();
}
return directSubclass;
}
}
private static Type getGenericSuperclass(Class<?> subclass, Class<?> superclass) {
if (!superclass.isInterface()) {
return subclass.getGenericSuperclass();
} else {
for (Type genericInterface : subclass.getGenericInterfaces()) {
if (getRawType(genericInterface) == superclass) {
return genericInterface;
}
}
}
return superclass;
}
private static Type[] resolveTypeArguments(Class<?> subclass, Type supertype) {
if (supertype instanceof ParameterizedType) {
ParameterizedType parameterizedSupertype = (ParameterizedType) supertype;
return resolveTypeArguments(subclass, parameterizedSupertype);
} else {
return subclass.getTypeParameters();
}
}
private static Type[] resolveTypeArguments(Class<?> subclass, ParameterizedType parameterizedSupertype) {
Type genericSuperclass = getGenericSuperclass(subclass, getRawType(parameterizedSupertype));
if (!(genericSuperclass instanceof ParameterizedType)) {
return subclass.getTypeParameters();
}
ParameterizedType parameterizedSuperclass = (ParameterizedType) genericSuperclass;
Type[] typeParameters = subclass.getTypeParameters();
Type[] actualTypeArguments = parameterizedSupertype.getActualTypeArguments();
return resolveTypeArguments(parameterizedSuperclass, typeParameters, actualTypeArguments);
}
private static Type[] resolveTypeArguments(ParameterizedType subtype, ParameterizedType parameterizedSupertype) {
return resolveTypeArguments(getParameterizedType(getRawType(subtype)), parameterizedSupertype.getActualTypeArguments(), subtype.getActualTypeArguments());
}
private static Type[] resolveTypeArguments(ParameterizedType parameterizedType, Type[] typeParameters, Type[] actualTypeArguments) {
Type[] resolvedTypeArguments = new Type[typeParameters.length];
for (int i = 0; i < typeParameters.length; i++) {
resolvedTypeArguments[i] = resolveTypeArgument(parameterizedType, typeParameters[i], actualTypeArguments);
}
return resolvedTypeArguments;
}
private static Type resolveTypeArgument(ParameterizedType parameterizedType, Type typeParameter, Type[] actualTypeArguments) {
if (typeParameter instanceof TypeVariable) {
TypeVariable<?> variable = (TypeVariable<?>) typeParameter;
int index = getIndex(parameterizedType, variable);
if (index == -1) {
return typeParameter;
} else {
return actualTypeArguments[index];
}
} else if (typeParameter instanceof GenericArrayType) {
GenericArrayType array = (GenericArrayType) typeParameter;
return createArrayType(resolveTypeArgument(parameterizedType, array.getGenericComponentType(), actualTypeArguments));
} else {
return typeParameter;
}
}
private static Type createArrayType(Type componentType) {
if (componentType instanceof Class) {
return Array.newInstance((Class<?>) componentType, 0).getClass();
} else {
return new OwbGenericArrayTypeImpl(componentType);
}
}
public static Type resolveType(ParameterizedType parameterizedType, Type metadataType) {
return resolveType(parameterizedType, metadataType, newSeenList());
}
}
| 9,491 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/generics/OwbTypeVariableImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils.generics;
import java.lang.reflect.*;
import java.util.Arrays;
public class OwbTypeVariableImpl
{
private static final Class<?>[] TYPE_VARIABLE_TYPES = new Class<?>[]{TypeVariable.class};
/**
* Java TypeVariable is different in various JDK versions. Thus it is not possible to e.g.
* write a custom TypeVariable which works in either Java7 and Java8 as they introduced
* new methods in Java8 which have return generics which only exist in Java8 :(
*
* As workaround we dynamically crate a proxy to wrap this and do the delegation manually.
* This is of course slower, but as we do not use it often it might not have much impact.
*
* @param typeVariable
* @param bounds
* @return the typeVariable with the defined bounds.
*/
public static TypeVariable createTypeVariable(TypeVariable typeVariable, Type... bounds)
{
TypeVariable tv = (TypeVariable) Proxy.newProxyInstance(OwbTypeVariableImpl.class.getClassLoader(), TYPE_VARIABLE_TYPES,
new OwbTypeVariableInvocationHandler(typeVariable, bounds));
return tv;
}
public static class OwbTypeVariableInvocationHandler implements InvocationHandler
{
private String name;
private GenericDeclaration genericDeclaration;
private Type[] bounds;
public OwbTypeVariableInvocationHandler(TypeVariable typeVariable, Type... bounds)
{
name = typeVariable.getName();
genericDeclaration = typeVariable.getGenericDeclaration();
if (bounds == null || bounds.length == 0)
{
this.bounds = typeVariable.getBounds();
}
else
{
this.bounds = bounds;
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
String methodName = method.getName();
if ("equals".equals(methodName))
{
return typeVariableEquals(args[0]);
}
else if ("hashCode".equals(methodName))
{
return typeVariableHashCode();
}
else if ("toString".equals(methodName))
{
return typeVariableToString();
}
else if ("getName".equals(methodName))
{
return getName();
}
else if ("getGenericDeclaration".equals(methodName))
{
return getGenericDeclaration();
}
else if ("getBounds".equals(methodName))
{
return getBounds();
}
// new method from java8...
return null;
}
/** method from TypeVariable */
public String getName()
{
return name;
}
/** method from TypeVariable */
public GenericDeclaration getGenericDeclaration()
{
return genericDeclaration;
}
/** method from TypeVariable */
public Type[] getBounds()
{
return bounds.clone();
}
/** method from TypeVariable */
public int typeVariableHashCode()
{
return Arrays.hashCode(bounds) ^ name.hashCode() ^ genericDeclaration.hashCode();
}
/** method from TypeVariable */
public boolean typeVariableEquals(Object object)
{
if (this == object)
{
return true;
}
else if (object instanceof TypeVariable)
{
TypeVariable<?> that = (TypeVariable<?>)object;
return name.equals(that.getName()) && genericDeclaration.equals(that.getGenericDeclaration()) && Arrays.equals(bounds, that.getBounds());
}
else
{
return false;
}
}
/** method from TypeVariable */
public String typeVariableToString()
{
StringBuilder buffer = new StringBuilder();
buffer.append(name);
if (bounds.length > 0)
{
buffer.append(" extends ");
boolean first = true;
for (Type bound: bounds)
{
if (first)
{
first = false;
}
else
{
buffer.append(',');
}
buffer.append(' ').append(bound);
}
}
return buffer.toString();
}
}
}
| 9,492 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/generics/OwbGenericArrayTypeImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils.generics;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
public class OwbGenericArrayTypeImpl implements GenericArrayType {
private Type componentType;
public OwbGenericArrayTypeImpl(Type componentType) {
this.componentType = componentType;
}
@Override
public Type getGenericComponentType() {
return componentType;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return componentType.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof GenericArrayType) {
return ((GenericArrayType) obj).getGenericComponentType().equals(componentType);
} else {
return false;
}
}
public String toString() {
return componentType + "[]";
}
}
| 9,493 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/generics/OwbParametrizedTypeImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils.generics;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
/**
* Custom parametrized type implementation.
*
* @version $Rev: 1621935 $ $Date: 2014-09-02 09:07:32 +0200 (Tue, 02 Sep 2014) $
*/
public class OwbParametrizedTypeImpl implements ParameterizedType {
/**
* Owner type
*/
private final Type owner;
/**
* Raw type
*/
private final Type rawType;
/**
* Actual type arguments
*/
private final Type[] types;
/**
* New instance.
*
* @param owner owner
* @param raw raw
*/
public OwbParametrizedTypeImpl(Type owner, Type raw, Type... types) {
this.owner = owner;
rawType = raw;
this.types = types;
}
@Override
public Type[] getActualTypeArguments() {
return types.clone();
}
@Override
public Type getOwnerType() {
return owner;
}
@Override
public Type getRawType() {
return rawType;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Arrays.hashCode(types) ^ (owner == null ? 0 : owner.hashCode()) ^ (rawType == null ? 0 : rawType.hashCode());
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof ParameterizedType) {
ParameterizedType that = (ParameterizedType) obj;
Type thatOwnerType = that.getOwnerType();
Type thatRawType = that.getRawType();
return (owner == null ? thatOwnerType == null : owner.equals(thatOwnerType))
&& (rawType == null ? thatRawType == null : rawType.equals(thatRawType))
&& Arrays.equals(types, that.getActualTypeArguments());
} else {
return false;
}
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(((Class<?>) rawType).getName());
Type[] actualTypes = getActualTypeArguments();
if (actualTypes.length > 0) {
buffer.append("<");
int length = actualTypes.length;
for (int i = 0; i < length; i++) {
if (actualTypes[i] instanceof Class) {
buffer.append(((Class<?>) actualTypes[i]).getSimpleName());
} else {
buffer.append(actualTypes[i].toString());
}
if (i != actualTypes.length - 1) {
buffer.append(", ");
}
}
buffer.append(">");
}
return buffer.toString();
}
}
| 9,494 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/generics/ClassUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils.generics;
import java.lang.reflect.*;
import java.util.*;
/**
* Utility classes with respect to the class operations.
*
* @author <a href="mailto:gurkanerdogdu@yahoo.com">Gurkan Erdogdu</a>
* @since 1.0
*/
public final class ClassUtil {
public static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPERS_MAP;
static {
Map<Class<?>, Class<?>> primitiveToWrappersMap = new HashMap<Class<?>, Class<?>>();
primitiveToWrappersMap.put(Integer.TYPE, Integer.class);
primitiveToWrappersMap.put(Float.TYPE, Float.class);
primitiveToWrappersMap.put(Double.TYPE, Double.class);
primitiveToWrappersMap.put(Character.TYPE, Character.class);
primitiveToWrappersMap.put(Long.TYPE, Long.class);
primitiveToWrappersMap.put(Byte.TYPE, Byte.class);
primitiveToWrappersMap.put(Short.TYPE, Short.class);
primitiveToWrappersMap.put(Boolean.TYPE, Boolean.class);
primitiveToWrappersMap.put(Void.TYPE, Void.class);
PRIMITIVE_TO_WRAPPERS_MAP = Collections.unmodifiableMap(primitiveToWrappersMap);
}
public static final Type[] NO_TYPES = new Type[0];
/*
* Private constructor
*/
private ClassUtil() {
throw new UnsupportedOperationException();
}
public static boolean isSame(Type type1, Type type2) {
if ((type1 instanceof Class) && ((Class<?>) type1).isPrimitive()) {
type1 = PRIMITIVE_TO_WRAPPERS_MAP.get(type1);
}
if ((type2 instanceof Class) && ((Class<?>) type2).isPrimitive()) {
type2 = PRIMITIVE_TO_WRAPPERS_MAP.get(type2);
}
return type1 == type2;
}
public static Class<?> getPrimitiveWrapper(Class<?> clazz) {
return PRIMITIVE_TO_WRAPPERS_MAP.get(clazz);
}
/**
* Gets the class of the given type arguments.
* <p>
* If the given type {@link Type} parameters is an instance of the
* {@link ParameterizedType}, it returns the raw type otherwise it return
* the casted {@link Class} of the type argument.
* </p>
*
* @param type class or parametrized type
* @return
*/
public static Class<?> getClass(Type type)
{
return getClazz(type);
}
/**
* Returns true if type is an instance of <code>ParameterizedType</code>
* else otherwise.
*
* @param type type of the artifact
* @return true if type is an instance of <code>ParameterizedType</code>
*/
public static boolean isParametrizedType(Type type)
{
return type instanceof ParameterizedType;
}
/**
* Returns true if type is an instance of <code>WildcardType</code>
* else otherwise.
*
* @param type type of the artifact
* @return true if type is an instance of <code>WildcardType</code>
*/
public static boolean isWildCardType(Type type)
{
return type instanceof WildcardType;
}
/**
* Returns true if rhs is assignable type
* to the lhs, false otherwise.
*
* @param lhs left hand side class
* @param rhs right hand side class
* @return true if rhs is assignable to lhs
*/
public static boolean isClassAssignableFrom(Class<?> lhs, Class<?> rhs)
{
if(lhs.isPrimitive())
{
lhs = getPrimitiveWrapper(lhs);
}
if(rhs.isPrimitive())
{
rhs = getPrimitiveWrapper(rhs);
}
if (lhs.isAssignableFrom(rhs))
{
return true;
}
return false;
}
/**
* Return raw class type for given type.
*
* @param type base type instance
* @return class type for given type
*/
public static Class<?> getClazz(Type type) {
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
return (Class<?>) pt.getRawType();
} else if (type instanceof Class) {
return (Class<?>) type;
} else if (type instanceof GenericArrayType) {
GenericArrayType arrayType = (GenericArrayType) type;
return Array.newInstance(getClazz(arrayType.getGenericComponentType()), 0).getClass();
} else if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
Type[] bounds = wildcardType.getUpperBounds();
if (bounds.length > 1) {
throw new IllegalArgumentException("Illegal use of wild card type with more than one upper bound: " + wildcardType);
} else if (bounds.length == 0) {
return Object.class;
} else {
return getClass(bounds[0]);
}
} else if (type instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) type;
if (typeVariable.getBounds().length > 1) {
throw new IllegalArgumentException("Illegal use of type variable with more than one bound: " + typeVariable);
} else {
Type[] bounds = typeVariable.getBounds();
if (bounds.length == 0) {
return Object.class;
} else {
return getClass(bounds[0]);
}
}
} else {
throw new IllegalArgumentException("Unsupported type " + type);
}
}
public static boolean isRawClassEquals(Type ipType, Type apiType) {
Class ipClass = getRawPrimitiveType(ipType);
Class apiClass = getRawPrimitiveType(apiType);
if (ipClass == null || apiClass == null) {
// we found some illegal generics
return false;
}
return ipClass.equals(apiClass);
}
private static Class getRawPrimitiveType(Type type) {
if (type instanceof Class) {
if (((Class) type).isPrimitive()) {
return getPrimitiveWrapper((Class) type);
}
return (Class) type;
}
if (type instanceof ParameterizedType) {
return getRawPrimitiveType(((ParameterizedType) type).getRawType());
}
return null;
}
}
| 9,495 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/generics/TypeInference.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils.generics;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import java.lang.reflect.*;
import java.util.*;
public class TypeInference {
public static class Match<E> {
final E e;
final List<TypedObject> args;
final Map<TypeVariable<?>, Type> inferred;
final int score;
Match(E e, List<TypedObject> args, Map<TypeVariable<?>, Type> inferred, int score) {
this.e = e;
this.args = args;
this.inferred = inferred;
this.score = score;
}
public E getMember() {
return e;
}
public List<TypedObject> getArgs() {
return args;
}
public Map<TypeVariable<?>, Type> getInferred() {
return inferred;
}
public int getScore() {
return score;
}
}
public static class TypedObject {
final Type type;
final Object value;
public TypedObject(Type type, Object value) {
this.type = type;
this.value = value;
}
public Type getType() {
return type;
}
public Object getValue() {
return value;
}
}
public interface Converter {
TypedObject convert(TypedObject from, Type to) throws Exception;
}
private interface Executable<T> {
T getMember();
Type[] getGenericParameterTypes();
}
private static class ConstructorExecutable implements Executable<Constructor<?>> {
private final Constructor<?> constructor;
private ConstructorExecutable(Constructor<?> constructor) {
this.constructor = constructor;
}
@Override
public Constructor<?> getMember() {
return constructor;
}
@Override
public Type[] getGenericParameterTypes() {
return constructor.getGenericParameterTypes();
}
}
private static class MethodExecutable implements Executable<Method> {
private final Method method;
private MethodExecutable(Method method) {
this.method = method;
}
@Override
public Method getMember() {
return method;
}
@Override
public Type[] getGenericParameterTypes() {
return method.getGenericParameterTypes();
}
}
public static List<Match<Constructor<?>>> findMatchingConstructors(Type clazz, List<TypedObject> args, Converter converter, boolean reorder) {
List<Executable<Constructor<?>>> executables = findConstructors(clazz, args.size());
return findMatching(executables, args, converter, reorder);
}
public static List<Match<Method>> findMatchingMethods(Type clazz, String name, List<TypedObject> args, Converter converter, boolean reorder) {
List<Executable<Method>> executables = findMethods(clazz, name, true, args.size());
return findMatching(executables, args, converter, reorder);
}
public static List<Match<Method>> findMatchingStatics(Type clazz, String name, List<TypedObject> args, Converter converter, boolean reorder) {
List<Executable<Method>> executables = findMethods(clazz, name, false, args.size());
return findMatching(executables, args, converter, reorder);
}
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();
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;
} 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 static List<Executable<Constructor<?>>> findConstructors(Type clazz, int size) {
List<Constructor<?>> constructors = new ArrayList<Constructor<?>>();
for (Constructor<?> constructor : ClassUtil.getClass(clazz).getConstructors()) {
if (constructor.getGenericParameterTypes().length != size) {
continue;
}
constructors.add(constructor);
}
List<Executable<Constructor<?>>> executables = new ArrayList<Executable<Constructor<?>>>();
for (Constructor<?> constructor : constructors) {
executables.add(new ConstructorExecutable(constructor));
}
return executables;
}
private static List<Executable<Method>> findMethods(Type clazz, String name, boolean instance, int size) {
List<Method> methods = new ArrayList<Method>();
for (Method method : ReflectionUtils.getPublicMethods(ClassUtil.getClass(clazz))) {
if (instance == Modifier.isStatic(method.getModifiers())) {
continue;
}
if (method.isBridge()) {
continue;
}
if (!method.getName().equals(name)) {
continue;
}
if (method.getGenericParameterTypes().length != size) {
continue;
}
methods.add(method);
}
methods = applyStaticHidingRules(methods);
List<Executable<Method>> executables = new ArrayList<Executable<Method>>();
for (Method method : methods) {
executables.add(new MethodExecutable(method));
}
return executables;
}
private static final long COST_ASSIGN = 1L;
private static final long COST_CAST = 100L;
private static final long COST_CONVERT = 10000L;
private static <E> List<Match<E>> findMatching(List<Executable<E>> executables, List<TypedObject> args, Converter converter, boolean reorder) {
Comparator<Match<E>> comparator = new Comparator<Match<E>>() {
@Override
public int compare(Match<E> o1, Match<E> o2) {
return o1.getScore() - o2.getScore();
}
};
List<Match<E>> matches = new ArrayList<Match<E>>();
for (Executable<E> e : executables) {
Match<E> match = match(e, args, converter);
if (match != null) {
matches.add(match);
}
}
Collections.sort(matches, comparator);
if (matches.isEmpty() && reorder) {
for (long p = 1, l = factorial(args.size()); p < l; p++) {
List<TypedObject> pargs = permutation(p, args);
for (Executable<E> e : executables) {
Match<E> match = match(e, pargs, converter);
if (match != null) {
matches.add(match);
}
}
}
Collections.sort(matches, comparator);
}
return matches;
}
private static <E> Match<E> match(Executable<E> executable, List<TypedObject> args, Converter converter) {
Map<TypeVariable<?>, Type> variables = new HashMap<TypeVariable<?>, Type>();
Type[] parameterTypes = executable.getGenericParameterTypes();
boolean allowCast = true;
for (int i = 0; i < parameterTypes.length; i++) {
TypedObject arg = args.get(i);
Type needed = parameterTypes[i];
if (GenericsUtil.containsTypeVariable(needed)
&& ClassUtil.getClass(needed).isAssignableFrom(ClassUtil.getClass(arg.type))) {
try {
Type[] neededTypes = getParameters(needed);
Type[] actualTypes = getParameters(ClassUtil.getClass(needed), arg.type);
for (int j = 0; j < neededTypes.length; j++) {
if (neededTypes[j] instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) neededTypes[j];
Type t = variables.get(tv);
t = mergeBounds(t, actualTypes[j]);
variables.put(tv, t);
}
}
} catch (IllegalArgumentException e) {
allowCast = false;
}
}
}
int score = 0;
List<TypedObject> converted = new ArrayList<TypedObject>();
for (int i = 0; i < parameterTypes.length; i++) {
TypedObject arg = args.get(i);
Type needed = parameterTypes[i];
long sc;
if (arg.type == null || needed == arg.type) {
sc = COST_ASSIGN;
} else if (allowCast && ClassUtil.getClass(needed).isAssignableFrom(ClassUtil.getClass(arg.type))) {
sc = COST_CAST;
} else {
sc = COST_CONVERT;
}
try {
Type real = mapVariables(needed, variables);
converted.add(converter.convert(arg, real));
score += sc;
} catch (Exception e) {
return null;
}
}
return new Match<E>(executable.getMember(), converted, variables, score);
}
private static Type[] mapVariables(Type[] types, Map<TypeVariable<?>, Type> variables) {
Type[] resolved = new Type[types.length];
for (int i = 0; i < types.length; i++) {
resolved[i] = mapVariables(types[i], variables);
}
return resolved;
}
private static Type mapVariables(Type type, Map<TypeVariable<?>, Type> variables) {
if (type == null) {
return null;
} else if (type instanceof Class) {
return type;
} else if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
return new OwbParametrizedTypeImpl(
mapVariables(pt.getOwnerType(), variables),
mapVariables(pt.getRawType(), variables),
mapVariables(pt.getActualTypeArguments(), variables));
} else if (type instanceof TypeVariable) {
return variables.containsKey(type) ? variables.get(type) : type;
} else if (type instanceof WildcardType) {
WildcardType wt = (WildcardType) type;
return new OwbWildcardTypeImpl(
mapVariables(wt.getUpperBounds(), variables),
mapVariables(wt.getLowerBounds(), variables));
} else if (type instanceof GenericArrayType) {
GenericArrayType gat = (GenericArrayType) type;
return new OwbGenericArrayTypeImpl(mapVariables(gat.getGenericComponentType(), variables));
} else {
throw new UnsupportedOperationException();
}
}
private static Type mergeBounds(Type t1, Type t2) {
Set<Type> types = new HashSet<Type>();
TypeVariable vt = null;
if (t1 instanceof TypeVariable) {
Collections.addAll(types, ((TypeVariable) t1).getBounds());
vt = (TypeVariable) t1;
} else if (t1 != null) {
types.add(t1);
}
if (t2 instanceof TypeVariable) {
Collections.addAll(types, ((TypeVariable) t2).getBounds());
vt = (TypeVariable) t2;
} else if (t2 != null) {
types.add(t2);
}
List<Type> bounds = new ArrayList<Type>();
Class cl = null;
for (Type type : types) {
if (isClass(type)) {
cl = cl != null ? reduceClasses(cl, (Class) type) : (Class) type;
}
}
if (cl != null) {
bounds.add(cl);
}
List<Type> l = Collections.emptyList();
for (Type type : types) {
if (!isClass(type)) {
l = reduceTypes(l, Collections.singletonList(type));
}
}
bounds.addAll(l);
if (bounds.size() == 1) {
return bounds.get(0);
} else {
return OwbTypeVariableImpl.createTypeVariable(vt, bounds.toArray(new Type[bounds.size()]));
}
}
private static boolean isClass(Type t) {
Class c = ClassUtil.getClass(t);
return !c.isInterface() && !c.isEnum();
}
private static List<Type> reduceTypes(List<Type> l1, List<Type> l2) {
List<Type> types = new ArrayList<Type>();
for (Type t1 : l1) {
boolean discard = false;
for (Type t2 : l2) {
discard |= GenericsUtil.isAssignableFrom(false, false, t1, t2);
}
if (!discard) {
types.add(t1);
}
}
for (Type t2 : l2) {
boolean discard = false;
for (Type t1 : l1) {
discard |= GenericsUtil.isAssignableFrom(false, false, t1, t2);
}
if (!discard) {
types.add(t2);
}
}
return types;
}
private static Class reduceClasses(Class<?> c1, Class<?> c2) {
if (c1.isAssignableFrom(c2)) {
return c1;
} else if (c2.isAssignableFrom(c1)) {
return c2;
} else {
throw new IllegalArgumentException("Illegal bounds: " + c1 + ", " + c2);
}
}
private static Type[] getParameters(Class<?> neededClass, Type type) {
return GenericsUtil.resolveTypes(getParameters(neededClass), type);
}
private static long factorial(int n) {
if (n > 20 || n < 0) throw new IllegalArgumentException(n + " is out of range");
long l = 1L;
for (int i = 2; i <= n; i++) {
l *= i;
}
return l;
}
private static <T> List<T> permutation(long no, List<T> items) {
return permutationHelper(no, new LinkedList<T>(items), new ArrayList<T>());
}
private static <T> List<T> permutationHelper(long no, LinkedList<T> in, List<T> out) {
if (in.isEmpty()) return out;
long subFactorial = factorial(in.size() - 1);
out.add(in.remove((int) (no / subFactorial)));
return permutationHelper((int) (no % subFactorial), in, out);
}
private static Type[] getParameters(Type type) {
if (type instanceof Class) {
Class clazz = (Class) type;
if (clazz.isArray()) {
return clazz.getComponentType().getTypeParameters();
} else {
return clazz.getTypeParameters();
}
}
if (type instanceof ParameterizedType) {
return ((ParameterizedType) type).getActualTypeArguments();
}
throw new RuntimeException("Unknown type " + type);
}
}
| 9,496 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading/RWLock.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.utils.threading;
import java.util.concurrent.Callable;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
public class RWLock {
private ReentrantReadWriteLock _lock = new ReentrantReadWriteLock();
public <T> T runReadOperation(Callable<T> call) throws Exception {
ReadLock rl = _lock.readLock();
rl.lock();
try {
return call.call();
} finally {
rl.unlock();
}
}
public void runReadOperation(Runnable r) {
ReadLock rl = _lock.readLock();
rl.lock();
try {
r.run();
} finally {
rl.unlock();
}
}
public <T> T runWriteOperation(Callable<T> call) throws Exception {
WriteLock wl = _lock.writeLock();
wl.lock();
try {
return call.call();
} finally {
wl.unlock();
}
}
public void runWriteOperation(Runnable r) {
WriteLock wl = _lock.writeLock();
wl.lock();
try {
r.run();
} finally {
wl.unlock();
}
}
} | 9,497 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading/ScheduledExecutorServiceWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.utils.threading;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.aries.blueprint.utils.threading.impl.Discardable;
import org.apache.aries.blueprint.utils.threading.impl.DiscardableCallable;
import org.apache.aries.blueprint.utils.threading.impl.DiscardableRunnable;
import org.apache.aries.blueprint.utils.threading.impl.WrappedFuture;
import org.apache.aries.blueprint.utils.threading.impl.WrappedScheduledFuture;
import org.apache.aries.util.tracker.SingleServiceTracker;
import org.apache.aries.util.tracker.SingleServiceTracker.SingleServiceListener;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
/**
* This class looks like a ScheduledExecutorService to the outside world. Internally it uses either
* a scheduled thread pool with a core size of 3, or it picks one up from the service registry. If
* it picks one up from the service registry then it shuts the internal one down. This doesn't fully meet
* the spec for a SchedueledExecutorService. It does not properly implement shutdownNow, but this isn't used
* by blueprint so for now that should be fine.
* <p>
* <p>It also wraps the Runnables and Callables so when a task is canceled we quickly clean up memory rather
* than waiting for the target to get to the task and purge it.
* </p>
*/
public class ScheduledExecutorServiceWrapper implements ScheduledExecutorService, SingleServiceListener {
public interface ScheduledExecutorServiceFactory {
ScheduledExecutorService create(String name);
}
private final AtomicReference<ScheduledExecutorService> _current = new AtomicReference<ScheduledExecutorService>();
private SingleServiceTracker<ScheduledExecutorService> _tracked;
private final AtomicReference<ScheduledExecutorService> _default = new AtomicReference<ScheduledExecutorService>();
private final AtomicBoolean _shutdown = new AtomicBoolean();
private final Queue<Discardable<Runnable>> _unprocessedWork = new LinkedBlockingQueue<Discardable<Runnable>>();
private final RWLock _lock = new RWLock();
private final AtomicInteger _invokeEntryCount = new AtomicInteger();
private final ScheduledExecutorServiceFactory _factory;
private final String _name;
public ScheduledExecutorServiceWrapper(BundleContext context, String name, ScheduledExecutorServiceFactory sesf) {
_name = name;
_factory = sesf;
try {
_tracked = new SingleServiceTracker<ScheduledExecutorService>(context, ScheduledExecutorService.class, "(aries.blueprint.poolName=" + _name + ")", this);
_tracked.open();
} catch (InvalidSyntaxException e) {
// Just ignore and stick with the default one.
}
if (_current.get() == null) {
_default.set(_factory.create(name));
if (!!!_current.compareAndSet(null, _default.get())) {
_default.getAndSet(null).shutdown();
}
}
}
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
long timeLeftToWait = unit.toMillis(timeout);
long pausePeriod = timeLeftToWait;
if (pausePeriod > 1000) pausePeriod = 1000;
while (!!!_unprocessedWork.isEmpty() && _invokeEntryCount.get() > 0 && timeLeftToWait > 0) {
Thread.sleep(pausePeriod);
timeLeftToWait -= pausePeriod;
if (timeLeftToWait < pausePeriod) pausePeriod = timeLeftToWait;
}
return _unprocessedWork.isEmpty() && _invokeEntryCount.get() > 0;
}
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks)
throws InterruptedException {
try {
return runUnlessShutdown(new Callable<List<Future<T>>>() {
public List<Future<T>> call() throws Exception {
_invokeEntryCount.incrementAndGet();
try {
return _current.get().invokeAll(tasks);
} finally {
_invokeEntryCount.decrementAndGet();
}
}
});
} catch (InterruptedException e) {
throw e;
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks,
final long timeout,
final TimeUnit unit) throws InterruptedException {
try {
return runUnlessShutdown(new Callable<List<Future<T>>>() {
public List<Future<T>> call() throws Exception {
_invokeEntryCount.incrementAndGet();
try {
return _current.get().invokeAll(tasks, timeout, unit);
} finally {
_invokeEntryCount.decrementAndGet();
}
}
});
} catch (InterruptedException e) {
throw e;
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks) throws InterruptedException,
ExecutionException {
try {
return runUnlessShutdown(new Callable<T>() {
public T call() throws Exception {
_invokeEntryCount.incrementAndGet();
try {
return _current.get().invokeAny(tasks);
} finally {
_invokeEntryCount.decrementAndGet();
}
}
});
} catch (InterruptedException e) {
throw e;
} catch (ExecutionException e) {
throw e;
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
try {
return runUnlessShutdown(new Callable<T>() {
public T call() throws Exception {
_invokeEntryCount.incrementAndGet();
try {
return _current.get().invokeAny(tasks, timeout, unit);
} finally {
_invokeEntryCount.decrementAndGet();
}
}
});
} catch (InterruptedException e) {
throw e;
} catch (ExecutionException e) {
throw e;
} catch (TimeoutException e) {
throw e;
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
public boolean isShutdown() {
return _shutdown.get();
}
public boolean isTerminated() {
if (isShutdown()) return _unprocessedWork.isEmpty();
else return false;
}
public void shutdown() {
_lock.runWriteOperation(new Runnable() {
public void run() {
_shutdown.set(true);
ScheduledExecutorService s = _default.get();
if (s != null) s.shutdown();
}
});
}
public List<Runnable> shutdownNow() {
try {
return _lock.runWriteOperation(new Callable<List<Runnable>>() {
public List<Runnable> call() {
_shutdown.set(true);
ScheduledExecutorService s = _default.get();
if (s != null) s.shutdownNow();
List<Runnable> runnables = new ArrayList<Runnable>();
for (Discardable<Runnable> r : _unprocessedWork) {
Runnable newRunnable = r.discard();
if (newRunnable != null) {
runnables.add(newRunnable);
}
}
return runnables;
}
});
} catch (Exception e) {
// This wont happen since our callable doesn't throw any exceptions, so we just return an empty list
return Collections.emptyList();
}
}
public <T> Future<T> submit(final Callable<T> task) {
try {
return runUnlessShutdown(new Callable<Future<T>>() {
public Future<T> call() throws Exception {
DiscardableCallable<T> t = new DiscardableCallable<T>(task, _unprocessedWork);
try {
return new WrappedFuture<T>(_current.get().submit((Callable<T>) t), t);
} catch (RuntimeException e) {
t.discard();
throw e;
}
}
});
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
public Future<?> submit(final Runnable task) {
try {
return runUnlessShutdown(new Callable<Future<?>>() {
public Future<?> call() {
DiscardableRunnable t = new DiscardableRunnable(task, _unprocessedWork);
try {
return new WrappedFuture(_current.get().submit(t), t);
} catch (RuntimeException e) {
t.discard();
throw e;
}
}
});
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
public <T> Future<T> submit(final Runnable task, final T result) {
try {
return runUnlessShutdown(new Callable<Future<T>>() {
public Future<T> call() {
DiscardableRunnable t = new DiscardableRunnable(task, _unprocessedWork);
try {
return new WrappedFuture<T>(_current.get().submit(t, result), t);
} catch (RuntimeException e) {
t.discard();
throw e;
}
}
});
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
public void execute(final Runnable command) {
try {
runUnlessShutdown(new Callable<Object>() {
public Object call() {
DiscardableRunnable t = new DiscardableRunnable(command, _unprocessedWork);
try {
_current.get().execute(t);
} catch (RuntimeException e) {
t.discard();
throw e;
}
return null;
}
});
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) {
try {
return runUnlessShutdown(new Callable<ScheduledFuture<?>>() {
public ScheduledFuture<?> call() {
DiscardableRunnable t = new DiscardableRunnable(command, _unprocessedWork);
try {
return new WrappedScheduledFuture(_current.get().schedule(t, delay, unit), t);
} catch (RuntimeException e) {
t.discard();
throw e;
}
}
});
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
public <V> ScheduledFuture<V> schedule(final Callable<V> callable, final long delay, final TimeUnit unit) {
try {
return runUnlessShutdown(new Callable<ScheduledFuture<V>>() {
public ScheduledFuture<V> call() {
DiscardableCallable<V> c = new DiscardableCallable<V>(callable, _unprocessedWork);
try {
return new WrappedScheduledFuture<V>(_current.get().schedule((Callable<V>) c, delay, unit), c);
} catch (RuntimeException e) {
c.discard();
throw e;
}
}
});
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
public ScheduledFuture<?> scheduleAtFixedRate(final Runnable command, final long initialDelay, final long period,
final TimeUnit unit) {
try {
return runUnlessShutdown(new Callable<ScheduledFuture<?>>() {
public ScheduledFuture<?> call() {
DiscardableRunnable t = new DiscardableRunnable(command, _unprocessedWork);
try {
return new WrappedScheduledFuture(_current.get().scheduleAtFixedRate(t, initialDelay, period, unit), t);
} catch (RuntimeException e) {
t.discard();
throw e;
}
}
});
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
public ScheduledFuture<?> scheduleWithFixedDelay(final Runnable command, final long initialDelay, final long delay,
final TimeUnit unit) {
try {
return runUnlessShutdown(new Callable<ScheduledFuture<?>>() {
public ScheduledFuture<?> call() {
DiscardableRunnable t = new DiscardableRunnable(command, _unprocessedWork);
try {
return new WrappedScheduledFuture(_current.get().scheduleWithFixedDelay(t, initialDelay, delay, unit), t);
} catch (RuntimeException e) {
t.discard();
throw e;
}
}
});
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
public void serviceFound() {
ScheduledExecutorService s = _default.get();
if (_current.compareAndSet(s, _tracked.getService())) {
if (s != null) {
if (_default.compareAndSet(s, null)) {
s.shutdown();
}
}
}
}
// TODO when lost or replaced we need to move work to the "new" _current. This is a huge change because the futures are not currently stored.
public void serviceLost() {
ScheduledExecutorService s = _default.get();
if (s == null) {
s = _factory.create(_name);
if (_default.compareAndSet(null, s)) {
_current.set(s);
}
}
}
public void serviceReplaced() {
_current.set(_tracked.getService());
}
private <T> T runUnlessShutdown(final Callable<T> call) throws InterruptedException, ExecutionException, TimeoutException {
try {
return _lock.runReadOperation(new Callable<T>() {
public T call() throws Exception {
if (isShutdown()) throw new RejectedExecutionException();
return call.call();
}
});
} catch (InterruptedException e) {
throw e;
} catch (ExecutionException e) {
throw e;
} catch (TimeoutException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RejectedExecutionException();
}
}
} | 9,498 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading/impl/DiscardableRunnable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.utils.threading.impl;
import java.util.Collections;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
public class DiscardableRunnable implements Runnable, Discardable<Runnable> {
private AtomicReference<Runnable> r = new AtomicReference<Runnable>();
private Queue<Discardable<Runnable>> _removeFromListOnRun;
public DiscardableRunnable(Runnable run, Queue<Discardable<Runnable>> _unprocessedWork) {
r.set(run);
_removeFromListOnRun = _unprocessedWork;
_removeFromListOnRun.add(this);
}
private DiscardableRunnable(Runnable run) {
r.set(run);
_removeFromListOnRun = new LinkedBlockingQueue<Discardable<Runnable>>();
}
public void run() {
_removeFromListOnRun.remove(this);
Runnable run = r.get();
if (run != null) {
run.run();
}
}
public Runnable discard() {
_removeFromListOnRun.remove(this);
return new DiscardableRunnable(r.getAndSet(null));
}
} | 9,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.