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/itests/blueprint-testbundleb/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundleb/src/main/java/org/apache/aries/blueprint/testbundleb/BeanForBeanProcessorTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.testbundleb;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.testbundlea.ProcessableBean;
public class BeanForBeanProcessorTest implements ProcessableBean{
Set<BeanProcessor> bps = new HashSet<BeanProcessor>();
Set<BeanProcessor> ad_bps = new HashSet<BeanProcessor>();
Set<BeanProcessor> ai_bps = new HashSet<BeanProcessor>();
Set<BeanProcessor> bd_bps = new HashSet<BeanProcessor>();
Set<BeanProcessor> bi_bps = new HashSet<BeanProcessor>();
private List<BeanProcessor> toList(Set<BeanProcessor> s){
List<BeanProcessor> lbps = new ArrayList<BeanProcessor>();
lbps.addAll(s);
return lbps;
}
public List<BeanProcessor> getProcessedBy() {
return toList(bps);
}
public List<BeanProcessor> getProcessedBy(Phase p) {
switch(p){
case BEFORE_INIT : return toList(bi_bps);
case AFTER_INIT : return toList(ai_bps);
case BEFORE_DESTROY : return toList(bd_bps);
case AFTER_DESTROY : return toList(ad_bps);
default: return null;
}
}
public void processAfterDestroy(BeanProcessor bp) {
bps.add(bp);
ad_bps.add(bp);
}
public void processAfterInit(BeanProcessor bp) {
bps.add(bp);
ai_bps.add(bp);
}
public void processBeforeDestroy(BeanProcessor bp) {
bps.add(bp);
bd_bps.add(bp);
}
public void processBeforeInit(BeanProcessor bp) {
bps.add(bp);
bi_bps.add(bp);
}
}
| 9,100 |
0 | Create_ds/aries/blueprint/itests/blueprint-testbundleb/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundleb/src/main/java/org/apache/aries/blueprint/testbundleb/TestBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.testbundleb;
public class TestBean {
private String red;
private String green;
private String blue;
public void init(){
setRed("EMPTY");
setGreen("EMPTY");
setBlue("EMPTY");
}
public String getRed() {
return red;
}
public void setRed(String red) {
this.red = red;
}
public String getGreen() {
return green;
}
public void setGreen(String green) {
this.green = green;
}
public String getBlue() {
return blue;
}
public void setBlue(String blue) {
this.blue = blue;
}
public boolean methodToInvoke(String argument){
if(argument!=null){
if(argument.equals(red)){
return true;
}
if(argument.equals(green)){
throw new RuntimeException("MATCHED ON GREEN ("+green+")");
}
}
return false;
}
}
| 9,101 |
0 | Create_ds/aries/blueprint/itests/blueprint-testbundleb/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundleb/src/main/java/org/apache/aries/blueprint/testbundleb/Activator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.blueprint.testbundleb;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
public void start(BundleContext context) {
}
public void stop(BundleContext context) {
}
}
| 9,102 |
0 | Create_ds/aries/blueprint/itests/blueprint-testbundleb/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundleb/src/main/java/org/apache/aries/blueprint/testbundleb/OtherBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.testbundleb;
public class OtherBean {
private TestBean testBean;
private String testValue;
public String getTestValue() {
return testValue;
}
public void setTestValue(String testValue) {
this.testValue = testValue;
}
public TestBean getTestBean() {
return testBean;
}
public void setTestBean(TestBean testBean) {
this.testBean = testBean;
}
public void init(){
try{
this.testBean.methodToInvoke(testValue);
}catch(Throwable t){
//ignore error.
}
}
}
| 9,103 |
0 | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint/testbundlee/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.testbundlee;
public class BeanA {
public BeanA(String arg1) {
}
}
| 9,104 |
0 | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint/testbundlee/BeanCItf.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.testbundlee;
public interface BeanCItf {
void doSomething();
int getInitialized();
}
| 9,105 |
0 | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint/testbundlee/BeanAFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.testbundlee;
public class BeanAFactory {
public static BeanA createBean(String arg1) {
return new BeanA(arg1);
}
}
| 9,106 |
0 | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint/testbundlee/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.testbundlee;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class BeanB implements ApplicationContextAware {
private BeanA beanA;
private ApplicationContext applicationContext;
public BeanA getBeanA() {
return beanA;
}
public void setBeanA(BeanA beanA) {
this.beanA = beanA;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
| 9,107 |
0 | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-testbundlee/src/main/java/org/apache/aries/blueprint/testbundlee/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.testbundlee;
import javax.annotation.PostConstruct;
import org.springframework.transaction.annotation.Transactional;
public class BeanC implements BeanCItf {
private final BeanA beanA;
private int initialized;
protected BeanC() {
this.beanA = null;
}
public BeanC(BeanA beanA) {
this.beanA = beanA;
}
@PostConstruct
public void start() {
this.initialized++;
}
@Transactional
public void doSomething() {
}
public int getInitialized() {
return initialized;
}
}
| 9,108 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/TestRegistrationListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import org.apache.aries.blueprint.BlueprintConstants;
import org.apache.aries.blueprint.sample.Foo;
import org.apache.aries.blueprint.sample.FooRegistrationListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.service.blueprint.container.BlueprintContainer;
@RunWith(PaxExam.class)
public class TestRegistrationListener extends AbstractBlueprintIntegrationTest {
@Test
public void testWithAutoExportEnabled() throws Exception {
BlueprintContainer blueprintContainer =
Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
assertNotNull(blueprintContainer);
Foo foo = context().getService(Foo.class, "(" + BlueprintConstants.COMPONENT_NAME_PROPERTY + "=foo)");
assertEquals(5, foo.getA());
FooRegistrationListener listener =
(FooRegistrationListener) blueprintContainer.getComponentInstance("fooRegistrationListener");
// If registration listener works fine, the registration method should
// have already been called and properties that were passed to this
// method should have been not null
Map<?, ?> props = listener.getProperties();
assertNotNull(props);
assertTrue(props.containsKey(BlueprintConstants.COMPONENT_NAME_PROPERTY));
assertEquals("foo", props.get(BlueprintConstants.COMPONENT_NAME_PROPERTY));
assertTrue(props.containsKey("key"));
assertEquals("value", props.get("key"));
}
@Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample")
};
}
}
| 9,109 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/TestConfigAdmin.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import java.util.Currency;
import java.util.Hashtable;
import javax.inject.Inject;
import org.apache.aries.blueprint.sample.Foo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerMethod.class)
public class TestConfigAdmin extends AbstractBlueprintIntegrationTest {
@Inject
ConfigurationAdmin ca;
@Test
public void testStrategyNone() throws Exception {
ca.getConfiguration("blueprint-sample-managed.none", null).update(getConfig1());
startTestBundle();
// foo should receive initial configuration
Foo foo = getComponent("none-managed");
assertEquals(5, foo.getA());
assertEquals(Currency.getInstance("PLN"), foo.getCurrency());
// foo should not reflect changes in config
ca.getConfiguration("blueprint-sample-managed.none", null).update(getConfig2());
Thread.sleep(100);
assertEquals(5, foo.getA());
assertEquals(Currency.getInstance("PLN"), foo.getCurrency());
}
@Test
public void testStrategyContainer() throws Exception {
// foo should have received initial configuration
ca.getConfiguration("blueprint-sample-managed.container", null).update(getConfig1());
startTestBundle();
Foo foo = getComponent("container-managed");
assertEquals(5, foo.getA());
assertEquals(Currency.getInstance("PLN"), foo.getCurrency());
// foo bean properties should have been updated
ca.getConfiguration("blueprint-sample-managed.container", null).update(getConfig2());
Thread.sleep(100);
assertEquals(10, foo.getA());
assertEquals(Currency.getInstance("USD"), foo.getCurrency());
}
@Test
public void testStrategyComponent() throws Exception {
// foo should receive initial configuration
ca.getConfiguration("blueprint-sample-managed.component", null).update(getConfig1());
startTestBundle();
Foo foo = getComponent("component-managed");
assertEquals(5, foo.getA());
assertEquals(Currency.getInstance("PLN"), foo.getCurrency());
// Foo.update() should have been called but the bean properties should not have been updated
ca.getConfiguration("blueprint-sample-managed.component", null).update(getConfig2());
Thread.sleep(100);
assertEquals(5, foo.getA());
assertEquals(Currency.getInstance("PLN"), foo.getCurrency());
assertNotNull(foo.getProps());
assertEquals("10", foo.getProps().get("a"));
assertEquals("USD", foo.getProps().get("currency"));
}
@SuppressWarnings("rawtypes")
@Test
public void testManagedServiceFactory() throws Exception {
Configuration cf = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory", null);
cf.update(getConfig1());
startTestBundle();
// Make sure only one service is registered
// Ask the service registry, not the container, since the container might have got it wrong :)
Foo foo = context().getService(Foo.class, "(service.pid=blueprint-sample-managed-service-factory.*)");
ServiceReference[] refs = context().getAllServiceReferences(Foo.class.getName(), "(service.pid=blueprint-sample-managed-service-factory.*)");
assertNotNull("No services were registered for the managed service factory", refs);
assertEquals("Multiple services were registered for the same pid.", 1, refs.length);
}
@Test
public void testPlaceholder() throws Exception {
Configuration cf = ca.getConfiguration("blueprint-sample-placeholder", null);
cf.update(getConfig3());
startTestBundle();
}
private Hashtable<String, String> getConfig1() {
Hashtable<String,String> props = new Hashtable<String,String>();
props.put("a", "5");
props.put("currency", "PLN");
return props;
}
private Hashtable<String, String> getConfig2() {
Hashtable<String, String> props;
props = new Hashtable<String,String>();
props.put("a", "10");
props.put("currency", "USD");
return props;
}
private Hashtable<String, String> getConfig3() {
Hashtable<String, String> props;
props = new Hashtable<String,String>();
props.put("key.b", "10");
return props;
}
private <T>T getComponent(String componentId) {
BlueprintContainer blueprintContainer = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
assertNotNull(blueprintContainer);
@SuppressWarnings("unchecked")
T component = (T)blueprintContainer.getComponentInstance(componentId);
assertNotNull(component);
return component;
}
private void startTestBundle() throws BundleException {
Bundle bundle = context().getBundleByName("org.apache.aries.blueprint.sample");
assertNotNull(bundle);
bundle.start();
}
@org.ops4j.pax.exam.Configuration
public static Option[] configuration() {
return new Option[] {
junitBundles(),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample", false)
};
}
}
| 9,110 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/BlueprintContainerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
public class BlueprintContainerTest extends AbstractBlueprintIntegrationTest {
@Test
public void test() throws Exception {
applyCommonConfiguration(context());
Bundle bundle = context().getBundleByName("org.apache.aries.blueprint.sample");
assertNotNull(bundle);
bundle.start();
// do the test
Helper.testBlueprintContainer(context(), bundle);
}
@org.ops4j.pax.exam.Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample", false),
};
}
}
| 9,111 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/ParserServiceIgnoreUnknownNamespaceHandlerTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.blueprintBundles;
import static org.ops4j.pax.exam.CoreOptions.frameworkProperty;
import static org.ops4j.pax.exam.CoreOptions.keepCaches;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import java.io.InputStream;
import java.net.URL;
import org.apache.aries.blueprint.itests.cm.service.Foo;
import org.apache.aries.blueprint.itests.cm.service.FooFactory;
import org.apache.aries.blueprint.itests.cm.service.FooInterface;
import org.apache.aries.blueprint.services.ParserService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
public class ParserServiceIgnoreUnknownNamespaceHandlerTest extends AbstractBlueprintIntegrationTest {
private static final String CM_BUNDLE = "org.apache.aries.blueprint.cm";
private static final String TEST_BUNDLE = "org.apache.aries.blueprint.cm.test.b1";
@ProbeBuilder
public TestProbeBuilder probeConfiguration(TestProbeBuilder probe) {
probe.setHeader(Constants.EXPORT_PACKAGE, Foo.class.getPackage().getName());
probe.setHeader(Constants.IMPORT_PACKAGE, Foo.class.getPackage().getName());
return probe;
}
@org.ops4j.pax.exam.Configuration
public Option[] config() {
InputStream testBundle = createTestBundle();
return new Option[] {
baseOptions(),
frameworkProperty("org.apache.aries.blueprint.parser.service.ignore.unknown.namespace.handlers").value("true"),
blueprintBundles(),
keepCaches(),
streamBundle(testBundle)
};
}
private InputStream createTestBundle() {
return TinyBundles.bundle()
.add(FooInterface.class)
.add(Foo.class)
.add(FooFactory.class)
.add("OSGI-INF/blueprint/context.xml", getResource("IgnoreUnknownNamespaceTest.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, TEST_BUNDLE)
.set(Constants.EXPORT_PACKAGE, Foo.class.getPackage().getName())
.set(Constants.IMPORT_PACKAGE, Foo.class.getPackage().getName())
.build(TinyBundles.withBnd());
}
@Before
public void stopCM() throws BundleException {
context().getBundleByName(CM_BUNDLE).stop();
}
@After
public void startCM() throws BundleException {
context().getBundleByName(CM_BUNDLE).start();
}
@Test
public void testIgnoreTrue() throws Exception {
ParserService parserService = context().getService(ParserService.class);
URL blueprintXML = context().getBundleByName(TEST_BUNDLE).getEntry("OSGI-INF/blueprint/context.xml");
// ensure there is no error parsing while CM is stopped
parserService.parse(blueprintXML, context().getBundleByName(TEST_BUNDLE));
}
}
| 9,112 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/FragmentTestBundleBlueprintAttribute.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.itests;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.service.blueprint.container.BlueprintContainer;
@RunWith(PaxExam.class)
public class FragmentTestBundleBlueprintAttribute extends AbstractBlueprintIntegrationTest
{
@Test
public void testFragmentProvidesBlueprintFile() throws Exception
{
Runnable r = context().getService(Runnable.class);
Assert.assertNotNull("Could not find blueprint registered service", r);
BlueprintContainer bc = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.test.host");
Assert.assertNotNull("Could not find blueprint container for bundle", bc);
}
@Configuration
public Option[] configuration() {
InputStream hostJar = TinyBundles.bundle()
.set(Constants.BUNDLE_MANIFESTVERSION, "2")
.set("Bundle-Blueprint", "META-INF/bp/*.xml")
.set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.test.host").build();
InputStream fragmentJar = TinyBundles.bundle()
.set(Constants.BUNDLE_MANIFESTVERSION, "2")
.set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.test.fragment")
.set(Constants.FRAGMENT_HOST, "org.apache.aries.test.host")
.add("META-INF/bp/bp.xml", this.getClass().getResourceAsStream("/bp.xml"))
.build();
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
streamBundle(fragmentJar).noStart(),
streamBundle(hostJar),
};
}
} | 9,113 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/SpringTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import java.util.List;
import org.apache.aries.blueprint.testbundles.BeanC;
import org.apache.aries.blueprint.testbundles.BeanCItf;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
public class SpringTest extends AbstractBlueprintIntegrationTest {
@Test
public void testSpringBundle() throws Exception {
Bundle bundles = context().getBundleByName("org.apache.aries.blueprint.testbundles");
assertNotNull(bundles);
bundles.start();
BlueprintContainer container = startBundleBlueprint("org.apache.aries.blueprint.testbundles");
List list = (List) container.getComponentInstance("springList");
System.out.println(list);
BeanCItf beanC = (BeanCItf) list.get(4);
assertEquals(1, beanC.getInitialized());
try {
beanC.doSomething();
fail("Should have thrown an exception because the transaction manager is not defined");
} catch (NoSuchBeanDefinitionException e) {
// expected
}
}
@org.ops4j.pax.exam.Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
// Blueprint spring
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.spring"),
// Spring
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.aopalliance"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-core"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-context"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-context-support"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-beans"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-aop"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-expression"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-tx"),
// Axon namespace handler for testing
mavenBundle("org.axonframework", "axon-core", "2.4.4"),
// test bundle
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testbundles", false),
};
}
}
| 9,114 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/Helper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Currency;
import org.apache.aries.blueprint.sample.Account;
import org.apache.aries.blueprint.sample.AccountFactory;
import org.apache.aries.blueprint.sample.Bar;
import org.apache.aries.blueprint.sample.Foo;
import org.apache.aries.itest.RichBundleContext;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.container.BlueprintContainer;
public class Helper {
private static final String SAMPLE_SYM_NAME = "org.apache.aries.blueprint.sample";
public static BlueprintContainer getBlueprintContainerForBundle(RichBundleContext context, String symbolicName) {
return context.getService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=" + symbolicName + ")");
}
public static BlueprintContainer getBlueprintContainerForBundle(RichBundleContext context, String symbolicName, long timeout) {
return context.getService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=" + symbolicName + ")", timeout);
}
public static Option blueprintBundles() {
return blueprintBundles(true);
}
public static Option debug(int port) {
return CoreOptions.vmOption("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + port);
}
public static Option blueprintBundles(boolean startBlueprint) {
return composite(
mvnBundle("org.ow2.asm", "asm-debug-all"),
mvnBundle("org.apache.felix", "org.apache.felix.configadmin"),
mvnBundle("org.ops4j.pax.url", "pax-url-aether"),
mvnBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit"),
mvnBundle("org.apache.aries.proxy", "org.apache.aries.proxy"),
mvnBundle("org.apache.commons", "commons-jexl"),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.jexl.evaluator"),
mvnBundle("org.apache.xbean", "xbean-asm5-shaded"),
mvnBundle("org.apache.xbean", "xbean-bundleutils"),
mvnBundle("org.apache.xbean", "xbean-finder"),
mvnBundle("org.apache.aries.quiesce", "org.apache.aries.quiesce.api", startBlueprint),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.api", startBlueprint),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.core", startBlueprint),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.cm", startBlueprint)
);
}
public static Option mvnBundle(String groupId, String artifactId) {
return mavenBundle(groupId, artifactId).versionAsInProject();
}
public static Option mvnBundle(String groupId, String artifactId, boolean start) {
return mavenBundle(groupId, artifactId).versionAsInProject().start(start);
}
public static void testBlueprintContainer(RichBundleContext context, Bundle bundle) throws Exception {
BlueprintContainer blueprintContainer = getBlueprintContainerForBundle(context, SAMPLE_SYM_NAME);
assertNotNull(blueprintContainer);
Bar bar = getInstance(blueprintContainer, "bar", Bar.class);
checkBar(bar);
Foo foo = getInstance(blueprintContainer, "foo", Foo.class);
checkFoo(bar, foo);
Foo fooService = context.getService(Foo.class);
assertNotNull(fooService);
checkFoo(bar, fooService);
// TODO Does not work
//assertEquals(obj, foo);
Account account = getInstance(blueprintContainer, "accountOne", Account.class);
assertEquals(1, account.getAccountNumber());
Account account2 = getInstance(blueprintContainer, "accountTwo", Account.class);
assertEquals(2, account2.getAccountNumber());
Account account3 = getInstance(blueprintContainer, "accountThree", Account.class);
assertEquals(3, account3.getAccountNumber());
AccountFactory accountFactory = getInstance(blueprintContainer, "accountFactory", AccountFactory.class);
assertEquals("account factory", accountFactory.getFactoryName());
bundle.stop();
Thread.sleep(1000);
try {
blueprintContainer = getBlueprintContainerForBundle(context, SAMPLE_SYM_NAME, 1);
fail("BlueprintContainer should have been unregistered");
} catch (Exception e) {
// Expected, as the module container should have been unregistered
}
assertTrue(foo.isInitialized());
assertTrue(foo.isDestroyed());
}
private static void checkBar(Bar bar) {
assertNotNull(bar.getContext());
assertEquals("Hello FooBar", bar.getValue());
assertNotNull(bar.getList());
assertEquals(2, bar.getList().size());
assertEquals("a list element", bar.getList().get(0));
assertEquals(Integer.valueOf(5), bar.getList().get(1));
}
private static void checkFoo(Bar bar, Foo foo) throws ParseException {
assertEquals(5, foo.getA());
assertEquals(10, foo.getB());
assertSame(bar, foo.getBar());
assertEquals(Currency.getInstance("PLN"), foo.getCurrency());
assertEquals(new SimpleDateFormat("yyyy.MM.dd").parse("2009.04.17"),
foo.getDate());
assertTrue(foo.isInitialized());
assertFalse(foo.isDestroyed());
}
@SuppressWarnings("unchecked")
private static <T>T getInstance(BlueprintContainer container, String name, Class<T> clazz) {
Object obj = container.getComponentInstance(name);
assertNotNull(obj);
assertEquals(clazz, obj.getClass());
return (T) obj;
}
}
| 9,115 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/ParserServiceImportCmAndIncorrectNamespaceHandlersTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.itests.cm.handler.IncorrectNamespaceHandler;
import org.apache.aries.blueprint.services.ParserService;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;
import static org.apache.aries.blueprint.itests.Helper.blueprintBundles;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.*;
public class ParserServiceImportCmAndIncorrectNamespaceHandlersTest extends AbstractBlueprintIntegrationTest {
private static final String NS_HANDLER_BUNDLE = "org.apache.aries.blueprint.incorrect";
private static final String TEST_BUNDLE = "org.apache.aries.blueprint.aries1503.test";
@org.ops4j.pax.exam.Configuration
public Option[] config() {
return new Option[] {
baseOptions(),
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
blueprintBundles(),
keepCaches(),
streamBundle(createIncorrectNamespaceHandlerBundle()),
streamBundle(createTestBundle())
};
}
private InputStream createIncorrectNamespaceHandlerBundle() {
return TinyBundles.bundle()
.add(IncorrectNamespaceHandler.class)
.add("OSGI-INF/blueprint/incorrect.xml", getResource("incorrect.xml"))
.add("incorrect-1.0.0.xsd", getResource("incorrect-1.0.0.xsd"))
.add("incorrect-1.1.0.xsd", getResource("incorrect-1.1.0.xsd"))
.set(Constants.BUNDLE_SYMBOLICNAME, NS_HANDLER_BUNDLE)
.set(Constants.EXPORT_PACKAGE, IncorrectNamespaceHandler.class.getPackage().getName())
.set(Constants.IMPORT_PACKAGE, "org.apache.aries.blueprint,org.apache.aries.blueprint.ext," +
"org.apache.aries.blueprint.mutable," +
"org.apache.aries.blueprint.compendium.cm," +
"org.osgi.service.blueprint.reflect,org.w3c.dom")
.build(TinyBundles.withBnd());
}
private InputStream createTestBundle() {
return TinyBundles.bundle()
.add("OSGI-INF/blueprint/ImportIncorrectAndCmNamespacesTest.xml", getResource("ImportIncorrectAndCmNamespacesTest.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, TEST_BUNDLE)
.set(Constants.IMPORT_PACKAGE, IncorrectNamespaceHandler.class.getPackage().getName()
+ ",org.apache.aries.blueprint,org.apache.aries.blueprint.ext," +
"org.apache.aries.blueprint.mutable," +
"org.osgi.service.blueprint.reflect,org.w3c.dom")
.build(TinyBundles.withBnd());
}
@Test
public void testXSDImports() throws Exception {
waitForConfig();
ParserService parserService = context().getService(ParserService.class);
URL blueprintXML = context().getBundleByName(TEST_BUNDLE).getEntry("OSGI-INF/blueprint/ImportIncorrectAndCmNamespacesTest.xml");
ComponentDefinitionRegistry cdr = parserService.parse(blueprintXML, context().getBundleByName(TEST_BUNDLE));
assertNotNull(cdr.getComponentDefinition("aries-1503"));
}
private void waitForConfig() throws InterruptedException {
final CountDownLatch ready = new CountDownLatch(2);
final AtomicBoolean failure = new AtomicBoolean(false);
@SuppressWarnings("rawtypes")
ServiceRegistration reg = context().registerService(
BlueprintListener.class,
new BlueprintListener() {
@Override
public void blueprintEvent(BlueprintEvent event) {
if (NS_HANDLER_BUNDLE.equals(event.getBundle().getSymbolicName())
&& BlueprintEvent.CREATED == event.getType()) {
ready.countDown();
} else if (TEST_BUNDLE.equals(event.getBundle().getSymbolicName())
&& (BlueprintEvent.CREATED == event.getType() || BlueprintEvent.FAILURE == event.getType())) {
ready.countDown();
if (BlueprintEvent.FAILURE == event.getType()) {
failure.set(true);
}
}
}
},
null);
try {
assertTrue(ready.await(3000, TimeUnit.MILLISECONDS));
assertFalse("org.apache.aries.blueprint.aries1503.test bundle should successfully start Blueprint container",
failure.get());
} finally {
reg.unregister();
}
}
}
| 9,116 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/MultiInterfacesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.apache.aries.blueprint.testbundlea.multi.InterfaceA;
import org.apache.aries.blueprint.testbundlea.multi.InterfaceB;
import org.apache.aries.blueprint.testbundlea.multi.InterfaceC;
import org.apache.aries.blueprint.testbundlea.multi.InterfaceD;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.service.blueprint.container.BlueprintContainer;
@RunWith(PaxExam.class)
public class MultiInterfacesTest extends AbstractBlueprintIntegrationTest {
@Test
public void testMultiInterfaceReferences() throws Exception {
//bundlea provides the ns handlers, bean processors, interceptors etc for this test.
startBundleBlueprint("org.apache.aries.blueprint.testbundlea");
//bundleb makes use of the extensions provided by bundlea
//bundleb's container will hold the beans we need to query to check the function
//provided by bundlea functioned as expected
BlueprintContainer beanContainer = startBundleBlueprint("org.apache.aries.blueprint.testbundleb");
Object obj1 = beanContainer.getComponentInstance("OnlyA");
Object obj2 = beanContainer.getComponentInstance("AandB");
Object obj3 = beanContainer.getComponentInstance("AandBandC");
Object obj4 = beanContainer.getComponentInstance("AandBandCandD");
assertEquals("A", ((InterfaceA)obj1).methodA());
assertEquals("A", ((InterfaceA)obj2).methodA());
assertEquals("A", ((InterfaceA)obj3).methodA());
assertEquals("B", ((InterfaceB)obj2).methodB());
assertEquals("C", ((InterfaceC)obj3).methodC());
assertFalse(obj1 instanceof InterfaceC);
assertFalse(obj2 instanceof InterfaceC);
assertFalse(obj1 instanceof InterfaceB);
assertTrue(obj4 instanceof InterfaceD);
try {
((InterfaceD)obj4).methodD();
fail("This should not work");
} catch (org.osgi.service.blueprint.container.ServiceUnavailableException t) {
//expected
}
}
@Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testbundlea"),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testbundleb")
};
}
}
| 9,117 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/AbstractBlueprintIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.ops4j.pax.exam.CoreOptions.vmOption;
import static org.ops4j.pax.exam.CoreOptions.when;
import java.io.InputStream;
import java.util.Hashtable;
import org.apache.aries.itest.AbstractIntegrationTest;
import org.apache.aries.itest.RichBundleContext;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.options.MavenArtifactProvisionOption;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
/**
* Base class for Pax Exam 1.2.x based unit tests Contains the injection point and various utilities used in
* most tests
*/
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public abstract class AbstractBlueprintIntegrationTest extends AbstractIntegrationTest {
public static final long DEFAULT_TIMEOUT = 15000;
protected BlueprintContainer startBundleBlueprint(String symbolicName) throws BundleException {
Bundle b = context().getBundleByName(symbolicName);
assertNotNull("Bundle " + symbolicName + " not found", b);
b.start();
BlueprintContainer beanContainer = Helper.getBlueprintContainerForBundle(context(), symbolicName);
assertNotNull(beanContainer);
return beanContainer;
}
public Option baseOptions() {
String localRepo = System.getProperty("maven.repo.local");
if (localRepo == null) {
localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository");
}
return composite(junitBundles(),
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
when(localRepo != null)
.useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)),
mvnBundle("org.ops4j.pax.logging", "pax-logging-api"),
mvnBundle("org.ops4j.pax.logging", "pax-logging-service"),
systemProperty("pax.exam.osgi.unresolved.fail").value("true")
);
}
public InputStream getResource(String path) {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);
if (is == null) {
throw new IllegalArgumentException("Resource not found " + path);
}
return is;
}
protected void applyCommonConfiguration(BundleContext ctx) throws Exception {
ConfigurationAdmin ca = (new RichBundleContext(ctx)).getService(ConfigurationAdmin.class);
Configuration cf = ca.getConfiguration("blueprint-sample-placeholder", null);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("key.b", "10");
cf.update(props);
}
protected Bundle getSampleBundle() {
Bundle bundle = context().getBundleByName("org.apache.aries.blueprint.sample");
assertNotNull(bundle);
return bundle;
}
protected MavenArtifactProvisionOption sampleBundleOption() {
return CoreOptions.mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample")
.versionAsInProject();
}
protected void startBlueprintBundles() throws BundleException, InterruptedException {
context().getBundleByName("org.apache.aries.blueprint.core").start();
context().getBundleByName("org.apache.aries.blueprint.cm").start();
Thread.sleep(2000);
}
}
| 9,118 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/BlueprintContainer2Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.framework.Bundle;
/**
* this test is based on blueprint container test, but this test starts the
* blueprint sample before the blueprint bundle is started so going a slightly
* different code path
*
*/
@RunWith(PaxExam.class)
public class BlueprintContainer2Test extends AbstractBlueprintIntegrationTest {
@Test
public void test() throws Exception {
applyCommonConfiguration(context());
Bundle bundle = getSampleBundle();
bundle.start();
startBlueprintBundles();
// do the test
Helper.testBlueprintContainer(context(), bundle);
}
@org.ops4j.pax.exam.Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(false),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample", false)
};
}
}
| 9,119 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/BlueprintContainerUseSystemContextTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.junit.Assert.assertNotNull;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.hooks.bundle.EventHook;
import org.osgi.framework.hooks.bundle.FindHook;
/**
* Shows that the blueprint extender uses the system bundle to find user bundles if the respective property is set
*/
public class BlueprintContainerUseSystemContextTest extends AbstractBlueprintIntegrationTest {
ServiceRegistration eventHook;
ServiceRegistration findHook;
@Before
public void regiserHook() {
final BundleContext systemContext = context().getBundle(Constants.SYSTEM_BUNDLE_LOCATION).getBundleContext();
eventHook = context().registerService(EventHook.class, new EventHook() {
@Override
public void event(BundleEvent event,
Collection contexts) {
if ("org.apache.aries.blueprint.sample".equals(event.getBundle().getSymbolicName())) {
// hide sample from everything but the system bundle
// TODO on R6 we should be able to even try hiding from the system bundle
// R5 it was not clear if hooks could hide from the system bundle
// equinox R5 does allow hiding from system bundle
contexts.retainAll(Collections.singleton(systemContext));
}
}
}, null);
findHook = context().registerService(FindHook.class, new FindHook(){
@Override
public void find(BundleContext context, Collection bundles) {
if (context.equals(systemContext)) {
// TODO on R6 we should be able to even try hiding from the system bundle
// R5 it was not clear if hooks could hide from the system bundle
// equinox R5 does allow hiding from system bundle
return;
}
for (Iterator iBundles = bundles.iterator(); iBundles.hasNext();) {
if ("org.apache.aries.blueprint.sample".equals(((Bundle) iBundles.next()).getSymbolicName())) {
// hide sample from everything
iBundles.remove();
}
}
}}, null);
}
@After
public void unregisterHook() {
eventHook.unregister();
findHook.unregister();
}
@Test
public void test() throws Exception {
applyCommonConfiguration(context());
Bundle bundle = context().installBundle(sampleBundleOption().getURL());
assertNotNull(bundle);
bundle.start();
// do the test
Helper.testBlueprintContainer(context(), bundle);
}
@org.ops4j.pax.exam.Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
CoreOptions.systemProperty("org.apache.aries.blueprint.use.system.context").value("true"),
Helper.blueprintBundles()
};
}
}
| 9,120 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/DeadLockTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.composite;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.aries.blueprint.itests.comp.ListFactory;
import org.apache.aries.blueprint.itests.comp.Listener;
import org.junit.Test;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
public class DeadLockTest extends AbstractBlueprintIntegrationTest {
private static final int TOTAL_REF_TEST_BUNDLES = 10;
@Test
public void testReferenceListenerDeadlock() throws Exception {
for (int i=0; i < TOTAL_REF_TEST_BUNDLES; i++) {
Bundle b = context().getBundleByName("sample" + i);
b.start();
}
// every blueprint container should be up
for (int i=0; i < TOTAL_REF_TEST_BUNDLES; i++) {
assertNotNull(Helper.getBlueprintContainerForBundle(context(), "sample" + i));
}
}
private InputStream getTestBundle(int no, int total) {
StringBuilder blueprint = new StringBuilder();
blueprint.append("<blueprint xmlns=\"http://www.osgi.org/xmlns/blueprint/v1.0.0\">");
blueprint.append("<bean id=\"listener\" class=\"" + Listener.class.getName() + "\" />");
for (int i=0; i<total; i++) {
if (i==no) {
blueprint.append("<service interface=\"java.util.List\">");
blueprint.append("<service-properties><entry key=\"no\" value=\""+i+"\" /></service-properties>");
blueprint.append("<bean class=\"" + ListFactory.class.getName() + "\" factory-method=\"create\">");
blueprint.append("<argument value=\""+i+"\" />");
blueprint.append("</bean>");
blueprint.append("</service>");
} else {
blueprint.append("<reference availability=\"optional\" id=\"ref"+i+"\" interface=\"java.util.List\" filter=\"(no="+i+")\">");
blueprint.append("<reference-listener ref=\"listener\" bind-method=\"bind\" unbind-method=\"unbind\" />");
blueprint.append("</reference>");
}
}
blueprint.append("</blueprint>");
try {
InputStream is = new ByteArrayInputStream(blueprint.toString().getBytes("UTF-8"));
return TinyBundles.bundle()
.add(Listener.class)
.add(ListFactory.class)
.add("OSGI-INF/blueprint/blueprint.xml", is)
.set(Constants.IMPORT_PACKAGE, "org.osgi.framework")
.set(Constants.BUNDLE_SYMBOLICNAME, "sample" + no).build();
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
private Option[] getRefTestBundles() {
List<Option> refTestBundles = new ArrayList<Option>();
for (int c=0;c < TOTAL_REF_TEST_BUNDLES; c++) {
refTestBundles.add(CoreOptions.provision(getTestBundle(c, TOTAL_REF_TEST_BUNDLES)));
}
return refTestBundles.toArray(new Option[]{});
}
@Test
public void testDeadlock() throws Exception {
bundleContext.registerService("java.util.Set",new HashSet<Object>(), null);
Bundle bundle = getSampleBundle();
bundle.start();
Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
// no actual assertions, we just don't want to deadlock
}
@org.ops4j.pax.exam.Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample", false),
composite(getRefTestBundles()),
};
}
}
| 9,121 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/ParserServiceImportXSDsBetweenNamespaceHandlersTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.blueprintBundles;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.keepCaches;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.itests.cm.handler.Aries1503aNamespaceHandler;
import org.apache.aries.blueprint.itests.cm.handler.Aries1503bNamespaceHandler;
import org.apache.aries.blueprint.services.ParserService;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;
public class ParserServiceImportXSDsBetweenNamespaceHandlersTest extends AbstractBlueprintIntegrationTest {
private static final String NS_HANDLER_BUNDLE = "org.apache.aries.blueprint.aries1503";
private static final String NS_HANDLER2_BUNDLE = "org.apache.aries.blueprint.aries1503b";
private static final String TEST_BUNDLE = "org.apache.aries.blueprint.aries1503.test";
@org.ops4j.pax.exam.Configuration
public Option[] config() {
return new Option[] {
baseOptions(),
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
blueprintBundles(),
keepCaches(),
streamBundle(createAries1503aNamespaceHandlerBundle()).noStart(),
streamBundle(createAries1503bNamespaceHandlerBundle()),
streamBundle(createTestBundle())
};
}
private InputStream createAries1503aNamespaceHandlerBundle() {
return TinyBundles.bundle()
.add(Aries1503aNamespaceHandler.class)
.add("OSGI-INF/blueprint/blueprint-aries-1503.xml", getResource("blueprint-aries-1503.xml"))
.add("blueprint-aries-1503.xsd", getResource("blueprint-aries-1503.xsd"))
.set(Constants.BUNDLE_SYMBOLICNAME, NS_HANDLER_BUNDLE)
.set(Constants.EXPORT_PACKAGE, Aries1503aNamespaceHandler.class.getPackage().getName())
.set(Constants.IMPORT_PACKAGE, "org.apache.aries.blueprint,org.apache.aries.blueprint.ext," +
"org.apache.aries.blueprint.mutable," +
"org.osgi.service.blueprint.reflect,org.w3c.dom")
.build(TinyBundles.withBnd());
}
private InputStream createAries1503bNamespaceHandlerBundle() {
return TinyBundles.bundle()
.add(Aries1503bNamespaceHandler.class)
// add this class too - we don't want to play with split packages, etc.
.add(Aries1503aNamespaceHandler.class)
.add("OSGI-INF/blueprint/blueprint-aries-1503-2.xml", getResource("blueprint-aries-1503-2.xml"))
.add("blueprint-aries-1503-2.xsd", getResource("blueprint-aries-1503-2.xsd"))
.add("blueprint-aries-1503.xsd", getResource("blueprint-aries-1503.xsd"))
.set(Constants.BUNDLE_SYMBOLICNAME, NS_HANDLER2_BUNDLE)
.set(Constants.EXPORT_PACKAGE, Aries1503bNamespaceHandler.class.getPackage().getName())
.set(Constants.IMPORT_PACKAGE, "org.apache.aries.blueprint,org.apache.aries.blueprint.ext," +
"org.apache.aries.blueprint.mutable," +
"org.osgi.service.blueprint.reflect,org.w3c.dom," +
Aries1503bNamespaceHandler.class.getPackage().getName())
.build(TinyBundles.withBnd());
}
private InputStream createTestBundle() {
return TinyBundles.bundle()
.add("OSGI-INF/blueprint/ImportNamespacesTest.xml", getResource("ImportNamespacesTest.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, TEST_BUNDLE)
.set(Constants.IMPORT_PACKAGE, Aries1503bNamespaceHandler.class.getPackage().getName()
+ ",org.apache.aries.blueprint,org.apache.aries.blueprint.ext")
.build(TinyBundles.withBnd());
}
@Test
public void testXSDImports() throws Exception {
waitForConfig();
ParserService parserService = context().getService(ParserService.class);
URL blueprintXML = context().getBundleByName(TEST_BUNDLE).getEntry("OSGI-INF/blueprint/ImportNamespacesTest.xml");
ComponentDefinitionRegistry cdr = parserService.parse(blueprintXML, context().getBundleByName(TEST_BUNDLE));
assertNotNull(cdr.getComponentDefinition("aries-1503"));
}
private void waitForConfig() throws InterruptedException {
final AtomicBoolean ready = new AtomicBoolean();
@SuppressWarnings("rawtypes")
ServiceRegistration reg = context().registerService(
BlueprintListener.class,
new BlueprintListener() {
@Override
public void blueprintEvent(BlueprintEvent event) {
if ("org.apache.aries.blueprint.aries1503b".equals(event.getBundle().getSymbolicName())
&& BlueprintEvent.CREATED == event.getType()) {
synchronized (ready) {
ready.set(true);
ready.notify();
}
}
}
},
null);
try {
synchronized (ready) {
if (!ready.get()) {
ready.wait(3000);
}
}
} finally {
reg.unregister();
}
}
}
| 9,122 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/SpringExtenderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import org.apache.aries.blueprint.testbundlee.BeanCItf;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.container.BlueprintContainer;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
public class SpringExtenderTest extends AbstractBlueprintIntegrationTest {
@Test
public void testSpringBundle() throws Exception {
try {
context().getService(BeanCItf.class, 1);
fail("The service should not be registered");
} catch (RuntimeException e) {
// Expected
}
Bundle bundles = context().getBundleByName("org.apache.aries.blueprint.testbundlee");
assertNotNull(bundles);
bundles.start();
BlueprintContainer container = startBundleBlueprint("org.apache.aries.blueprint.testbundlee");
assertNotNull(container);
BeanCItf beanC1 = context().getService(BeanCItf.class, "(name=BeanC-1)");
assertEquals(1, beanC1.getInitialized());
BeanCItf beanC2 = context().getService(BeanCItf.class, "(name=BeanC-2)");
assertEquals(1, beanC2.getInitialized());
}
@org.ops4j.pax.exam.Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
// Blueprint spring
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.spring"),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.spring.extender"),
// Spring
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.aopalliance"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-core"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-context"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-context-support"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-beans"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-aop"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-expression"),
mvnBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.spring-tx"),
// test bundle
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testbundlee", false),
};
}
}
| 9,123 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/ASMMultiBundleTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.testbundlea.NSHandlerOne;
import org.apache.aries.blueprint.testbundlea.NSHandlerTwo;
import org.apache.aries.blueprint.testbundlea.ProcessableBean;
import org.apache.aries.blueprint.testbundlea.ProcessableBean.Phase;
import org.apache.aries.blueprint.testbundleb.OtherBean;
import org.apache.aries.blueprint.testbundleb.TestBean;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.container.BlueprintContainer;
@RunWith(PaxExam.class)
public class ASMMultiBundleTest extends AbstractBlueprintIntegrationTest {
private void checkInterceptorLog(String []expected, List<String> log){
assertNotNull("interceptor log should not be null",log);
System.out.println("Log:");
for(String entry: log){
System.out.println(""+entry);
}
assertEquals("interceptor log size does not match expected size",expected.length,log.size());
List<String> extra=new ArrayList<String>();
boolean[] found = new boolean[expected.length];
for(String s : log){
boolean used=false;
for(int i=0; i<expected.length; i++){
if(s.startsWith(expected[i])){
found[i]=true;
used=true;
}
}
if(!used){
extra.add(s);
}
}
if(extra.size()!=0){
String extraFormatted="{";
for(String e:extra){
extraFormatted+=e+" ";
}
extraFormatted+="}";
fail("surplus interceptor invocations present in invocation log "+extraFormatted);
}
for(int i=0; i<found.length; i++){
assertTrue("interceptor invocation "+expected[i]+" not found",found[i]);
}
}
// TODO This test seems to fail on some runs. Need to stabilize and reenable
@Test
@Ignore
public void multiBundleTest() throws Exception {
//bundlea provides the ns handlers, bean processors, interceptors etc for this test.
Bundle bundlea = context().getBundleByName("org.apache.aries.blueprint.testbundlea");
assertNotNull(bundlea);
bundlea.start();
//bundleb makes use of the extensions provided by bundlea
Bundle bundleb = context().getBundleByName("org.apache.aries.blueprint.testbundleb");
assertNotNull(bundleb);
bundleb.start();
//bundleb's container will hold the beans we need to query to check the function
//provided by bundlea functioned as expected
BlueprintContainer beanContainer =
Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.testbundleb");
assertNotNull(beanContainer);
//TestBeanA should have the values below, no interference should be present from other sources.
Object obj1 = beanContainer.getComponentInstance("TestBeanA");
assertTrue(obj1 instanceof TestBean);
TestBean testBeanA = (TestBean)obj1;
org.junit.Assert.assertEquals("RED", testBeanA.getRed());
org.junit.Assert.assertEquals("GREEN", testBeanA.getGreen());
org.junit.Assert.assertEquals("BLUE", testBeanA.getBlue());
//TestBeanB tests that a custom ns handler is able to inject custom components to the blueprint,
//and modify existing components, and use injected components as modifications.
Object obj2 = beanContainer.getComponentInstance("TestBeanB");
assertTrue(obj2 instanceof TestBean);
TestBean testBeanB = (TestBean)obj2;
//value should be set in via the added passthroughmetadata via the nshandler.
org.junit.Assert.assertEquals("ONE_VALUE", testBeanB.getRed());
org.junit.Assert.assertEquals("GREEN", testBeanB.getGreen());
org.junit.Assert.assertEquals("BLUE", testBeanB.getBlue());
//TestBeanC tests that custom ns handlers can add interceptors to beans.
Object obj3 = beanContainer.getComponentInstance("TestBeanC");
assertTrue(obj3 instanceof TestBean);
TestBean testBeanC = (TestBean)obj3;
//handlers are in bundlea, with its own container.
BlueprintContainer handlerContainer =
Helper.getBlueprintContainerForBundle( context(), "org.apache.aries.blueprint.testbundlea");
assertNotNull(handlerContainer);
Object ns1 = handlerContainer.getComponentInstance("NSHandlerOne");
assertTrue(ns1 instanceof NSHandlerOne);
Object ns2 = handlerContainer.getComponentInstance("NSHandlerTwo");
assertTrue(ns2 instanceof NSHandlerTwo);
NSHandlerTwo nstwo = (NSHandlerTwo)ns2;
//now we have a handle to the nshandler2, we can query what it 'saw', and ensure
//that the interceptors are functioning as expected.
List<String> log = nstwo.getLog();
//TestBeanC has the interceptor configured, and is injected to OtherBeanA & OtherBeanB
//which then uses the injected bean during their init method call, to invoke a method
checkInterceptorLog(new String[] {
"PRECALL:TestBeanC:methodToInvoke:[RED]:",
"POSTCALL[true]:TestBeanC:methodToInvoke:[RED]:",
"PRECALL:TestBeanC:methodToInvoke:[BLUE]:",
"POSTCALL[false]:TestBeanC:methodToInvoke:[BLUE]:"
}, log);
//invoking GREEN is hardwired to cause an exception response, we do this
//from here to ensure the exception occurs and is visible as expected
RuntimeException re=null;
try{
testBeanC.methodToInvoke("GREEN");
}catch(RuntimeException e){
re=e;
}
assertNotNull("invocation of Green did not cause an exception as expected",re);
//Exception responses should be intercepted too, test for the POSTCALLWITHEXCEPTION log entry.
log = nstwo.getLog();
checkInterceptorLog(new String[] {
"PRECALL:TestBeanC:methodToInvoke:[RED]:",
"POSTCALL[true]:TestBeanC:methodToInvoke:[RED]:",
"PRECALL:TestBeanC:methodToInvoke:[BLUE]:",
"POSTCALL[false]:TestBeanC:methodToInvoke:[BLUE]:",
"PRECALL:TestBeanC:methodToInvoke:[GREEN]:",
"POSTCALLEXCEPTION[java.lang.RuntimeException: MATCHED ON GREEN (GREEN)]:TestBeanC:methodToInvoke:[GREEN]:"
}, log);
//ProcessedBean is a test to ensure that BeanProcessors are called..
//The test has the BeanProcessor look for ProcessableBeans, and log itself with them
Object obj4 = beanContainer.getComponentInstance("ProcessedBean");
assertTrue(obj4 instanceof ProcessableBean);
ProcessableBean pb = (ProcessableBean)obj4;
//Note, the BeanProcessor exists in the same container as the beans it processes!!
Object bp = beanContainer.getComponentInstance("http://ns.handler.three/BeanProcessor");
assertNotNull(bp);
assertTrue(bp instanceof BeanProcessor);
assertEquals(1,pb.getProcessedBy().size());
//check we were invoked..
assertEquals(pb.getProcessedBy().get(0),bp);
//check invocation for each phase.
assertEquals(pb.getProcessedBy(Phase.BEFORE_INIT).get(0),bp);
assertEquals(pb.getProcessedBy(Phase.AFTER_INIT).get(0),bp);
//destroy invocation will only occur at tear down.. TODO, how to test after teardown.
//assertEquals(pb.getProcessedBy(Phase.BEFORE_DESTROY).get(0),bp);
//assertEquals(pb.getProcessedBy(Phase.AFTER_DESTROY).get(0),bp);
Object objOther = beanContainer.getComponentInstance("PlaceHolderTestBean");
assertTrue(objOther instanceof OtherBean);
assertEquals("test1value", ((OtherBean)objOther).getTestValue());
}
@Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testbundlea", false),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testbundleb", false)
};
}
}
| 9,124 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/TestReferences.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.Assert;
import org.apache.aries.blueprint.sample.BindingListener;
import org.apache.aries.blueprint.sample.DefaultRunnable;
import org.apache.aries.blueprint.sample.DestroyTest;
import org.apache.aries.blueprint.sample.InterfaceA;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.ServiceUnavailableException;
@RunWith(PaxExam.class)
public class TestReferences extends AbstractBlueprintIntegrationTest {
@SuppressWarnings("rawtypes")
@Test
public void testUnaryReference() throws Exception {
BlueprintContainer blueprintContainer = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
assertNotNull(blueprintContainer);
BindingListener listener = (BindingListener) blueprintContainer.getComponentInstance("bindingListener");
assertNull(listener.getA());
assertNull(listener.getReference());
InterfaceA a = (InterfaceA) blueprintContainer.getComponentInstance("ref2");
try {
a.hello("world");
fail("A ServiceUnavailableException should have been thrown");
} catch (ServiceUnavailableException e) {
// Ignore, expected
}
ServiceRegistration reg1 = bundleContext.registerService(InterfaceA.class.getName(), new InterfaceA() {
public String hello(String msg) {
return "Hello " + msg + "!";
}
}, null);
waitForAsynchronousHandling();
assertNotNull(listener.getA());
assertNotNull(listener.getReference());
assertEquals("Hello world!", a.hello("world"));
Hashtable<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_RANKING, Integer.valueOf(1));
ServiceRegistration reg2 = bundleContext.registerService(InterfaceA.class.getName(), new InterfaceA() {
public String hello(String msg) {
return "Good morning " + msg + "!";
}
}, props);
waitForAsynchronousHandling();
assertNotNull(listener.getA());
assertNotNull(listener.getReference());
assertEquals("Hello world!", a.hello("world"));
reg1.unregister();
waitForAsynchronousHandling();
assertNotNull(listener.getA());
assertNotNull(listener.getReference());
assertEquals("Good morning world!", a.hello("world"));
reg2.unregister();
waitForAsynchronousHandling();
assertNull(listener.getA());
assertNull(listener.getReference());
try {
a.hello("world");
fail("A ServiceUnavailableException should have been thrown");
} catch (ServiceUnavailableException e) {
// Ignore, expected
}
}
@Test
public void testListReferences() throws Exception {
BlueprintContainer blueprintContainer = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
assertNotNull(blueprintContainer);
BindingListener listener = (BindingListener) blueprintContainer.getComponentInstance("listBindingListener");
assertNull(listener.getA());
assertNull(listener.getReference());
List<?> refs = (List<?>) blueprintContainer.getComponentInstance("ref-list");
assertNotNull(refs);
assertTrue(refs.isEmpty());
InterfaceA testService = new InterfaceA() {
public String hello(String msg) {
return "Hello " + msg + "!";
}
};
bundleContext.registerService(InterfaceA.class.getName(), testService, null);
waitForAsynchronousHandling();
assertNotNull(listener.getA());
assertNotNull(listener.getReference());
assertEquals(1, refs.size());
InterfaceA a = (InterfaceA) refs.get(0);
assertNotNull(a);
assertEquals("Hello world!", a.hello("world"));
}
@SuppressWarnings("rawtypes")
@Test
public void testDefaultReference() throws Exception {
BlueprintContainer blueprintContainer = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
assertNotNull(blueprintContainer);
Runnable refRunnable = (Runnable) blueprintContainer.getComponentInstance("refWithDefault");
DefaultRunnable defaultRunnable = (DefaultRunnable) blueprintContainer.getComponentInstance("defaultRunnable");
refRunnable.run();
waitForAsynchronousHandling();
Thread.sleep(2000);
assertEquals("The default runnable was not called", 1, defaultRunnable.getCount());
final AtomicBoolean called = new AtomicBoolean(false);
Runnable mockService = new Runnable() {
public void run() {
called.set(true);
}
};
ServiceRegistration reg = bundleContext.registerService(Runnable.class.getName(), mockService, null);
waitForAsynchronousHandling();
Thread.sleep(2000);
refRunnable.run();
assertEquals("The default runnable was called when a service was bound", 1, defaultRunnable.getCount());
Assert.assertTrue("Service should have been called", called.get());
reg.unregister();
waitForAsynchronousHandling();
Thread.sleep(2000);
refRunnable.run();
assertEquals("The default runnable was not called", 2, defaultRunnable.getCount());
}
@Test
public void testReferencesCallableInDestroy() throws Exception {
bundleContext.registerService(Runnable.class.getName(), new Thread(), null);
BlueprintContainer blueprintContainer = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.sample");
assertNotNull(blueprintContainer);
DestroyTest dt = (DestroyTest) blueprintContainer.getComponentInstance("destroyCallingReference");
Bundle b = findBundle("org.apache.aries.blueprint.sample");
assertNotNull(b);
b.stop();
assertTrue("The destroy method was called", dt.waitForDestruction(1000));
Exception e = dt.getDestroyFailure();
if (e != null) throw e;
}
private Bundle findBundle(String bsn)
{
for (Bundle b : bundleContext.getBundles()) {
if (bsn.equals(b.getSymbolicName())) return b;
}
return null;
}
private void waitForAsynchronousHandling() throws InterruptedException {
// Since service events are handled asynchronously in AbstractServiceReferenceRecipe, pause
Thread.sleep(200);
}
@Configuration
public static Option[] configuration() {
return new Option[] {
CoreOptions.junitBundles(),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample")
};
}
}
| 9,125 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/ParserServiceImportAndIncludeXSDsTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.itests.cm.handler.Aries1682NamespaceHandler;
import org.apache.aries.blueprint.services.ParserService;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;
import static org.apache.aries.blueprint.itests.Helper.blueprintBundles;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.*;
public class ParserServiceImportAndIncludeXSDsTest extends AbstractBlueprintIntegrationTest {
private static final String NS_HANDLER_BUNDLE = "org.apache.aries.blueprint.aries1682";
private static final String TEST_BUNDLE = "org.apache.aries.blueprint.aries1682.test";
@org.ops4j.pax.exam.Configuration
public Option[] config() {
return new Option[] {
baseOptions(),
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"),
blueprintBundles(),
keepCaches(),
streamBundle(createAries1682NamespaceHandlerBundle()),
streamBundle(createTestBundle())
};
}
private InputStream createAries1682NamespaceHandlerBundle() {
return TinyBundles.bundle()
.add(Aries1682NamespaceHandler.class)
.add("OSGI-INF/blueprint/blueprint-aries-1682.xml", getResource("blueprint-aries-1682.xml"))
.add("blueprint-aries-1682.xsd", getResource("blueprint-aries-1682.xsd"))
.add("blueprint-aries-1682-common.xsd", getResource("blueprint-aries-1682-common.xsd"))
.set(Constants.BUNDLE_SYMBOLICNAME, NS_HANDLER_BUNDLE)
.set(Constants.EXPORT_PACKAGE, Aries1682NamespaceHandler.class.getPackage().getName())
.set(Constants.IMPORT_PACKAGE, "org.apache.aries.blueprint," +
"org.apache.aries.blueprint.ext," +
"org.apache.aries.blueprint.mutable," +
FrameworkUtil.class.getPackage().getName() + "," +
"org.osgi.service.blueprint.reflect," +
"org.w3c.dom")
.build(TinyBundles.withClassicBuilder());
}
private InputStream createTestBundle() {
return TinyBundles.bundle()
.add("OSGI-INF/blueprint/ImportNamespacesWithXSDIncludeTest.xml", getResource("ImportNamespacesWithXSDIncludeTest.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, TEST_BUNDLE)
.set(Constants.IMPORT_PACKAGE, Aries1682NamespaceHandler.class.getPackage().getName()
+ ",org.apache.aries.blueprint,org.apache.aries.blueprint.ext")
.build(TinyBundles.withBnd());
}
@Test
public void testXSDImports() throws Exception {
assertTrue(TEST_BUNDLE + " should correctly register blueprint container", waitForConfig());
ParserService parserService = context().getService(ParserService.class);
URL blueprintXML = context().getBundleByName(TEST_BUNDLE).getEntry("OSGI-INF/blueprint/ImportNamespacesWithXSDIncludeTest.xml");
ComponentDefinitionRegistry cdr = parserService.parse(blueprintXML, context().getBundleByName(TEST_BUNDLE));
assertNotNull(cdr.getComponentDefinition("aries-1682"));
}
private boolean waitForConfig() throws InterruptedException {
final AtomicBoolean ready = new AtomicBoolean();
@SuppressWarnings("rawtypes")
ServiceRegistration reg = context().registerService(
BlueprintListener.class,
new BlueprintListener() {
@Override
public void blueprintEvent(BlueprintEvent event) {
if (TEST_BUNDLE.equals(event.getBundle().getSymbolicName())
&& BlueprintEvent.CREATED == event.getType()) {
synchronized (ready) {
ready.set(true);
ready.notify();
}
}
}
},
null);
try {
synchronized (ready) {
if (!ready.get()) {
ready.wait(3000);
}
}
return ready.get();
} finally {
reg.unregister();
}
}
}
| 9,126 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/FragmentTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.service.blueprint.container.BlueprintContainer;
@RunWith(PaxExam.class)
public class FragmentTest extends AbstractBlueprintIntegrationTest
{
@Test
public void testFragmentProvidesBlueprintFile() throws Exception
{
Runnable r = context().getService(Runnable.class);
Assert.assertNotNull("Could not find blueprint registered service", r);
BlueprintContainer bc = Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.test.host");
Assert.assertNotNull("Could not find blueprint container for bundle", bc);
}
@Configuration
public Option[] configuration() {
InputStream hostJar = TinyBundles.bundle()
.set(Constants.BUNDLE_MANIFESTVERSION, "2")
.set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.test.host").build();
InputStream fragmentJar = TinyBundles.bundle()
.set(Constants.BUNDLE_MANIFESTVERSION, "2")
.set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.test.fragment")
.set(Constants.FRAGMENT_HOST, "org.apache.aries.test.host")
.add("OSGI-INF/blueprint/bp.xml", this.getClass().getResourceAsStream("/bp.xml"))
.build();
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
streamBundle(fragmentJar).noStart(),
streamBundle(hostJar),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample", false)
};
}
} | 9,127 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/QuiesceBlueprintTest.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackages;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
import junit.framework.Assert;
import org.apache.aries.blueprint.testquiescebundle.TestBean;
import org.apache.aries.quiesce.manager.QuiesceCallback;
import org.apache.aries.quiesce.participant.QuiesceParticipant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.options.BootDelegationOption;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerMethod.class)
public class QuiesceBlueprintTest extends AbstractBlueprintIntegrationTest {
private static class TestQuiesceCallback implements QuiesceCallback
{
private int calls = 0;
public synchronized void bundleQuiesced(Bundle... bundlesQuiesced) {
System.out.println("bundleQuiesced "+ Arrays.toString(bundlesQuiesced));
calls++;
}
public synchronized int getCalls() {
return calls;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private QuiesceParticipant getParticipant(String bundleName) throws InvalidSyntaxException {
ServiceReference[] refs = bundleContext.getServiceReferences(QuiesceParticipant.class.getName(), null);
if(refs != null) {
for(ServiceReference ref : refs) {
if(ref.getBundle().getSymbolicName().equals(bundleName))
return (QuiesceParticipant) bundleContext.getService(ref);
else System.out.println(ref.getBundle().getSymbolicName());
}
}
return null;
}
@Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
bootDelegationPackages("javax.transaction", "javax.transaction.*"),
CoreOptions.vmOption("-Dorg.osgi.framework.system.packages=javax.accessibility,javax.activation,javax.activity,javax.annotation,javax.annotation.processing,javax.crypto,javax.crypto.interfaces,javax.crypto.spec,javax.imageio,javax.imageio.event,javax.imageio.metadata,javax.imageio.plugins.bmp,javax.imageio.plugins.jpeg,javax.imageio.spi,javax.imageio.stream,javax.jws,javax.jws.soap,javax.lang.model,javax.lang.model.element,javax.lang.model.type,javax.lang.model.util,javax.management,javax.management.loading,javax.management.modelmbean,javax.management.monitor,javax.management.openmbean,javax.management.relation,javax.management.remote,javax.management.remote.rmi,javax.management.timer,javax.naming,javax.naming.directory,javax.naming.event,javax.naming.ldap,javax.naming.spi,javax.net,javax.net.ssl,javax.print,javax.print.attribute,javax.print.attribute.standard,javax.print.event,javax.rmi,javax.rmi.CORBA,javax.rmi.ssl,javax.script,javax.security.auth,javax.security.auth.callback,javax.security.auth.kerberos,javax.security.auth.login,javax.security.auth.spi,javax.security.auth.x500,javax.security.cert,javax.security.sasl,javax.sound.midi,javax.sound.midi.spi,javax.sound.sampled,javax.sound.sampled.spi,javax.sql,javax.sql.rowset,javax.sql.rowset.serial,javax.sql.rowset.spi,javax.swing,javax.swing.border,javax.swing.colorchooser,javax.swing.event,javax.swing.filechooser,javax.swing.plaf,javax.swing.plaf.basic,javax.swing.plaf.metal,javax.swing.plaf.multi,javax.swing.plaf.synth,javax.swing.table,javax.swing.text,javax.swing.text.html,javax.swing.text.html.parser,javax.swing.text.rtf,javax.swing.tree,javax.swing.undo,javax.tools,javax.xml,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.bind.util,javax.xml.crypto,javax.xml.crypto.dom,javax.xml.crypto.dsig,javax.xml.crypto.dsig.dom,javax.xml.crypto.dsig.keyinfo,javax.xml.crypto.dsig.spec,javax.xml.datatype,javax.xml.namespace,javax.xml.parsers,javax.xml.soap,javax.xml.stream,javax.xml.stream.events,javax.xml.stream.util,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stax,javax.xml.transform.stream,javax.xml.validation,javax.xml.ws,javax.xml.ws.handler,javax.xml.ws.handler.soap,javax.xml.ws.http,javax.xml.ws.soap,javax.xml.ws.spi,javax.xml.xpath,org.ietf.jgss,org.omg.CORBA,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA.TypeCodePackage,org.omg.CORBA.portable,org.omg.CORBA_2_3,org.omg.CORBA_2_3.portable,org.omg.CosNaming,org.omg.CosNaming.NamingContextExtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.Dynamic,org.omg.DynamicAny,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage,org.omg.IOP,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage,org.omg.Messaging,org.omg.PortableInterceptor,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.PortableServer,org.omg.PortableServer.CurrentPackage,org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.ServantLocatorPackage,org.omg.PortableServer.portable,org.omg.SendingContext,org.omg.stub.java.rmi,org.w3c.dom,org.w3c.dom.bootstrap,org.w3c.dom.css,org.w3c.dom.events,org.w3c.dom.html,org.w3c.dom.ls,org.w3c.dom.ranges,org.w3c.dom.stylesheets,org.w3c.dom.traversal,org.w3c.dom.views,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers,javax.transaction;partial=true;mandatory:=partial,javax.transaction.xa;partial=true;mandatory:=partial"),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.quiesce", "org.apache.aries.quiesce.api"),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testbundlea", false),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testbundleb", false),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.testquiescebundle")
};
}
protected Bundle getBundle(String symbolicName) {
return getBundle(symbolicName, null);
}
protected Bundle getBundle(String bundleSymbolicName, String version) {
Bundle result = null;
for (Bundle b : bundleContext.getBundles()) {
if (b.getSymbolicName().equals(bundleSymbolicName)) {
if (version == null
|| b.getVersion().equals(Version.parseVersion(version))) {
result = b;
break;
}
}
}
return result;
}
public static BootDelegationOption bootDelegation() {
return new BootDelegationOption("org.apache.aries.unittest.fixture");
}
@Test
public void testBasicQuieseEmptyCounter() throws Exception
{
//This test checks that a single bundle when called will not quiesce while
//there is an active request (method sleeps), but will quiesce after the
//request is completed.
System.out.println("In testBasicQuieseEmptyCounter");
Object obj = context().getService(TestBean.class);
if (obj != null)
{
QuiesceParticipant participant = getParticipant("org.apache.aries.blueprint.core");
if (participant != null)
{
System.out.println(obj.getClass().getName());
TestQuiesceCallback callback = new TestQuiesceCallback();
Bundle bundle = getBundle("org.apache.aries.blueprint.testquiescebundle");
System.out.println("Got the bundle");
List<Bundle> bundles = new ArrayList<Bundle>();
bundles.add(bundle);
Thread t = new Thread(new TestBeanClient((TestBean)obj, 2000));
t.start();
System.out.println("Thread Started");
participant.quiesce(callback, bundles);
System.out.println("Called Quiesce");
Thread.sleep(1000);
Assert.assertTrue("Quiesce callback should not have occurred yet; calls should be 0, but it is "+callback.getCalls(), callback.getCalls()==0);
t.join();
System.out.println("After join");
Assert.assertTrue("Quiesce callback should have occurred once; calls should be 1, but it is "+callback.getCalls(), callback.getCalls()==1);
}
else
{
throw new Exception("No Quiesce Participant found for the blueprint service");
}
System.out.println("done");
}
else
{
throw new Exception("No Service returned for " + TestBean.class);
}
}
@Test
public void testNoServicesQuiesce() throws Exception {
//This test covers the case where one of the bundles being asked to quiesce has no
//services. It should be quiesced immediately.
System.out.println("In testNoServicesQuiesce");
Object obj = context().getService(TestBean.class);
if (obj != null)
{
QuiesceParticipant participant = getParticipant("org.apache.aries.blueprint.core");
if (participant != null)
{
TestQuiesceCallback callbackA = new TestQuiesceCallback();
TestQuiesceCallback callbackB = new TestQuiesceCallback();
//bundlea provides the ns handlers, bean processors, interceptors etc for this test.
Bundle bundlea = getBundle("org.apache.aries.blueprint.testbundlea");
assertNotNull(bundlea);
bundlea.start();
//bundleb has no services and makes use of the extensions provided by bundlea
Bundle bundleb = getBundle("org.apache.aries.blueprint.testbundleb");
assertNotNull(bundleb);
bundleb.start();
Helper.getBlueprintContainerForBundle(context(), "org.apache.aries.blueprint.testbundleb");
participant.quiesce(callbackB, Collections.singletonList(getBundle(
"org.apache.aries.blueprint.testbundleb")));
System.out.println("Called Quiesce");
Thread.sleep(200);
Assert.assertTrue("Quiesce callback B should have occurred; calls should be 1, but it is "+callbackB.getCalls(), callbackB.getCalls()==1);
Assert.assertTrue("Quiesce callback A should not have occurred yet; calls should be 0, but it is "+callbackA.getCalls(), callbackA.getCalls()==0);
bundleb.stop();
participant.quiesce(callbackA, Collections.singletonList(getBundle(
"org.apache.aries.blueprint.testbundlea")));
Thread.sleep(1000);
System.out.println("After second sleep");
Assert.assertTrue("Quiesce callback A should have occurred once; calls should be 1, but it is "+callbackA.getCalls(), callbackA.getCalls()==1);
Assert.assertTrue("Quiesce callback B should have occurred once; calls should be 1, but it is "+callbackB.getCalls(), callbackB.getCalls()==1);
}else{
throw new Exception("No Quiesce Participant found for the blueprint service");
}
}else{
throw new Exception("No Service returned for " + TestBean.class);
}
}
@Test
public void testMultiBundleQuiesce() throws Exception {
//This test covers the case where two bundles are quiesced at the same time.
//Bundle A should quiesce immediately, quiesce bundle should quiesce after the
//request has completed.
System.out.println("In testMultiBundleQuiesce");
Object obj = context().getService(TestBean.class);
if (obj != null)
{
QuiesceParticipant participant = getParticipant("org.apache.aries.blueprint.core");
if (participant != null)
{
TestQuiesceCallback callback = new TestQuiesceCallback();
//bundlea provides the ns handlers, bean processors, interceptors etc for this test.
Bundle bundlea = getBundle("org.apache.aries.blueprint.testbundlea");
assertNotNull(bundlea);
bundlea.start();
//quiesce bundle will sleep for a second so will quiesce after that
Bundle bundleq = getBundle("org.apache.aries.blueprint.testquiescebundle");
System.out.println("Got the bundle");
List<Bundle> bundles = new ArrayList<Bundle>();
bundles.add(bundlea);
bundles.add(bundleq);
Thread t = new Thread(new TestBeanClient((TestBean)obj, 1500));
t.start();
Thread.sleep(200);
participant.quiesce(callback, bundles);
System.out.println("Called Quiesce");
Thread.sleep(500);
Assert.assertTrue("Quiesce callback should have occurred once for bundle a but not for bundle q; calls should be 1, but it is "+callback.getCalls(), callback.getCalls()==1);
Thread.sleep(1500);
System.out.println("After second sleep");
Assert.assertTrue("Quiesce callback should have occurred twice, once for bundle a and q respectively; calls should be 2, but it is "+callback.getCalls(), callback.getCalls()==2);
}else{
throw new Exception("No Quiesce Participant found for the blueprint service");
}
}else{
throw new Exception("No Service returned for " + TestBean.class);
}
}
@Test
public void testMultiRequestQuiesce() throws Exception {
//This test covers the case where we have two active requests when
//the bundle is being quiesced.
System.out.println("In testMultiRequestQuiesce");
Object obj = context().getService(TestBean.class);
if (obj != null)
{
QuiesceParticipant participant = getParticipant("org.apache.aries.blueprint.core");
if (participant != null)
{
TestQuiesceCallback callback = new TestQuiesceCallback();
TestBeanClient client = new TestBeanClient((TestBean)obj, 1500);
//quiesce bundle will sleep for a second so will quiesce after that
Bundle bundle = getBundle("org.apache.aries.blueprint.testquiescebundle");
System.out.println("Got the bundle");
List<Bundle> bundles = new ArrayList<Bundle>();
bundles.add(bundle);
Thread t = new Thread(client);
t.start();
participant.quiesce(callback, bundles);
System.out.println("Called Quiesce, putting in a new request");
Thread t2 = new Thread(client);
t2.start();
Thread.sleep(5000);
Assert.assertTrue("Quiesce callback should have occurred once; calls should be 1, but it is "+callback.getCalls(), callback.getCalls()==1);
}else{
throw new Exception("No Quiesce Participant found for the blueprint service");
}
}else{
throw new Exception("No Service returned for " + TestBean.class);
}
}
private class TestBeanClient implements Runnable
{
private final TestBean myService;
private final int time;
public TestBeanClient(TestBean myService, int time)
{
this.myService = myService;
this.time = time;
}
public void run()
{
try
{
System.out.println("In Test Bean Client - Sleeping zzzzzzz");
myService.sleep(time);
System.out.println("Woken up");
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
| 9,128 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/MemoryLeakTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.provision;
import java.io.InputStream;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
public class MemoryLeakTest extends AbstractBlueprintIntegrationTest {
@Test
public void testScheduledExecMemoryLeak() throws Exception {
Bundle b = context().getBundleByName("test.bundle");
long startFreeMemory = getFreeMemory();
// 3000 iterations on a Mac 1.6 JVM leaks 30+ mb, 2000 leaks a bit more than 20,
// 10000 iterations would be close to OutOfMemory however by that stage the test runs very slowly
for (int i=0; i<1500; i++) {
b.start();
// give the container some time to operate, otherwise it probably won't even get to create a future
Thread.sleep(10);
b.stop();
}
long endFreeMemory = getFreeMemory();
long lossage = startFreeMemory - endFreeMemory;
System.out.println("We lost: " + lossage);
// increase the lossage value as it may depends of the JDK
assertTrue("We lost: " + lossage, lossage < 77000000);
}
private long getFreeMemory() {
for (int i=0; i<16; i++) System.gc();
return Runtime.getRuntime().freeMemory();
}
private InputStream memoryLeakTestBundle() {
return TinyBundles.bundle()
.add("OSGI-INF/blueprint/blueprint.xml", this.getClass().getResource("/bp2.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, "test.bundle")
.build();
}
@org.ops4j.pax.exam.Configuration
public Option[] configuration() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
provision(memoryLeakTestBundle())
};
}
}
| 9,129 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/comp/ListFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.comp;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class ListFactory {
public static List<Integer> create(int no) {
System.out.println(Thread.currentThread().getId()+": creating list");
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException ie) {}
System.out.println(Thread.currentThread().getId()+": created");
return Arrays.asList(no);
}
}
| 9,130 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/comp/Listener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.comp;
import java.util.Random;
public class Listener {
public void bind(Object service) {
try {
Thread.sleep(new Random().nextInt(20));
} catch (InterruptedException ie) {}
System.out.println(Thread.currentThread().getId()+": bind "+service);
}
public void unbind(Object service) {
try {
Thread.sleep(new Random().nextInt(20));
} catch (InterruptedException ie) {}
System.out.println(Thread.currentThread().getId()+": unbind "+service);
}
}
| 9,131 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/AuthorizationTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.authz;
import static org.apache.aries.blueprint.itests.Helper.mvnBundle;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import java.io.IOException;
import java.io.InputStream;
import java.security.AccessControlException;
import java.security.PrivilegedAction;
import javax.inject.Inject;
import javax.security.auth.login.LoginException;
import org.apache.aries.blueprint.itests.AbstractBlueprintIntegrationTest;
import org.apache.aries.blueprint.itests.Helper;
import org.apache.aries.blueprint.itests.authz.helper.JAASHelper;
import org.apache.aries.blueprint.itests.authz.testbundle.SecuredService;
import org.apache.aries.blueprint.itests.authz.testbundle.impl.SecuredServiceImpl;
import org.junit.Test;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
/**
* Test calling a service that is secured using the blueprint-authz module.
*
* Access is regulated using JEE security annotations
* @see SecuredServiceImpl
*/
public class AuthorizationTest extends AbstractBlueprintIntegrationTest {
@Inject
SecuredService service;
@Test
public void testOnlyAdminOk() throws LoginException, BundleException {
JAASHelper.doAs(new String[] {"admin"}, new CallOnlyAdmin());
}
@Test(expected = AccessControlException.class)
public void testOnlyAdminDenied() throws LoginException, BundleException {
JAASHelper.doAs(new String[] {"user"}, new CallOnlyAdmin());
}
@Test
public void testUserAdndAdminOk() throws LoginException, BundleException {
JAASHelper.doAs(new String[] {"admin"}, new CallUserAndAdmin());
JAASHelper.doAs(new String[] {"user"}, new CallUserAndAdmin());
}
@Test(expected = AccessControlException.class)
public void testUserAdndAdminDeniedForUnauthenticated() throws LoginException, BundleException {
service.userAndAdmin("Hi");
}
@Test
public void testAnyOneUnauthenticatedOk() throws LoginException, BundleException {
service.anyOne("Hi");
}
@Test(expected = AccessControlException.class)
public void testDenyAll() throws LoginException, BundleException {
JAASHelper.doAs(new String[] {"admin"}, new CallNoOne());
}
@ProbeBuilder
public TestProbeBuilder probeConfiguration(TestProbeBuilder probe) {
probe.setHeader(Constants.EXPORT_PACKAGE, SecuredService.class.getPackage().getName());
probe.setHeader(Constants.IMPORT_PACKAGE, SecuredService.class.getPackage().getName());
return probe;
}
@org.ops4j.pax.exam.Configuration
public Option[] configuration() throws IOException, LoginException, BundleException {
return new Option[] {
baseOptions(),
CoreOptions.keepCaches(),
Helper.blueprintBundles(),
mvnBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.authz"),
streamBundle(testBundle()),
};
}
private InputStream testBundle() {
InputStream testBundle = TinyBundles.bundle()
.set(Constants.BUNDLE_SYMBOLICNAME, "authz")
.add(SecuredServiceImpl.class)
.add(SecuredService.class)
.add("OSGI-INF/blueprint/authz.xml", this.getClass().getResourceAsStream("/authz.xml"))
.set(Constants.EXPORT_PACKAGE, SecuredService.class.getPackage().getName())
.set(Constants.IMPORT_PACKAGE, SecuredService.class.getPackage().getName())
.build(TinyBundles.withBnd());
return testBundle;
}
private final class CallUserAndAdmin implements PrivilegedAction<Void> {
@Override
public Void run() {
service.userAndAdmin("Hi");
return null;
}
}
private final class CallOnlyAdmin implements PrivilegedAction<Void> {
@Override
public Void run() {
service.onlyAdmin("Hi");
return null;
}
}
private final class CallNoOne implements PrivilegedAction<Void> {
@Override
public Void run() {
service.noOne("Hi");
return null;
}
}
} | 9,132 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/testbundle/SecuredService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.authz.testbundle;
public interface SecuredService {
String userAndAdmin(String msg);
String onlyAdmin(String msg);
String anyOne(String msg);
String noOne(String msg);
}
| 9,133 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/testbundle | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/testbundle/impl/SecuredServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.authz.testbundle.impl;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import org.apache.aries.blueprint.itests.authz.testbundle.SecuredService;
@RolesAllowed("admin")
public class SecuredServiceImpl implements SecuredService {
@RolesAllowed({"user", "admin"})
public String userAndAdmin(String msg) {
return msg;
}
public String onlyAdmin(String msg) {
return msg;
}
@PermitAll
public String anyOne(String msg) {
return msg;
}
@DenyAll
public String noOne(String msg) {
return msg;
}
}
| 9,134 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/helper/SimpleLoginModule.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.authz.helper;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
public class SimpleLoginModule implements LoginModule {
private Subject subject;
private String name;
private String[] groups;
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
Map<String, ?> options) {
this.subject = subject;
this.name = (String)options.get("username");
this.groups = (String[])options.get("groups");
}
@Override
public boolean login() throws LoginException {
return true;
}
@Override
public boolean commit() throws LoginException {
subject.getPrincipals().add(new UserPrincipal(name));
for (String group : groups) {
subject.getPrincipals().add(new GroupPrincipal(group));
}
return true;
}
@Override
public boolean abort() throws LoginException {
return true;
}
@Override
public boolean logout() throws LoginException {
subject.getPrincipals().clear();
return true;
}
}
| 9,135 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/helper/NamedPrincipal.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.authz.helper;
import java.security.Principal;
public class NamedPrincipal implements Principal {
private String name;
public NamedPrincipal(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
} | 9,136 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/helper/JAASHelper.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.authz.helper;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
public class JAASHelper {
public static <T> void doAs(final String[] groups, PrivilegedAction<T> action) {
Configuration config = new Configuration() {
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, Object> options = new HashMap<String, Object>();
options.put("username", "dummy"); // The user does not matter
options.put("groups", groups);
AppConfigurationEntry entry = new AppConfigurationEntry(SimpleLoginModule.class.getName(),
LoginModuleControlFlag.REQUIRED,
options);
return new AppConfigurationEntry[] {
entry
};
}
};
try {
LoginContext lc = new LoginContext("test", new Subject(), null, config);
lc.login();
Subject.doAs(lc.getSubject(), action);
lc.logout();
} catch (LoginException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
| 9,137 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/helper/UserPrincipal.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.authz.helper;
public class UserPrincipal extends NamedPrincipal {
public UserPrincipal(String name) {
super(name);
}
}
| 9,138 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/helper/GroupPrincipal.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.authz.helper;
public class GroupPrincipal extends NamedPrincipal {
public GroupPrincipal(String name) {
super(name);
}
}
| 9,139 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/CmPropertyPlaceholderTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm;
import java.io.InputStream;
import java.util.Hashtable;
import javax.inject.Inject;
import org.apache.aries.blueprint.itests.AbstractBlueprintIntegrationTest;
import org.apache.aries.blueprint.itests.Helper;
import org.apache.aries.blueprint.itests.cm.service.Foo;
import org.apache.aries.blueprint.itests.cm.service.FooFactory;
import org.apache.aries.blueprint.itests.cm.service.FooInterface;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.*;
import static org.ops4j.pax.exam.CoreOptions.keepCaches;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
public class CmPropertyPlaceholderTest extends AbstractBlueprintIntegrationTest {
private static final String TEST_BUNDLE = "org.apache.aries.blueprint.cm.test.b1";
@Inject
ConfigurationAdmin ca;
@ProbeBuilder
public TestProbeBuilder probeConfiguration(TestProbeBuilder probe) {
probe.setHeader(Constants.EXPORT_PACKAGE, Foo.class.getPackage().getName());
probe.setHeader(Constants.IMPORT_PACKAGE, Foo.class.getPackage().getName());
return probe;
}
@org.ops4j.pax.exam.Configuration
public Option[] config() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
keepCaches(),
streamBundle(testBundle())
};
}
protected InputStream testBundle() {
return TinyBundles.bundle() //
.add(FooInterface.class) //
.add(Foo.class) //
.add(FooFactory.class) //
.add("OSGI-INF/blueprint/context.xml", getResource("CmPropertyPlaceholderTest.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, TEST_BUNDLE) //
.set(Constants.EXPORT_PACKAGE, Foo.class.getPackage().getName()) //
.set(Constants.IMPORT_PACKAGE, Foo.class.getPackage().getName()) //
.build(TinyBundles.withBnd());
}
@Test
public void testProperties() throws Exception {
ServiceReference sr = getServiceRef(FooInterface.class, "(key=foo5)");
assertNotNull(sr);
FooInterface foo = (FooInterface)context().getService(sr);
assertNotNull(foo);
assertThat(foo.getB(), equalTo("42"));
assertThat(foo.getC(), nullValue());
Configuration cf = ca.getConfiguration("blueprint-sample-properties.pid", null);
Hashtable<String,Object> props = new Hashtable<String,Object>();
props.put("pb", "43");
cf.update(props);
Thread.sleep(500);
sr = getServiceRef(FooInterface.class, "(key=foo5)");
foo = (FooInterface)context().getService(sr);
assertEquals("43", foo.getB());
props.clear();
props.put("pc", 7);
props.put("pd", new int[] { 3, 4 });
cf.update(props);
Thread.sleep(500);
sr = getServiceRef(FooInterface.class, "(key=foo5)");
foo = (FooInterface)context().getService(sr);
assertEquals(7L, (long) foo.getC());
assertArrayEquals(new int[] { 3, 4 }, (int[]) foo.getD());
cf.delete();
Thread.sleep(500);
sr = getServiceRef(FooInterface.class, "(key=foo5)");
foo = (FooInterface)context().getService(sr);
assertEquals(foo.getB(), "42");
}
@SuppressWarnings("rawtypes")
private ServiceReference getServiceRef(Class serviceInterface, String filter)
throws InvalidSyntaxException {
int tries = 0;
do {
ServiceReference[] srAr = bundleContext.getServiceReferences(serviceInterface.getName(), filter);
if (srAr != null && srAr.length > 0) {
return srAr[0];
}
tries++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
} while (tries < 100);
throw new RuntimeException("Could not find service " + serviceInterface.getName() + ", " + filter);
}
}
| 9,140 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/CmPropertiesTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm;
import java.io.InputStream;
import java.util.Hashtable;
import javax.inject.Inject;
import org.apache.aries.blueprint.itests.AbstractBlueprintIntegrationTest;
import org.apache.aries.blueprint.itests.Helper;
import org.apache.aries.blueprint.itests.cm.service.Foo;
import org.apache.aries.blueprint.itests.cm.service.FooFactory;
import org.apache.aries.blueprint.itests.cm.service.FooInterface;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import static org.junit.Assert.*;
import static org.ops4j.pax.exam.CoreOptions.keepCaches;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
public class CmPropertiesTest extends AbstractBlueprintIntegrationTest {
private static final String TEST_BUNDLE = "org.apache.aries.blueprint.cm.test.b1";
@Inject
ConfigurationAdmin ca;
@ProbeBuilder
public TestProbeBuilder probeConfiguration(TestProbeBuilder probe) {
probe.setHeader(Constants.EXPORT_PACKAGE, Foo.class.getPackage().getName());
probe.setHeader(Constants.IMPORT_PACKAGE, Foo.class.getPackage().getName());
return probe;
}
@org.ops4j.pax.exam.Configuration
public Option[] config() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
keepCaches(),
streamBundle(testBundle())
};
}
protected InputStream testBundle() {
return TinyBundles.bundle() //
.add(FooInterface.class) //
.add(Foo.class) //
.add(FooFactory.class) //
.add("OSGI-INF/blueprint/context.xml", getResource("CmPropertiesTest.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, TEST_BUNDLE) //
.set(Constants.EXPORT_PACKAGE, Foo.class.getPackage().getName()) //
.set(Constants.IMPORT_PACKAGE, Foo.class.getPackage().getName()) //
.build(TinyBundles.withBnd());
}
@Test
public void testProperties() throws Exception {
ServiceReference sr = getServiceRef(FooInterface.class, "(key=foo4)");
assertNotNull(sr);
FooInterface foo = (FooInterface)context().getService(sr);
assertNotNull(foo);
assertNotNull(foo.getProps());
assertTrue(foo.getProps().isEmpty());
Configuration cf = ca.getConfiguration("blueprint-sample-properties.pid", null);
Hashtable<String,String> props = new Hashtable<String,String>();
props.put("a", "5");
cf.update(props);
Thread.sleep(500);
assertFalse(foo.getProps().isEmpty());
assertEquals("5", foo.getProps().getProperty("a"));
props.put("a", "6");
cf.update(props);
Thread.sleep(500);
assertFalse(foo.getProps().isEmpty());
assertEquals("6", foo.getProps().getProperty("a"));
cf.delete();
Thread.sleep(500);
assertNull(foo.getProps().getProperty("a"));
}
@SuppressWarnings("rawtypes")
private ServiceReference getServiceRef(Class serviceInterface, String filter)
throws InvalidSyntaxException {
int tries = 0;
do {
ServiceReference[] srAr = bundleContext.getServiceReferences(serviceInterface.getName(), filter);
if (srAr != null && srAr.length > 0) {
return srAr[0];
}
tries++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
} while (tries < 100);
throw new RuntimeException("Could not find service " + serviceInterface.getName() + ", " + filter);
}
}
| 9,141 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/ManagedServiceFactoryTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.ops4j.pax.exam.CoreOptions.keepCaches;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import java.io.InputStream;
import java.util.Hashtable;
import javax.inject.Inject;
import org.apache.aries.blueprint.itests.AbstractBlueprintIntegrationTest;
import org.apache.aries.blueprint.itests.Helper;
import org.apache.aries.blueprint.itests.cm.service.Foo;
import org.apache.aries.blueprint.itests.cm.service.FooFactory;
import org.apache.aries.blueprint.itests.cm.service.FooInterface;
import org.junit.Test;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
public class ManagedServiceFactoryTest extends AbstractBlueprintIntegrationTest {
private static final String TEST_BUNDLE = "org.apache.aries.blueprint.cm.test.b1";
@Inject
ConfigurationAdmin ca;
@ProbeBuilder
public TestProbeBuilder probeConfiguration(TestProbeBuilder probe) {
probe.setHeader(Constants.EXPORT_PACKAGE, Foo.class.getPackage().getName());
probe.setHeader(Constants.IMPORT_PACKAGE, Foo.class.getPackage().getName());
return probe;
}
@org.ops4j.pax.exam.Configuration
public Option[] config() {
return new Option[] {
baseOptions(),
Helper.blueprintBundles(),
keepCaches(),
streamBundle(testBundle())
};
}
protected InputStream testBundle() {
return TinyBundles.bundle() //
.add(FooInterface.class) //
.add(Foo.class) //
.add(FooFactory.class) //
.add("OSGI-INF/blueprint/context.xml", getResource("ManagedServiceFactoryTest.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, TEST_BUNDLE) //
.set(Constants.EXPORT_PACKAGE, Foo.class.getPackage().getName()) //
.set(Constants.IMPORT_PACKAGE, Foo.class.getPackage().getName()) //
.build(TinyBundles.withBnd());
}
@Test
public void test1() throws Exception {
Configuration cf = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory", null);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("a", "5");
cf.update(props);
@SuppressWarnings("rawtypes")
ServiceReference sr = getServiceRef(Foo.class, "(key=foo1)");
Foo foo = (Foo)context().getService(sr);
assertNotNull(foo);
assertEquals(5, foo.getA());
assertEquals("default", foo.getB());
assertEquals("5", sr.getProperty("a"));
assertNull(sr.getProperty("b"));
props = new Hashtable<String, String>();
props.put("a", "5");
props.put("b", "foo");
cf.update(props);
Thread.sleep(500);
// No update of bean after creation
assertEquals(5, foo.getA());
assertEquals("default", foo.getB());
// Only initial update of service properties
assertEquals("5", sr.getProperty("a"));
assertNull(sr.getProperty("b"));
}
@Test
public void test2() throws Exception {
Configuration cf = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory2", null);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("a", "5");
cf.update(props);
@SuppressWarnings("rawtypes")
ServiceReference sr = getServiceRef(Foo.class, "(key=foo2)");
Foo foo = (Foo)context().getService(sr);
assertNotNull(foo);
assertEquals(5, foo.getA());
assertEquals("default", foo.getB());
assertNull(sr.getProperty("a"));
assertNull(sr.getProperty("b"));
props = new Hashtable<String, String>();
props.put("a", "5");
props.put("b", "foo");
cf.update(props);
// Update after creation
Thread.sleep(500);
assertEquals(5, foo.getA());
assertEquals("foo", foo.getB());
// No update of service properties
assertNull(sr.getProperty("a"));
assertNull(sr.getProperty("b"));
}
@Test
public void test3() throws Exception {
Configuration cf = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory3", null);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("a", "5");
cf.update(props);
@SuppressWarnings("rawtypes")
ServiceReference sr = getServiceRef(Foo.class, "(&(key=foo3)(a=5))");
assertNotNull(sr);
Foo foo = (Foo)context().getService(sr);
assertNotNull(foo);
assertEquals(5, foo.getA());
assertEquals("default", foo.getB());
assertEquals("5", sr.getProperty("a"));
assertNull(sr.getProperty("b"));
props = new Hashtable<String, String>();
props.put("a", "5");
props.put("b", "foo");
cf.update(props);
// Update after creation
Thread.sleep(500);
assertEquals(5, foo.getA());
assertEquals("foo", foo.getB());
// Update of service properties
assertEquals("5", sr.getProperty("a"));
assertEquals("foo", sr.getProperty("b"));
cf.delete();
}
@SuppressWarnings("rawtypes")
@Test
public void testCreateAndUpdate() throws Exception {
Configuration cf = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory3", null);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("a", "5");
cf.update(props);
Configuration cf2 = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory3", null);
Hashtable<String, String> props2 = new Hashtable<String, String>();
props2.put("a", "7");
cf2.update(props2);
ServiceReference sr = getServiceRef(Foo.class, "(&(key=foo3)(a=5))");
ServiceReference sr2 = getServiceRef(Foo.class, "(&(key=foo3)(a=7))");
Foo foo = (Foo)context().getService(sr);
assertNotNull(foo);
assertEquals(5, foo.getA());
assertEquals("default", foo.getB());
assertEquals("5", sr.getProperty("a"));
assertNull(sr.getProperty("b"));
Foo foo2 = (Foo)context().getService(sr2);
assertNotNull(foo2);
assertEquals(7, foo2.getA());
assertEquals("default", foo2.getB());
assertEquals("7", sr2.getProperty("a"));
assertNull(sr2.getProperty("b"));
props = new Hashtable<String, String>();
props.put("a", "5");
props.put("b", "foo");
cf.update(props);
props2 = new Hashtable<String, String>();
props2.put("a", "7");
props2.put("b", "foo2");
cf2.update(props2);
// Update after creation
Thread.sleep(500);
assertEquals(5, foo.getA());
assertEquals("foo", foo.getB());
// Update of service properties
assertEquals("5", sr.getProperty("a"));
assertEquals("foo", sr.getProperty("b"));
// 2a Update after creation
assertEquals(7, foo2.getA());
assertEquals("foo2", foo2.getB());
// 2b Update of service properties
assertEquals("7", sr2.getProperty("a"));
assertEquals("foo2", sr2.getProperty("b"));
cf.delete();
cf2.delete();
}
@SuppressWarnings("rawtypes")
@Test
public void testCreateAndUpdateUsingUpdateMethod() throws Exception {
Configuration cf = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory4", null);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("a", "5");
cf.update(props);
Configuration cf2 = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory4", null);
Hashtable<String, String> props2 = new Hashtable<String, String>();
props2.put("a", "7");
cf2.update(props2);
ServiceReference sr = getServiceRef(Foo.class, "(&(key=foo4)(a=5))");
ServiceReference sr2 = getServiceRef(Foo.class, "(&(key=foo4)(a=7))");
Foo foo = (Foo)context().getService(sr);
assertNotNull(foo);
assertEquals(5, foo.getA());
assertEquals("default", foo.getB());
assertEquals("5", sr.getProperty("a"));
assertNull(sr.getProperty("b"));
Foo foo2 = (Foo)context().getService(sr2);
assertNotNull(foo2);
assertEquals(7, foo2.getA());
assertEquals("default", foo2.getB());
assertEquals("7", sr2.getProperty("a"));
assertNull(sr2.getProperty("b"));
props = new Hashtable<String, String>();
props.put("a", "5");
props.put("b", "foo");
cf.update(props);
props2 = new Hashtable<String, String>();
props2.put("a", "7");
props2.put("b", "foo2");
cf2.update(props2);
// Update after creation
Thread.sleep(500);
assertEquals(5, foo.getA());
assertEquals("foo", foo.getB());
// Update of service properties
assertEquals("5", sr.getProperty("a"));
assertEquals("foo", sr.getProperty("b"));
// 2a Update after creation
assertEquals(7, foo2.getA());
assertEquals("foo2", foo2.getB());
// 2b Update of service properties
assertEquals("7", sr2.getProperty("a"));
assertEquals("foo2", sr2.getProperty("b"));
}
@Test
public void testFactoryCreation() throws Exception {
Configuration cf = ca.createFactoryConfiguration("blueprint-sample-managed-service-factory5", null);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("a", "5");
cf.update(props);
@SuppressWarnings("rawtypes")
ServiceReference sr = getServiceRef(Foo.class, "(key=foo5)");
Foo foo = (Foo)context().getService(sr);
assertNotNull(foo);
assertEquals(5, foo.getA());
assertEquals("default", foo.getB());
assertEquals("5", sr.getProperty("a"));
assertNull(sr.getProperty("b"));
props = new Hashtable<String, String>();
props.put("a", "5");
props.put("b", "foo");
cf.update(props);
Thread.sleep(500);
// No update of bean after creation
assertEquals(5, foo.getA());
assertEquals("default", foo.getB());
// Only initial update of service properties
assertEquals("5", sr.getProperty("a"));
assertNull(sr.getProperty("b"));
}
@SuppressWarnings("rawtypes")
private ServiceReference getServiceRef(Class serviceInterface, String filter)
throws InvalidSyntaxException {
int tries = 0;
do {
ServiceReference[] srAr = bundleContext.getServiceReferences(serviceInterface.getName(), filter);
if (srAr != null && srAr.length > 0) {
return (ServiceReference)srAr[0];
}
tries++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
} while (tries < 100);
throw new RuntimeException("Could not find service " + serviceInterface.getName() + ", " + filter);
}
}
| 9,142 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/ManagedServiceFactoryUseSystemBundleTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm;
import static org.ops4j.pax.exam.CoreOptions.keepCaches;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.apache.aries.blueprint.itests.Helper;
import org.junit.After;
import org.junit.Before;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.hooks.service.EventListenerHook;
import org.osgi.framework.hooks.service.FindHook;
/**
* Shows that the cm bundle can process config even if the events are hidden from it
* when the property to use the system bundle context is set
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class ManagedServiceFactoryUseSystemBundleTest extends ManagedServiceFactoryTest {
private static final String CM_BUNDLE = "org.apache.aries.blueprint.cm";
@org.ops4j.pax.exam.Configuration
public Option[] config() {
return new Option[] {
baseOptions(),
systemProperty("org.apache.aries.blueprint.use.system.context").value("true"),
Helper.blueprintBundles(), //
keepCaches(), //
streamBundle(testBundle())
};
}
ServiceRegistration eventHook;
ServiceRegistration findHook;
@Before
public void regiserHook() throws BundleException {
context().getBundleByName(CM_BUNDLE).stop();
final BundleContext systemContext = context().getBundle(Constants.SYSTEM_BUNDLE_LOCATION)
.getBundleContext();
eventHook = context().registerService(EventListenerHook.class, new EventListenerHook() {
public void event(ServiceEvent event, Map contexts) {
if (CM_BUNDLE.equals(event.getServiceReference().getBundle().getSymbolicName())) {
// hide from everything but the system bundle
// TODO on R6 we should be able to even try hiding from the system bundle
// R5 it was not clear if hooks could hide from the system bundle
// equinox R5 does allow hiding from system bundle
contexts.keySet().retainAll(Collections.singleton(systemContext));
}
}
}, null);
findHook = context().registerService(FindHook.class, new FindHook() {
public void find(BundleContext context, String arg1, String arg2, boolean arg3,
Collection references) {
// hide from everything but the system bundle
// TODO on R6 we should be able to even try hiding from the system bundle
// R5 it was not clear if hooks could hide from the system bundle
// equinox R5 does allow hiding from system bundle
if (!context.equals(systemContext)) {
for (Iterator<ServiceReference> iReferences = references.iterator(); iReferences
.hasNext();) {
if (CM_BUNDLE.equals(iReferences.next().getBundle().getSymbolicName())) {
iReferences.remove();
}
}
}
}
}, null);
context().getBundleByName(CM_BUNDLE).start();
}
@After
public void unregisterHook() {
eventHook.unregister();
findHook.unregister();
}
}
| 9,143 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/handler/Aries1503aNamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm.handler;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Aries1503aNamespaceHandler implements NamespaceHandler {
@Override
public URL getSchemaLocation(String namespace) {
if ("http://aries.apache.org/blueprint/xmlns/blueprint-aries-1503/v1.0.0".equals(namespace)) {
return getClass().getResource("/blueprint-aries-1503.xsd");
}
return null;
}
@Override
public Set<Class> getManagedClasses() {
return new HashSet<Class>(Collections.<Class>singletonList(String.class));
}
@Override
public Metadata parse(Element element, ParserContext context) {
MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
metadata.setProcessor(true);
metadata.setId("aries-1503");
metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
metadata.addArgument(new PassThroughMetadata() {
@Override
public Object getObject() {
return "ARIES-1503";
}
@Override
public String getId() {
return "aries-1503-arg";
}
@Override
public int getActivation() {
return 0;
}
@Override
public List<String> getDependsOn() {
return null;
}
}, null, 0);
metadata.setRuntimeClass(String.class);
return metadata;
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
return null;
}
}
| 9,144 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/handler/Aries1682NamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm.handler;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Aries1682NamespaceHandler implements NamespaceHandler {
@Override
public URL getSchemaLocation(String namespace) {
if ("http://aries.apache.org/blueprint/xmlns/blueprint-aries-1682/v1.0.0".equals(namespace)) {
try {
return new URL("jar:" + FrameworkUtil.getBundle(this.getClass()).getLocation() + "!/blueprint-aries-1682.xsd");
} catch (MalformedURLException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
return null;
}
@Override
public Set<Class> getManagedClasses() {
return new HashSet<Class>(Collections.<Class>singletonList(String.class));
}
@Override
public Metadata parse(Element element, ParserContext context) {
MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
metadata.setProcessor(true);
metadata.setId("aries-1682");
metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
metadata.addArgument(new PassThroughMetadata() {
@Override
public Object getObject() {
return "ARIES-1682";
}
@Override
public String getId() {
return "aries-1682-arg";
}
@Override
public int getActivation() {
return 0;
}
@Override
public List<String> getDependsOn() {
return null;
}
}, null, 0);
metadata.setRuntimeClass(String.class);
return metadata;
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
return null;
}
}
| 9,145 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/handler/IncorrectNamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm.handler;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class IncorrectNamespaceHandler implements NamespaceHandler {
@Override
public URL getSchemaLocation(String namespace) {
if ("http://aries.apache.org/incorrect/v1.0.0".equals(namespace)) {
return getClass().getResource("/incorrect-1.0.0.xsd");
} else {
return getClass().getResource("/incorrect-1.1.0.xsd");
}
}
@Override
public Set<Class> getManagedClasses() {
return new HashSet<Class>(Collections.<Class>singletonList(String.class));
}
@Override
public Metadata parse(Element element, ParserContext context) {
MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
metadata.setProcessor(true);
metadata.setId("aries-1503");
metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
metadata.addArgument(new PassThroughMetadata() {
@Override
public Object getObject() {
return "ARIES-1503";
}
@Override
public String getId() {
return "aries-1503-arg";
}
@Override
public int getActivation() {
return 0;
}
@Override
public List<String> getDependsOn() {
return null;
}
}, null, 0);
metadata.setRuntimeClass(String.class);
return metadata;
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
return null;
}
}
| 9,146 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/handler/Aries1503bNamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm.handler;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Aries1503bNamespaceHandler implements NamespaceHandler {
@Override
public URL getSchemaLocation(String namespace) {
if ("http://aries.apache.org/blueprint/xmlns/blueprint-aries-1503/v1.1.0".equals(namespace)) {
return getClass().getResource("/blueprint-aries-1503-2.xsd");
}
if ("http://aries.apache.org/blueprint/xmlns/blueprint-aries-1503/v1.0.0".equals(namespace)) {
try {
Bundle extBundle = FrameworkUtil.getBundle(Aries1503aNamespaceHandler.class);
return Aries1503aNamespaceHandler.class.newInstance().getSchemaLocation(namespace);
} catch (Throwable t) {
return null;
}
}
return null;
}
@Override
public Set<Class> getManagedClasses() {
return new HashSet<Class>(Collections.<Class>singletonList(String.class));
}
@Override
public Metadata parse(Element element, ParserContext context) {
MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
metadata.setProcessor(true);
metadata.setId("aries-1503");
metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
metadata.addArgument(new PassThroughMetadata() {
@Override
public Object getObject() {
return "ARIES-1503";
}
@Override
public String getId() {
return "aries-1503-arg";
}
@Override
public int getActivation() {
return 0;
}
@Override
public List<String> getDependsOn() {
return null;
}
}, null, 0);
metadata.setRuntimeClass(String.class);
return metadata;
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
return null;
}
}
| 9,147 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/service/FooInterface.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm.service;
import java.util.Properties;
public interface FooInterface {
String getB();
Long getC();
Object getD();
Properties getProps();
}
| 9,148 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/service/Foo.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.itests.cm.service;
import java.util.Map;
import java.util.Properties;
public class Foo implements FooInterface {
public Foo() {
}
private int a;
private String b;
private Long c;
private Object d;
private Properties props;
public int getA() {
return a;
}
public void setA(int i) {
a = i;
}
@Override
public String getB() {
return b;
}
public void setB(String i) {
b = i;
}
public Long getC() {
return c;
}
public void setC(Long c) {
this.c = c;
}
public Object getD() {
return d;
}
public void setD(Object d) {
this.d = d;
}
public Properties getProps() {
return props;
}
public void setProps(Properties props) {
this.props = props;
}
public void update(Map<String, String> pMap) {
Properties properties = new Properties();
String value = pMap.get("a");
if (value != null) {
a = Integer.parseInt(value);
properties.put("a", a);
}
value = pMap.get("b");
if (value != null) {
b = value;
properties.put("b", b);
}
props = properties;
}
}
| 9,149 |
0 | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm | Create_ds/aries/blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/cm/service/FooFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.itests.cm.service;
public class FooFactory {
public FooInterface create(){
return new Foo();
}
}
| 9,150 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/SpringBeanProcessor.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.ComponentDefinitionRegistryProcessor;
import org.apache.aries.blueprint.ExtendedBeanMetadata;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.spring.BlueprintBeanFactory.SpringMetadata;
import org.osgi.framework.BundleContext;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
public class SpringBeanProcessor implements BeanProcessor, ComponentDefinitionRegistryProcessor {
private final BundleContext bundleContext;
private final ExtendedBlueprintContainer blueprintContainer;
private final SpringApplicationContext applicationContext;
boolean creatingProcessor;
public SpringBeanProcessor(
BundleContext bundleContext,
ExtendedBlueprintContainer blueprintContainer,
SpringApplicationContext applicationContext) {
this.bundleContext = bundleContext;
this.blueprintContainer = blueprintContainer;
this.applicationContext = applicationContext;
}
@Override
public void process(ComponentDefinitionRegistry componentDefinitionRegistry) {
applicationContext.refresh();
}
@Override
public Object beforeInit(Object o, String s, BeanCreator beanCreator, BeanMetadata beanMetadata) {
if (beanMetadata instanceof SpringMetadata || beanMetadata == null) {
return o;
}
if (o instanceof Aware) {
if (o instanceof BeanNameAware) {
((BeanNameAware) o).setBeanName(s);
}
if (o instanceof BeanClassLoaderAware) {
ClassLoader cl = bundleContext.getBundle().adapt(BundleWiring.class).getClassLoader();
((BeanClassLoaderAware) o).setBeanClassLoader(cl);
}
if (o instanceof BeanFactoryAware) {
((BeanFactoryAware) o).setBeanFactory(applicationContext.getBeanFactory());
}
}
return applicationContext.getBeanFactory().applyBeanPostProcessorsBeforeInitialization(o, s);
}
@Override
public Object afterInit(Object o, String s, BeanCreator beanCreator, BeanMetadata beanMetadata) {
return applicationContext.getBeanFactory().applyBeanPostProcessorsAfterInitialization(o, s);
}
@Override
public void beforeDestroy(Object o, String s) {
}
@Override
public void afterDestroy(Object o, String s) {
}
private <T> List<T> getProcessors(Class<T> type) {
List<T> processors = new ArrayList<T>();
if (!creatingProcessor) {
creatingProcessor = true;
for (BeanMetadata bean : blueprintContainer.getMetadata(BeanMetadata.class)) {
Class clazz = null;
if (bean instanceof ExtendedBeanMetadata) {
clazz = ((ExtendedBeanMetadata) bean).getRuntimeClass();
}
if (clazz == null && bean.getClassName() != null) {
try {
clazz = bundleContext.getBundle().loadClass(bean.getClassName());
} catch (ClassNotFoundException e) {
}
}
if (clazz == null) {
continue;
}
if (type.isAssignableFrom(clazz)) {
Object p = blueprintContainer.getComponentInstance(bean.getId());
processors.add(type.cast(p));
}
}
creatingProcessor = false;
}
return processors;
}
}
| 9,151 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/SpringApplicationContext.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.support.AbstractApplicationContext;
public class SpringApplicationContext extends AbstractApplicationContext {
private final ExtendedBlueprintContainer container;
private final DefaultListableBeanFactory beanFactory;
private final List<ClassLoader> parentClassLoaders = new ArrayList<ClassLoader>();
public SpringApplicationContext(ExtendedBlueprintContainer container) {
this.container = container;
parentClassLoaders.add(container.getClassLoader());
setClassLoader(new ClassLoader() {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
for (ClassLoader cl : parentClassLoaders) {
try {
return cl.loadClass(name);
} catch (ClassNotFoundException e) {
// Ignore
}
}
throw new ClassNotFoundException(name);
}
@Override
public URL getResource(String name) {
for (ClassLoader cl : parentClassLoaders) {
URL url = cl.getResource(name);
if (url != null) {
return url;
}
}
return null;
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
final Enumeration<URL>[] enums = (Enumeration<URL>[]) new Enumeration<?>[parentClassLoaders.size()];
for (int i = 0; i < enums.length; i++) {
enums[i] = parentClassLoaders.get(i).getResources(name);
}
return new Enumeration<URL>() {
private int index = 0;
@Override
public boolean hasMoreElements() {
return next();
}
@Override
public URL nextElement() {
if (!this.next()) {
throw new NoSuchElementException();
} else {
return enums[this.index].nextElement();
}
}
private boolean next() {
while(this.index < enums.length) {
if (enums[this.index] != null && enums[this.index].hasMoreElements()) {
return true;
}
++this.index;
}
return false;
}
};
}
});
this.beanFactory = new BlueprintBeanFactory(container, this);
prepareBeanFactory(beanFactory);
prepareRefresh();
}
public void process() {
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
}
@Override
protected void refreshBeanFactory() throws BeansException, IllegalStateException {
}
@Override
protected void closeBeanFactory() {
}
@Override
public DefaultListableBeanFactory getBeanFactory() throws IllegalStateException {
return beanFactory;
}
public void addSourceBundle(Bundle bundle) {
// This should always be not null, but we want to support unit testing
if (bundle != null) {
parentClassLoaders.add(bundle.adapt(BundleWiring.class).getClassLoader());
}
}
}
| 9,152 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/BeansNamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.WeakHashMap;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.xml.BeanDefinitionDocumentReader;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A spring namespace handler to handle spring bean elements.
*/
public class BeansNamespaceHandler implements org.springframework.beans.factory.xml.NamespaceHandler {
private WeakHashMap<ParserContext, BeanDefinitionReader> readers = new WeakHashMap<ParserContext, BeanDefinitionReader>();
@Override
public void init() {
}
@Override
public BeanDefinition parse(Element ele, ParserContext parserContext) {
BeanDefinitionHolder bdh = getReader(parserContext).parseElement(ele);
return bdh != null ? bdh.getBeanDefinition() : null;
}
@Override
public BeanDefinitionHolder decorate(Node source, BeanDefinitionHolder definition, ParserContext parserContext) {
return definition;
}
private BeanDefinitionReader getReader(ParserContext parserContext) {
BeanDefinitionReader reader = readers.get(parserContext);
if (reader == null) {
reader = new BeanDefinitionReader(parserContext.getReaderContext());
readers.put(parserContext, reader);
}
return reader;
}
/**
* Default implementation of the {@link BeanDefinitionDocumentReader} interface that
* reads bean definitions according to the "spring-beans" DTD and XSD format
* (Spring's default XML bean definition format).
*
* <p>The structure, elements, and attribute names of the required XML document
* are hard-coded in this class. (Of course a transform could be run if necessary
* to produce this format). {@code <beans>} does not need to be the root
* element of the XML document: this class will parse all bean definition elements
* in the XML file, regardless of the actual root element.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Rob Harrop
* @author Erik Wiersma
* @since 18.12.2003
*/
public static class BeanDefinitionReader {
public static final String BEAN_ELEMENT = BeanDefinitionParserDelegate.BEAN_ELEMENT;
public static final String NESTED_BEANS_ELEMENT = "beans";
public static final String ALIAS_ELEMENT = "alias";
public static final String NAME_ATTRIBUTE = "name";
public static final String ALIAS_ATTRIBUTE = "alias";
public static final String IMPORT_ELEMENT = "import";
public static final String RESOURCE_ATTRIBUTE = "resource";
public static final String PROFILE_ATTRIBUTE = "profile";
private final XmlReaderContext readerContext;
private BeanDefinitionParserDelegate delegate;
public BeanDefinitionReader(XmlReaderContext readerContext) {
this.readerContext = readerContext;
}
/**
* Return the descriptor for the XML resource that this parser works on.
*/
protected final XmlReaderContext getReaderContext() {
return this.readerContext;
}
/**
* Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor} to pull the
* source metadata from the supplied {@link Element}.
*/
protected Object extractSource(Element ele) {
return getReaderContext().extractSource(ele);
}
public BeanDefinitionHolder parseElement(Element ele) {
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), ele.getOwnerDocument().getDocumentElement(), parent);
BeanDefinitionHolder bdh = parseDefaultElement(ele, this.delegate);
this.delegate = parent;
return bdh;
}
/**
* Register each bean definition within the given root {@code <beans/>} element.
*/
protected void doRegisterBeanDefinitions(Element root) {
// Any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!getReaderContext().getReader().getEnvironment().acceptsProfiles(specifiedProfiles)) {
return;
}
}
}
parseBeanDefinitions(root, this.delegate);
this.delegate = parent;
}
protected BeanDefinitionParserDelegate createDelegate(
XmlReaderContext readerContext, Element root, BeanDefinitionParserDelegate parentDelegate) {
BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
delegate.initDefaults(root, parentDelegate);
return delegate;
}
/**
* Parse the elements at the root level in the document:
* "import", "alias", "bean".
* @param root the DOM root element of the document
*/
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
private BeanDefinitionHolder parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
BeanDefinitionHolder bdh = null;
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
bdh = processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
return bdh;
}
/**
* Parse an "import" element and load the bean definitions
* from the given resource into the bean factory.
*/
protected void importBeanDefinitionResource(Element ele) {
String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
if (!StringUtils.hasText(location)) {
getReaderContext().error("Resource location must not be empty", ele);
return;
}
// Resolve system properties: e.g. "${user.dir}"
location = getReaderContext().getReader().getEnvironment().resolveRequiredPlaceholders(location);
Set<Resource> actualResources = new LinkedHashSet<Resource>(4);
// Discover whether the location is an absolute or relative URI
boolean absoluteLocation = false;
try {
absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
}
catch (URISyntaxException ex) {
// cannot convert to an URI, considering the location relative
// unless it is the well-known Spring prefix "classpath*:"
}
// Absolute or relative?
if (absoluteLocation) {
try {
int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
// if (logger.isDebugEnabled()) {
// logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
// }
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
}
}
else {
// No URL -> considering resource location as relative to the current file.
try {
int importCount;
Resource relativeResource = getReaderContext().getResource().createRelative(location);
if (relativeResource.exists()) {
importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
actualResources.add(relativeResource);
}
else {
String baseLocation = getReaderContext().getResource().getURL().toString();
importCount = getReaderContext().getReader().loadBeanDefinitions(
StringUtils.applyRelativePath(baseLocation, location), actualResources);
}
// if (logger.isDebugEnabled()) {
// logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
// }
}
catch (IOException ex) {
getReaderContext().error("Failed to resolve current resource location", ele, ex);
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",
ele, ex);
}
}
Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}
/**
* Process the given alias element, registering the alias with the registry.
*/
protected void processAliasRegistration(Element ele) {
String name = ele.getAttribute(NAME_ATTRIBUTE);
String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
boolean valid = true;
if (!StringUtils.hasText(name)) {
getReaderContext().error("Name must not be empty", ele);
valid = false;
}
if (!StringUtils.hasText(alias)) {
getReaderContext().error("Alias must not be empty", ele);
valid = false;
}
if (valid) {
try {
getReaderContext().getRegistry().registerAlias(name, alias);
}
catch (Exception ex) {
getReaderContext().error("Failed to register alias '" + alias +
"' for bean with name '" + name + "'", ele, ex);
}
getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
}
}
/**
* Process the given bean element, parsing the bean definition
* and registering it with the registry.
*/
protected BeanDefinitionHolder processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
return bdHolder;
}
}
}
| 9,153 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/BlueprintNamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.Properties;
import java.util.Set;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.NamespaceHandler2;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.apache.aries.blueprint.mutable.MutablePassThroughMetadata;
import org.apache.aries.blueprint.mutable.MutableRefMetadata;
import org.apache.aries.blueprint.parser.Parser;
import org.apache.aries.blueprint.parser.ParserContextImpl;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.EmptyReaderEventListener;
import org.springframework.beans.factory.parsing.FailFastProblemReporter;
import org.springframework.beans.factory.parsing.NullSourceExtractor;
import org.springframework.beans.factory.parsing.ProblemReporter;
import org.springframework.beans.factory.parsing.ReaderEventListener;
import org.springframework.beans.factory.parsing.SourceExtractor;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.springframework.beans.factory.xml.NamespaceHandlerResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Blueprint NamespaceHandler wrapper for a spring NamespaceHandler
*/
public class BlueprintNamespaceHandler implements NamespaceHandler, NamespaceHandler2 {
public static final String SPRING_CONTEXT_ID = "." + org.springframework.beans.factory.xml.ParserContext.class.getName();
public static final String SPRING_BEAN_PROCESSOR_ID = "." + SpringBeanProcessor.class.getName();
public static final String SPRING_APPLICATION_CONTEXT_ID = "." + ApplicationContext.class.getName();
public static final String SPRING_BEAN_FACTORY_ID = "." + BeanFactory.class.getName();
private final Bundle bundle;
private final Properties schemas;
private final org.springframework.beans.factory.xml.NamespaceHandler springHandler;
public BlueprintNamespaceHandler(Bundle bundle, Properties schemas, org.springframework.beans.factory.xml.NamespaceHandler springHandler) {
this.bundle = bundle;
this.schemas = schemas;
this.springHandler = springHandler;
springHandler.init();
}
public org.springframework.beans.factory.xml.NamespaceHandler getSpringHandler() {
return springHandler;
}
@Override
public boolean usePsvi() {
return true;
}
@Override
public URL getSchemaLocation(String s) {
if (schemas.containsKey(s)) {
return bundle.getResource(schemas.getProperty(s));
}
return null;
}
@Override
public Set<Class> getManagedClasses() {
return Collections.<Class>singleton(BeanDefinition.class);
}
@Override
public Metadata parse(Element element, ParserContext parserContext) {
try {
// Get the spring context
org.springframework.beans.factory.xml.ParserContext springContext
= getOrCreateParserContext(parserContext);
// Parse spring bean
BeanDefinition bd = springHandler.parse(element, springContext);
for (String name : springContext.getRegistry().getBeanDefinitionNames()) {
if (springContext.getRegistry().getBeanDefinition(name) == bd) {
ComponentDefinitionRegistry registry = parserContext.getComponentDefinitionRegistry();
if (registry.containsComponentDefinition(name)) {
// Hack: we can't really make the difference between a top level bean
// and an inlined bean when using custom (eventually nested) namespaces.
// To work around the problem, the BlueprintBeanFactory will always register
// a BeanMetadata for each bean, but here, we unregister it and return it instead
// so that the caller is responsible for registering the metadata.
ComponentMetadata metadata = registry.getComponentDefinition(name);
registry.removeComponentDefinition(name);
return metadata;
}
}
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata componentMetadata, ParserContext parserContext) {
return componentMetadata;
}
private org.springframework.beans.factory.xml.ParserContext getOrCreateParserContext(ParserContext parserContext) {
ComponentDefinitionRegistry registry = parserContext.getComponentDefinitionRegistry();
ExtendedBlueprintContainer container = getBlueprintContainer(parserContext);
// Create spring application context
SpringApplicationContext applicationContext = getPassThrough(parserContext,
SPRING_APPLICATION_CONTEXT_ID, SpringApplicationContext.class);
if (applicationContext == null) {
applicationContext = new SpringApplicationContext(container);
registry.registerComponentDefinition(createPassThrough(parserContext,
SPRING_APPLICATION_CONTEXT_ID, applicationContext, "destroy"
));
}
// Create registry
DefaultListableBeanFactory beanFactory = getPassThrough(parserContext,
SPRING_BEAN_FACTORY_ID, DefaultListableBeanFactory.class);
if (beanFactory == null) {
beanFactory = applicationContext.getBeanFactory();
registry.registerComponentDefinition(createPassThrough(parserContext,
SPRING_BEAN_FACTORY_ID, beanFactory
));
}
// Create spring parser context
org.springframework.beans.factory.xml.ParserContext springParserContext
= getPassThrough(parserContext, SPRING_CONTEXT_ID, org.springframework.beans.factory.xml.ParserContext.class);
if (springParserContext == null) {
// Create spring context
springParserContext = createSpringParserContext(parserContext, beanFactory);
registry.registerComponentDefinition(createPassThrough(parserContext,
SPRING_CONTEXT_ID, springParserContext
));
}
// Create processor
if (!parserContext.getComponentDefinitionRegistry().containsComponentDefinition(SPRING_BEAN_PROCESSOR_ID)) {
MutableBeanMetadata bm = parserContext.createMetadata(MutableBeanMetadata.class);
bm.setId(SPRING_BEAN_PROCESSOR_ID);
bm.setProcessor(true);
bm.setScope(BeanMetadata.SCOPE_SINGLETON);
bm.setRuntimeClass(SpringBeanProcessor.class);
bm.setActivation(BeanMetadata.ACTIVATION_EAGER);
bm.addArgument(createRef(parserContext, "blueprintBundleContext"), null, 0);
bm.addArgument(createRef(parserContext, "blueprintContainer"), null, 0);
bm.addArgument(createRef(parserContext, SPRING_APPLICATION_CONTEXT_ID), null, 0);
registry.registerComponentDefinition(bm);
}
// Add the namespace handlers' bundle to the application context classloader
for (URI uri : parserContext.getNamespaces()) {
NamespaceHandler ns = parserContext.getNamespaceHandler(uri);
if (ns instanceof BlueprintNamespaceHandler) {
applicationContext.addSourceBundle(((BlueprintNamespaceHandler) ns).bundle);
}
}
return springParserContext;
}
private ComponentMetadata createPassThrough(ParserContext parserContext, String id, Object o) {
MutablePassThroughMetadata pt = parserContext.createMetadata(MutablePassThroughMetadata.class);
pt.setId(id);
pt.setObject(o);
return pt;
}
private ComponentMetadata createPassThrough(ParserContext parserContext, String id, Object o, String destroy) {
MutablePassThroughMetadata pt = parserContext.createMetadata(MutablePassThroughMetadata.class);
pt.setId(id + ".factory");
pt.setObject(new Holder(o));
MutableBeanMetadata b = parserContext.createMetadata(MutableBeanMetadata.class);
b.setId(id);
b.setFactoryComponent(pt);
b.setFactoryMethod("getObject");
b.setDestroyMethod(destroy);
return b;
}
public static class Holder {
private final Object object;
public Holder(Object object) {
this.object = object;
}
public Object getObject() {
return object;
}
}
private Metadata createRef(ParserContext parserContext, String id) {
MutableRefMetadata ref = parserContext.createMetadata(MutableRefMetadata.class);
ref.setComponentId(id);
return ref;
}
private ExtendedBlueprintContainer getBlueprintContainer(ParserContext parserContext) {
ExtendedBlueprintContainer container = getPassThrough(parserContext, "blueprintContainer", ExtendedBlueprintContainer.class);
if (container == null) {
throw new IllegalStateException();
}
return container;
}
@SuppressWarnings("unchecked")
private <T> T getPassThrough(ParserContext parserContext, String name, Class<T> clazz) {
Metadata metadata = parserContext.getComponentDefinitionRegistry().getComponentDefinition(name);
if (metadata instanceof BeanMetadata) {
BeanMetadata bm = (BeanMetadata) metadata;
if (bm.getFactoryComponent() instanceof PassThroughMetadata
&& "getObject".equals(bm.getFactoryMethod())) {
metadata = bm.getFactoryComponent();
}
}
if (metadata instanceof PassThroughMetadata) {
Object o = ((PassThroughMetadata) metadata).getObject();
if (o instanceof Holder) {
o = ((Holder) o).getObject();
}
return (T) o;
} else {
return null;
}
}
private org.springframework.beans.factory.xml.ParserContext createSpringParserContext(final ParserContext parserContext, DefaultListableBeanFactory registry) {
try {
SpringVersionBridgeXmlBeanDefinitionReader xbdr = new SpringVersionBridgeXmlBeanDefinitionReader(registry);
Resource resource = new UrlResource(parserContext.getSourceNode().getOwnerDocument().getDocumentURI());
ProblemReporter problemReporter = new FailFastProblemReporter();
ReaderEventListener listener = new EmptyReaderEventListener();
SourceExtractor extractor = new NullSourceExtractor();
NamespaceHandlerResolver resolver = new SpringNamespaceHandlerResolver(parserContext);
xbdr.setProblemReporter(problemReporter);
xbdr.setEventListener(listener);
xbdr.setSourceExtractor(extractor);
xbdr.setNamespaceHandlerResolver(resolver);
xbdr.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws IOException {
for (URI ns : parserContext.getNamespaces()) {
NamespaceHandler nh = parserContext.getNamespaceHandler(ns);
URL url = null;
if (publicId != null) {
url = nh.getSchemaLocation(publicId);
}
if (url == null && systemId != null) {
url = nh.getSchemaLocation(systemId);
}
if (url != null) {
InputSource is = new InputSource();
is.setPublicId(publicId);
is.setSystemId(systemId);
is.setByteStream(url.openStream());
return is;
}
}
return null;
}
});
XmlReaderContext xmlReaderContext = xbdr.createReaderContext(resource);
BeanDefinitionParserDelegate bdpd = new BeanDefinitionParserDelegate(xmlReaderContext);
return new org.springframework.beans.factory.xml.ParserContext(xmlReaderContext, bdpd);
} catch (Exception e) {
throw new RuntimeException("Error creating spring parser context", e);
}
}
/**
* Some methods are protected in Spring 3.x, hence overridden methods in this class to make them available.
*/
private class SpringVersionBridgeXmlBeanDefinitionReader extends XmlBeanDefinitionReader {
public SpringVersionBridgeXmlBeanDefinitionReader(final BeanDefinitionRegistry registry) {
super(registry);
}
@Override
public XmlReaderContext createReaderContext(final Resource resource) {
return super.createReaderContext(resource);
}
}
}
| 9,154 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/Activator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.blueprint.spring;
import java.net.URL;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.felix.utils.extender.AbstractExtender;
import org.apache.felix.utils.extender.Extension;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Spring namespace extender.
* This OSGi extender is responsible for registering spring namespaces for blueprint.
*
* @see SpringExtension
*/
public class Activator extends AbstractExtender {
private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class);
ServiceRegistration<NamespaceHandler> registration;
@Override
protected Extension doCreateExtension(Bundle bundle) throws Exception {
URL handlers = bundle.getResource(SpringExtension.SPRING_HANDLERS);
if (handlers != null) {
return new SpringExtension(bundle);
}
return null;
}
@Override
protected void debug(Bundle bundle, String msg) {
LOGGER.debug(msg + ": " + bundle.getSymbolicName() + "/" + bundle.getVersion());
}
@Override
protected void warn(Bundle bundle, String msg, Throwable t) {
LOGGER.warn(msg + ": " + bundle.getSymbolicName() + "/" + bundle.getVersion(), t);
}
@Override
protected void error(String msg, Throwable t) {
LOGGER.error(msg, t);
}
}
| 9,155 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/SpringNamespaceHandlerResolver.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring;
import java.net.URI;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.springframework.beans.factory.xml.NamespaceHandlerResolver;
public class SpringNamespaceHandlerResolver implements NamespaceHandlerResolver {
private final ParserContext parserContext;
public SpringNamespaceHandlerResolver(ParserContext parserContext) {
this.parserContext = parserContext;
}
@Override
public org.springframework.beans.factory.xml.NamespaceHandler resolve(String namespaceUri) {
try {
NamespaceHandler handler = parserContext.getNamespaceHandler(URI.create(namespaceUri));
if (handler instanceof BlueprintNamespaceHandler) {
return ((BlueprintNamespaceHandler) handler).getSpringHandler();
}
else if (handler != null) {
return new SpringNamespaceHandler(parserContext, handler);
}
} catch (ComponentDefinitionException e) {
// Ignore
}
return null;
}
}
| 9,156 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/BlueprintBeanFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.NoSuchComponentException;
import org.osgi.service.blueprint.container.ReifiedType;
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.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.osgi.service.blueprint.reflect.ValueMetadata;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
public class BlueprintBeanFactory extends DefaultListableBeanFactory implements ResourceLoader {
private final ExtendedBlueprintContainer container;
private final ResourceLoader resourceLoader;
public BlueprintBeanFactory(ExtendedBlueprintContainer container, ResourceLoader resourceLoader) {
super(new WrapperBeanFactory(container));
this.container = container;
this.resourceLoader = resourceLoader;
}
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
return super.getBean(requiredType);
}
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
ComponentDefinitionRegistry registry = container.getComponentDefinitionRegistry();
ComponentMetadata metadata = registry.getComponentDefinition(beanName);
if (metadata != null && !(metadata instanceof SpringMetadata)) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"': There is already bound.");
}
super.registerBeanDefinition(beanName, beanDefinition);
if (!beanDefinition.isAbstract()) {
registry.registerComponentDefinition(new SpringMetadata(beanName));
}
}
@Override
public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
super.removeBeanDefinition(beanName);
}
@Override
public Resource getResource(String location) {
return resourceLoader.getResource(location);
}
@Override
public ClassLoader getClassLoader() {
return resourceLoader.getClassLoader();
}
public class SpringMetadata implements BeanMetadata {
private final String beanName;
public SpringMetadata(String beanName) {
this.beanName = beanName;
}
public BeanDefinition getDefinition() {
return getBeanDefinition(beanName);
}
@Override
public String getId() {
return beanName;
}
@Override
public String getScope() {
return getDefinition().isSingleton() ? SCOPE_SINGLETON : SCOPE_PROTOTYPE;
}
@Override
public int getActivation() {
return getDefinition().isLazyInit() ? ACTIVATION_LAZY : ACTIVATION_EAGER;
}
@Override
public List<String> getDependsOn() {
String[] dependson = getDefinition().getDependsOn();
return dependson != null ? Arrays.asList(dependson) : Collections.<String>emptyList();
}
@Override
public String getClassName() {
return null;
}
@Override
public String getInitMethod() {
return null;
}
@Override
public String getDestroyMethod() {
return null;
}
@Override
public List<BeanArgument> getArguments() {
return Collections.<BeanArgument>singletonList(new BeanArgument() {
@Override
public Metadata getValue() {
return new ValueMetadata() {
@Override
public String getStringValue() {
return beanName;
}
@Override
public String getType() {
return null;
}
};
}
@Override
public String getValueType() {
return null;
}
@Override
public int getIndex() {
return -1;
}
});
}
@Override
public List<BeanProperty> getProperties() {
return Collections.emptyList();
}
@Override
public String getFactoryMethod() {
return "getBean";
}
@Override
public Target getFactoryComponent() {
return new RefMetadata() {
@Override
public String getComponentId() {
return BlueprintNamespaceHandler.SPRING_BEAN_FACTORY_ID;
}
};
}
}
static class WrapperBeanFactory implements BeanFactory {
private final ExtendedBlueprintContainer container;
public WrapperBeanFactory(ExtendedBlueprintContainer container) {
this.container = container;
}
@Override
public Object getBean(String name) throws BeansException {
try {
return container.getComponentInstance(name);
} catch (NoSuchComponentException e) {
throw new NoSuchBeanDefinitionException(name);
}
}
@SuppressWarnings("unchecked")
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
Object bean = getBean(name);
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
bean = container.getConverter().convert(bean, new ReifiedType(requiredType));
} catch (Exception ex) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
throw new UnsupportedOperationException();
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
throw new UnsupportedOperationException();
}
@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
throw new UnsupportedOperationException();
}
@Override
public boolean containsBean(String name) {
return container.getComponentIds().contains(name);
}
@Override
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
throw new UnsupportedOperationException();
}
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
throw new UnsupportedOperationException();
}
@Override
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
throw new UnsupportedOperationException();
}
@Override
public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException {
throw new UnsupportedOperationException();
}
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
throw new UnsupportedOperationException();
}
@Override
public String[] getAliases(String name) {
throw new UnsupportedOperationException();
}
}
}
| 9,157 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/SpringNamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class SpringNamespaceHandler implements org.springframework.beans.factory.xml.NamespaceHandler {
private final NamespaceHandler handler;
private final ParserContext parserContext;
public SpringNamespaceHandler(ParserContext parserContext, NamespaceHandler handler) {
this.parserContext = parserContext;
this.handler = handler;
}
@Override
public void init() {
}
@Override
public BeanDefinition parse(Element element, org.springframework.beans.factory.xml.ParserContext parserContext) {
Metadata metadata = handler.parse(element, this.parserContext);
if (metadata instanceof ComponentMetadata) {
this.parserContext.getComponentDefinitionRegistry().registerComponentDefinition(
(ComponentMetadata) metadata);
}
return null;
}
@Override
public BeanDefinitionHolder decorate(Node source, BeanDefinitionHolder definition, org.springframework.beans.factory.xml.ParserContext parserContext) {
return definition;
}
}
| 9,158 |
0 | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-spring/src/main/java/org/apache/aries/blueprint/spring/SpringExtension.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.felix.utils.extender.Extension;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
/**
* Spring extension.
* Each spring namespace is wrapped in a blueprint namespace.
*
* @see BlueprintNamespaceHandler
*/
public class SpringExtension implements Extension {
public static final String SPRING_HANDLERS = "META-INF/spring.handlers";
public static final String SPRING_SCHEMAS = "META-INF/spring.schemas";
private final Bundle bundle;
private final List<ServiceRegistration<NamespaceHandler>> registrations;
public SpringExtension(Bundle bundle) {
this.bundle = bundle;
this.registrations = new ArrayList<ServiceRegistration<NamespaceHandler>>();
}
@Override
public void start() throws Exception {
Map<String, NamespaceHandler> handlers = new HashMap<String, NamespaceHandler>();
Properties props = loadSpringHandlers();
Properties schemas = loadSpringSchemas();
for (String key : props.stringPropertyNames()) {
String clazzName = props.getProperty(key);
org.springframework.beans.factory.xml.NamespaceHandler springHandler
= (org.springframework.beans.factory.xml.NamespaceHandler) bundle.loadClass(clazzName).newInstance();
NamespaceHandler wrapper = new BlueprintNamespaceHandler(bundle, schemas, springHandler);
handlers.put(key, wrapper);
}
if (bundle == FrameworkUtil.getBundle(BeanFactory.class)) {
org.springframework.beans.factory.xml.NamespaceHandler springHandler
= new BeansNamespaceHandler();
NamespaceHandler wrapper = new BlueprintNamespaceHandler(bundle, schemas, springHandler);
handlers.put(BeanDefinitionParserDelegate.BEANS_NAMESPACE_URI, wrapper);
}
for (Map.Entry<String, NamespaceHandler> entry : handlers.entrySet()) {
Hashtable<String, String> svcProps = new Hashtable<String, String>();
svcProps.put("osgi.service.blueprint.namespace", entry.getKey());
ServiceRegistration<NamespaceHandler> reg =
bundle.getBundleContext().registerService(NamespaceHandler.class, entry.getValue(),
svcProps);
registrations.add(reg);
}
}
private Properties loadSpringHandlers() throws IOException {
Properties props = new Properties();
URL url = bundle.getResource(SPRING_HANDLERS);
InputStream is = url.openStream();
try {
props.load(is);
} finally {
is.close();
}
return props;
}
private Properties loadSpringSchemas() throws IOException {
Properties props = new Properties();
URL url = bundle.getResource(SPRING_SCHEMAS);
InputStream is = url.openStream();
try {
props.load(is);
} finally {
is.close();
}
return props;
}
@Override
public void destroy() throws Exception {
for (ServiceRegistration<NamespaceHandler> reg : registrations) {
reg.unregister();
}
}
}
| 9,159 |
0 | Create_ds/aries/blueprint/blueprint-spring-extender/src/test/java/org/apache/aries/blueprint/spring | Create_ds/aries/blueprint/blueprint-spring-extender/src/test/java/org/apache/aries/blueprint/spring/extender/SpringXsdVersionResolverTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.extender;
import static org.hamcrest.CoreMatchers.equalTo;
import org.junit.Assert;
import org.junit.Test;
/**
* Resolves spring xsd version.
*
*/
public class SpringXsdVersionResolverTest {
@Test
public void testResolve() {
final String xsdVersion = SpringXsdVersionResolver.resolve();
Assert.assertThat(xsdVersion, equalTo("4.2"));
}
}
| 9,160 |
0 | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring/extender/SpringOsgiCompendiumNamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.extender;
import java.net.URI;
import java.net.URL;
import java.util.Set;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class SpringOsgiCompendiumNamespaceHandler implements NamespaceHandler {
public static final String CM_NAMESPACE = "http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.3.0";
@Override
public URL getSchemaLocation(String namespace) {
if (namespace.startsWith("http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium")) {
String sub = namespace.substring("http://www.springframework.org/schema/osgi-compendium/".length());
if ("spring-osgi-compendium.xsd".equals(sub)) {
sub = "spring-osgi-compendium-1.2.xsd";
}
return getClass().getResource(sub);
}
return null;
}
@Override
public Set<Class> getManagedClasses() {
return null;
}
@Override
public Metadata parse(Element element, ParserContext context) {
fixDom(element, CM_NAMESPACE);
NamespaceHandler handler = context.getNamespaceHandler(URI.create(CM_NAMESPACE));
return handler.parse(element, context);
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
return component;
}
private static void fixDom(Node node, String namespace) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (!namespace.equals(node.getNamespaceURI())) {
node.getOwnerDocument().renameNode(node, namespace, node.getLocalName());
}
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
fixDom(children.item(i), namespace);
}
}
}
}
| 9,161 |
0 | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring/extender/SpringXsdVersionResolver.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.extender;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.SpringVersion;
/**
* Resolves spring xsd version.
*
*/
public class SpringXsdVersionResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringXsdVersionResolver.class);
private static final String DEFAULT_VERSION = "4.3"; // latest version
private static final Pattern PATTERN = Pattern.compile("^\\d*\\.\\d*");
/**
* It will call a Spring method that returns the full version. Expects
* format 4.2.2.RELEASE and 4.2 will be returned.
*
* @return String containing the xsd version.
*/
public static String resolve() {
final String fullVersion = SpringVersion.getVersion();
if (fullVersion != null) {
final Matcher matcher = PATTERN.matcher(fullVersion);
if (matcher.find()) {
return matcher.group(0);
}
}
LOGGER.trace("Could not resolve xsd version from Spring's version {}", fullVersion);
return DEFAULT_VERSION;
}
}
| 9,162 |
0 | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring/extender/SpringOsgiNamespaceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.extender;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.mutable.MutableRefMetadata;
import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
import org.apache.aries.blueprint.mutable.MutableValueMetadata;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
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;
public class SpringOsgiNamespaceHandler implements NamespaceHandler {
public static final String BLUEPRINT_NAMESPACE = "http://www.osgi.org/xmlns/blueprint/v1.0.0";
public static final String SPRING_NAMESPACE = "http://www.springframework.org/schema/beans";
public static final String BEAN_ELEMENT = "bean";
public static final String BEAN_NAME_ELEMENT = "bean-name";
public static final String FILTER_ATTRIBUTE = "filter";
public static final String INTERFACE_ATTRIBUTE = "interface";
public static final String TIMEOUT_ATTRIBUTE = "timeout";
public static final String DEPENDS_ON_ATTRIBUTE = "depends-on";
public static final String CARDINALITY_ATTRIBUTE = "cardinality";
public static final String LISTENER_ELEMENT = "listener";
public static final String REF_ATTRIBUTE = "ref";
public static final String BIND_METHOD_ATTRIBUTE = "bind-method";
public static final String UNBIND_METHOD_ATTRIBUTE = "unbind-method";
public static final String ID_ATTRIBUTE = "id";
public static final String CARDINALITY_0_1 = "0..1";
public static final String VALUE_ATTRIBUTE = "value";
public static final String VALUE_REF_ATTRIBUTE = "value-ref";
public static final String KEY_ATTRIBUTE = "key";
public static final String KEY_REF_ATTRIBUTE = "key-ref";
public static final String ENTRY_ELEMENT = "entry";
public static final String SERVICE_PROPERTIES_ELEMENT = "service-properties";
public static final String REGISTRATION_LISTENER_ELEMENT = "registration-listener";
public static final String INTERFACES_ELEMENT = "interfaces";
public static final String VALUE_ELEMENT = "value";
public static final String AUTO_EXPORT_ATTRIBUTE = "auto-export";
public static final String AUTO_EXPORT_INTERFACES = "interfaces";
public static final String AUTO_EXPORT_CLASS_HIERARCHY = "class-hierarchy";
public static final String AUTO_EXPORT_ALL_CLASSES = "all-classes";
public static final String RANKING_ATTRIBUTE = "ranking";
public static final String REFERENCE_ELEMENT = "reference";
public static final String SERVICE_ELEMENT = "service";
public static final String BUNDLE_ELEMENT = "bundle";
public static final String SET_ELEMENT = "set";
public static final String LIST_ELEMENT = "list";
public static final int DEFAULT_TIMEOUT = 300000;
public static final String REGISTRATION_METHOD_ATTRIBUTE = "registration-method";
public static final String UNREGISTRATION_METHOD_ATTRIBUTE = "unregistration-method";
private int idCounter;
@Override
public URL getSchemaLocation(String namespace) {
if (namespace.startsWith("http://www.springframework.org/schema/osgi/spring-osgi")) {
String sub = namespace.substring("http://www.springframework.org/schema/osgi/".length());
if ("spring-osgi.xsd".equals(sub)) {
sub = "spring-osgi-1.2.xsd";
}
return getClass().getResource(sub);
}
return null;
}
@Override
public Set<Class> getManagedClasses() {
return null;
}
@Override
public Metadata parse(Element element, ParserContext context) {
if (REFERENCE_ELEMENT.equals(element.getLocalName())) {
return parseReference(element, context);
}
else if (SERVICE_ELEMENT.equals(element.getLocalName())) {
return parseService(element, context);
}
else if (BUNDLE_ELEMENT.equals(element.getLocalName())) {
return parseBundle(element, context);
}
else if (SET_ELEMENT.equals(element.getLocalName())) {
return parseSet(element, context);
}
else if (LIST_ELEMENT.equals(element.getLocalName())) {
return parseList(element, context);
}
else {
throw new UnsupportedOperationException();
}
}
private Metadata parseBundle(Element element, ParserContext context) {
throw new UnsupportedOperationException();
}
private Metadata parseList(Element element, ParserContext context) {
// TODO: support list
throw new UnsupportedOperationException();
}
private Metadata parseSet(Element element, ParserContext context) {
// TODO: support set
throw new UnsupportedOperationException();
}
private Metadata parseService(Element element, ParserContext context) {
MutableServiceMetadata metadata = context.createMetadata(MutableServiceMetadata.class);
// Parse attributes
if (element.hasAttribute(ID_ATTRIBUTE)) {
metadata.setId(element.getAttribute(ID_ATTRIBUTE));
} else {
metadata.setId(generateId(context));
}
if (nonEmpty(element.getAttribute(REF_ATTRIBUTE)) != null) {
MutableRefMetadata ref = context.createMetadata(MutableRefMetadata.class);
ref.setComponentId(element.getAttribute(REF_ATTRIBUTE));
metadata.setServiceComponent(ref);
}
metadata.setRanking(nonEmpty(element.getAttribute(RANKING_ATTRIBUTE)) != null
? Integer.parseInt(element.getAttribute(RANKING_ATTRIBUTE))
: 0);
String itf = nonEmpty(element.getAttribute(INTERFACE_ATTRIBUTE));
if (itf != null) {
metadata.addInterface(itf);
}
String[] dependsOn = StringUtils.tokenizeToStringArray(nonEmpty(element.getAttribute(DEPENDS_ON_ATTRIBUTE)), ",; ");
metadata.setDependsOn(dependsOn != null ? Arrays.asList(dependsOn) : null);
String autoExp = nonEmpty(element.getAttribute(AUTO_EXPORT_ATTRIBUTE));
if (AUTO_EXPORT_INTERFACES.equals(autoExp)) {
metadata.setAutoExport(ServiceMetadata.AUTO_EXPORT_INTERFACES);
} else if (AUTO_EXPORT_CLASS_HIERARCHY.equals(autoExp)) {
metadata.setAutoExport(ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY);
} else if (AUTO_EXPORT_ALL_CLASSES.equals(autoExp)) {
metadata.setAutoExport(ServiceMetadata.AUTO_EXPORT_ALL_CLASSES);
} else {
metadata.setAutoExport(ServiceMetadata.AUTO_EXPORT_DISABLED);
}
// TODO: @context-class-loader
// Parse child elements
for (Element child : getChildren(element)) {
if (element.getNamespaceURI().equals(child.getNamespaceURI())) {
if (INTERFACES_ELEMENT.equals(child.getLocalName())) {
List<String> itfs = parseInterfaces(child);
for (String intf : itfs) {
metadata.addInterface(intf);
}
}
else if (REGISTRATION_LISTENER_ELEMENT.equals(child.getLocalName())) {
String regMethod = nonEmpty(child.getAttribute(REGISTRATION_METHOD_ATTRIBUTE));
String unregMethod = nonEmpty(child.getAttribute(UNREGISTRATION_METHOD_ATTRIBUTE));
String refStr = nonEmpty(child.getAttribute(REF_ATTRIBUTE));
Target listenerComponent = null;
if (refStr != null) {
MutableRefMetadata ref = context.createMetadata(MutableRefMetadata.class);
ref.setComponentId(refStr);
listenerComponent = ref;
}
for (Element cchild : getChildren(child)) {
if (listenerComponent != null) {
throw new IllegalArgumentException("Only one of @ref attribute or inlined bean definition element is allowed");
}
listenerComponent = parseInlinedTarget(context, metadata, cchild);
}
if (listenerComponent == null) {
throw new IllegalArgumentException("Missing @ref attribute or inlined bean definition element");
}
metadata.addRegistrationListener(listenerComponent, regMethod, unregMethod);
}
else if (SERVICE_PROPERTIES_ELEMENT.equals(child.getLocalName())) {
// TODO: @key-type
for (Element e : getChildren(child)) {
if (ENTRY_ELEMENT.equals(e.getLocalName())) {
NonNullMetadata key;
Metadata val;
boolean hasKeyAttribute = e.hasAttribute(KEY_ATTRIBUTE);
boolean hasKeyRefAttribute = e.hasAttribute(KEY_REF_ATTRIBUTE);
if (hasKeyRefAttribute && !hasKeyAttribute) {
MutableRefMetadata r = context.createMetadata(MutableRefMetadata.class);
r.setComponentId(e.getAttribute(KEY_REF_ATTRIBUTE));
key = r;
} else if (hasKeyAttribute && !hasKeyRefAttribute) {
MutableValueMetadata v = context.createMetadata(MutableValueMetadata.class);
v.setStringValue(e.getAttribute(KEY_ATTRIBUTE));
key = v;
} else {
throw new IllegalStateException("Either key or key-ref must be specified");
}
// TODO: support key
boolean hasValAttribute = e.hasAttribute(VALUE_ATTRIBUTE);
boolean hasValRefAttribute = e.hasAttribute(VALUE_REF_ATTRIBUTE);
if (hasValRefAttribute && !hasValAttribute) {
MutableRefMetadata r = context.createMetadata(MutableRefMetadata.class);
r.setComponentId(e.getAttribute(VALUE_REF_ATTRIBUTE));
val = r;
} else if (hasValAttribute && !hasValRefAttribute) {
MutableValueMetadata v = context.createMetadata(MutableValueMetadata.class);
v.setStringValue(e.getAttribute(VALUE_ATTRIBUTE));
val = v;
} else {
throw new IllegalStateException("Either val or val-ref must be specified");
}
// TODO: support children elements ?
metadata.addServiceProperty(key, val);
}
}
}
}
else if (BLUEPRINT_NAMESPACE.equals(child.getNamespaceURI())
&& BEAN_ELEMENT.equals(child.getLocalName())) {
if (metadata.getServiceComponent() != null) {
throw new IllegalArgumentException("Only one of @ref attribute and bean element is allowed");
}
Target bean = context.parseElement(BeanMetadata.class, metadata, child);
metadata.setServiceComponent(bean);
}
else {
if (metadata.getServiceComponent() != null) {
throw new IllegalArgumentException("Only one of @ref attribute or inlined bean definition element is allowed");
}
NamespaceHandler handler = context.getNamespaceHandler(URI.create(child.getNamespaceURI()));
if (handler == null) {
throw new IllegalStateException("No NamespaceHandler found for " + child.getNamespaceURI());
}
Metadata md = handler.parse(child, context);
if (!(md instanceof Target)) {
throw new IllegalStateException("NamespaceHandler did not return a Target instance but " + md);
}
metadata.setServiceComponent((Target) md);
}
}
return metadata;
}
private Metadata parseReference(Element element, ParserContext context) {
MutableReferenceMetadata metadata = context.createMetadata(MutableReferenceMetadata.class);
// Parse attributes
if (element.hasAttribute(ID_ATTRIBUTE)) {
metadata.setId(element.getAttribute(ID_ATTRIBUTE));
} else {
metadata.setId(generateId(context));
}
metadata.setAvailability(CARDINALITY_0_1.equals(element.getAttribute(CARDINALITY_ATTRIBUTE))
? ReferenceMetadata.AVAILABILITY_OPTIONAL
: ReferenceMetadata.AVAILABILITY_MANDATORY);
metadata.setTimeout(getLong(element.getAttribute(TIMEOUT_ATTRIBUTE), DEFAULT_TIMEOUT));
metadata.setInterface(element.getAttribute(INTERFACE_ATTRIBUTE));
metadata.setFilter(element.getAttribute(FILTER_ATTRIBUTE));
String[] dependsOn = StringUtils.tokenizeToStringArray(element.getAttribute(DEPENDS_ON_ATTRIBUTE), ",; ");
metadata.setDependsOn(dependsOn != null ? Arrays.asList(dependsOn) : null);
metadata.setComponentName(element.getAttribute(BEAN_NAME_ELEMENT));
// TODO: @context-class-loader
// Parse child elements
for (Element child : getChildren(element)) {
if (element.getNamespaceURI().equals(child.getNamespaceURI())) {
if (INTERFACES_ELEMENT.equals(child.getLocalName())) {
List<String> itfs = parseInterfaces(child);
metadata.setExtraInterfaces(itfs);
}
else if (LISTENER_ELEMENT.equals(child.getLocalName())) {
String bindMethod = nonEmpty(child.getAttribute(BIND_METHOD_ATTRIBUTE));
String unbindMethod = nonEmpty(child.getAttribute(UNBIND_METHOD_ATTRIBUTE));
String refStr = nonEmpty(child.getAttribute(REF_ATTRIBUTE));
Target listenerComponent = null;
if (refStr != null) {
MutableRefMetadata ref = context.createMetadata(MutableRefMetadata.class);
ref.setComponentId(refStr);
listenerComponent = ref;
}
for (Element cchild : getChildren(child)) {
if (listenerComponent != null) {
throw new IllegalArgumentException("Only one of @ref attribute or inlined bean definition element is allowed");
}
listenerComponent = parseInlinedTarget(context, metadata, cchild);
}
if (listenerComponent == null) {
throw new IllegalArgumentException("Missing @ref attribute or inlined bean definition element");
}
metadata.addServiceListener(listenerComponent, bindMethod, unbindMethod);
}
}
else {
throw new UnsupportedOperationException("Custom namespaces not supported");
}
}
return metadata;
}
private Target parseInlinedTarget(ParserContext context, ComponentMetadata metadata, Element element) {
Target listenerComponent;
if (BLUEPRINT_NAMESPACE.equals(element.getNamespaceURI())
&& BEAN_ELEMENT.equals(element.getLocalName())) {
listenerComponent = context.parseElement(BeanMetadata.class, metadata, element);
}
else {
NamespaceHandler handler = context.getNamespaceHandler(URI.create(element.getNamespaceURI()));
if (handler == null) {
throw new IllegalStateException("No NamespaceHandler found for " + element.getNamespaceURI());
}
Metadata md = handler.parse(element, context);
if (!(md instanceof Target)) {
throw new IllegalStateException("NamespaceHandler did not return a Target instance but " + md);
}
listenerComponent = (Target) md;
}
return listenerComponent;
}
private List<String> parseInterfaces(Element element) {
List<String> extra = new ArrayList<String>();
for (Element e : getChildren(element)) {
if (VALUE_ELEMENT.equals(e.getLocalName())) {
extra.add(getTextValue(e));
} else {
// The schema support all kind of children for a list type
// The type for the spring property is converted to a Class[] array
// TODO: support other elements ?
throw new UnsupportedOperationException("Unsupported child: " + element.getLocalName());
}
}
return extra;
}
private String nonEmpty(String ref) {
return ref != null && ref.isEmpty() ? null : ref;
}
private String generateId(ParserContext context) {
String id;
do {
id = ".spring-osgi-" + ++idCounter;
} while (context.getComponentDefinitionRegistry().containsComponentDefinition(id));
return id;
}
@Override
public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
return component;
}
private List<Element> getChildren(Element element) {
List<Element> children = new ArrayList<Element>();
for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child instanceof Element) {
children.add((Element) child);
}
}
return children;
}
private long getLong(String str, long def) {
if (str == null || str.isEmpty()) {
return def;
} else {
return Long.parseLong(str);
}
}
public static String getTextValue(Element valueEle) {
Assert.notNull(valueEle, "Element must not be null");
StringBuilder sb = new StringBuilder();
NodeList nl = valueEle.getChildNodes();
for(int i = 0, l = nl.getLength(); i < l; ++i) {
Node item = nl.item(i);
if(item instanceof CharacterData && !(item instanceof Comment) || item instanceof EntityReference) {
sb.append(item.getNodeValue());
}
}
return sb.toString();
}
}
| 9,163 |
0 | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring/extender/Activator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.blueprint.spring.extender;
import java.util.Hashtable;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.services.BlueprintExtenderService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator,
ServiceTrackerCustomizer<BlueprintExtenderService, SpringOsgiExtender> {
private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class);
BundleContext bundleContext;
ServiceTracker<BlueprintExtenderService, SpringOsgiExtender> tracker;
ServiceRegistration<NamespaceHandler> osgiNamespaceRegistration;
ServiceRegistration<NamespaceHandler> compendiumNamespaceRegistration;
@Override
public void start(BundleContext context) throws Exception {
this.bundleContext = context;
tracker = new ServiceTracker<BlueprintExtenderService, SpringOsgiExtender>(
bundleContext, BlueprintExtenderService.class, this
);
tracker.open();
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("osgi.service.blueprint.namespace", "http://www.springframework.org/schema/osgi");
osgiNamespaceRegistration = bundleContext.registerService(
NamespaceHandler.class, new SpringOsgiNamespaceHandler(), props);
props = new Hashtable<String, String>();
props.put("osgi.service.blueprint.namespace", "http://www.springframework.org/schema/osgi-compendium");
compendiumNamespaceRegistration = bundleContext.registerService(
NamespaceHandler.class, new SpringOsgiCompendiumNamespaceHandler(), props);
}
@Override
public void stop(BundleContext context) throws Exception {
tracker.close();
osgiNamespaceRegistration.unregister();
compendiumNamespaceRegistration.unregister();
}
@Override
public SpringOsgiExtender addingService(ServiceReference<BlueprintExtenderService> reference) {
BlueprintExtenderService blueprintExtenderService = bundleContext.getService(reference);
SpringOsgiExtender extender = new SpringOsgiExtender(blueprintExtenderService);
try {
extender.start(bundleContext);
} catch (Exception e) {
LOGGER.error("Error starting SpringOsgiExtender", e);
}
return extender;
}
@Override
public void modifiedService(ServiceReference<BlueprintExtenderService> reference, SpringOsgiExtender service) {
}
@Override
public void removedService(ServiceReference<BlueprintExtenderService> reference, SpringOsgiExtender service) {
try {
service.stop(bundleContext);
} catch (Exception e) {
LOGGER.error("Error stopping SpringOsgiExtender", e);
}
bundleContext.ungetService(reference);
}
}
| 9,164 |
0 | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring/extender/SpringOsgiExtension.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.extender;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.services.BlueprintExtenderService;
import org.apache.felix.utils.extender.Extension;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class SpringOsgiExtension implements Extension {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringOsgiExtension.class);
private final BlueprintExtenderService blueprintExtenderService;
private final Bundle bundle;
private final List<URL> paths;
BlueprintContainer container;
public SpringOsgiExtension(BlueprintExtenderService blueprintExtenderService, Bundle bundle, List<URL> paths) {
// TODO: parse Spring-Context header directives
// TODO: create-asynchrously
// TODO: wait-for-dependencies
// TODO: timeout
// TODO: publish-context
this.blueprintExtenderService = blueprintExtenderService;
this.bundle = bundle;
this.paths = paths;
}
@Override
public void start() throws Exception {
List<Object> bpPaths = new ArrayList<Object>();
Set<URI> namespaces = new LinkedHashSet<URI>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
for (URL url : paths) {
InputStream is = url.openStream();
try {
InputSource inputSource = new InputSource(is);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(inputSource);
Attr schemaLoc = doc.getDocumentElement().getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation");
if (schemaLoc != null) {
List<String> locs = new ArrayList<String>(Arrays.asList(schemaLoc.getValue().split("\\s+")));
locs.remove("");
for (int i = 0; i < locs.size() / 2; i++) {
String ns = locs.get(i * 2);
namespaces.add(URI.create(ns));
if (ns.startsWith("http://www.springframework.org/schema/osgi-compendium")) {
namespaces.add(URI.create(SpringOsgiCompendiumNamespaceHandler.CM_NAMESPACE));
}
}
}
} finally {
is.close();
}
}
File file = File.createTempFile("blueprint-spring-extender", ".xml");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
try {
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writer.write("<blueprint xmlns=\"http://www.osgi.org/xmlns/blueprint/v1.0.0\"\n");
writer.write("\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
writer.write("\txmlns:bean=\"http://www.springframework.org/schema/beans\"\n");
writer.write("\txsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-" + SpringXsdVersionResolver.resolve() + ".xsd\">\n");
for (URL url : paths) {
writer.write("\t<bean:import resource=\"" + url.toString() + "\"/>\n");
}
writer.write("</blueprint>\n");
} finally {
writer.close();
}
LOGGER.info("Generated blueprint for bundle {}/{} at {}", bundle.getSymbolicName(), bundle.getVersion(), file);
bpPaths.add(file.toURI().toURL());
container = blueprintExtenderService.createContainer(bundle, bpPaths, namespaces);
}
@Override
public void destroy() throws Exception {
// Make sure the container has not been destroyed yet
if (container == blueprintExtenderService.getContainer(bundle)) {
blueprintExtenderService.destroyContainer(bundle, container);
}
}
}
| 9,165 |
0 | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring | Create_ds/aries/blueprint/blueprint-spring-extender/src/main/java/org/apache/aries/blueprint/spring/extender/SpringOsgiExtender.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.extender;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.aries.blueprint.services.BlueprintExtenderService;
import org.apache.aries.blueprint.utils.HeaderParser;
import org.apache.aries.blueprint.utils.HeaderParser.PathElement;
import org.apache.felix.utils.extender.AbstractExtender;
import org.apache.felix.utils.extender.Extension;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Spring namespace extender.
* This OSGi extender is responsible for registering spring namespaces for blueprint.
*
* @see SpringOsgiExtension
*/
public class SpringOsgiExtender extends AbstractExtender {
public static final String SPRING_CONTEXT_HEADER = "Spring-Context";
private static final Logger LOGGER = LoggerFactory.getLogger(SpringOsgiExtender.class);
private final BlueprintExtenderService blueprintExtenderService;
public SpringOsgiExtender(BlueprintExtenderService blueprintExtenderService) {
this.blueprintExtenderService = blueprintExtenderService;
}
@Override
protected Extension doCreateExtension(Bundle bundle) throws Exception {
List<URL> paths = getSpringPaths(bundle);
if (paths != null && !paths.isEmpty()) {
return new SpringOsgiExtension(blueprintExtenderService, bundle, paths);
}
return null;
}
private List<URL> getSpringPaths(Bundle bundle) throws Exception {
LOGGER.debug("Scanning bundle {}/{} for spring application", bundle.getSymbolicName(), bundle.getVersion());
List<URL> pathList = new ArrayList<URL>();
String springHeader = bundle.getHeaders().get(SPRING_CONTEXT_HEADER);
if (springHeader == null) {
springHeader = "*";
}
List<PathElement> paths = HeaderParser.parseHeader(springHeader);
for (PathElement path : paths) {
String name = path.getName();
if ("*".equals(name)) {
name = "META-INF/spring/*.xml";
}
String baseName;
String filePattern;
int pos = name.lastIndexOf('/');
if (pos < 0) {
baseName = "/";
filePattern = name;
} else {
baseName = name.substring(0, pos + 1);
filePattern = name.substring(pos + 1);
}
if (filePattern.contains("*")) {
Enumeration<URL> e = bundle.findEntries(baseName, filePattern, false);
while (e != null && e.hasMoreElements()) {
pathList.add(e.nextElement());
}
} else {
pathList.add(bundle.getEntry(name));
}
}
if (!pathList.isEmpty()) {
LOGGER.debug("Found spring application in bundle {}/{} with paths: {}", bundle.getSymbolicName(), bundle.getVersion(), pathList);
// Check compatibility
// TODO: For lazy bundles, the class is either loaded from an imported package or not found, so it should
// not trigger the activation. If it does, we need to use something else like package admin or
// ServiceReference, or just not do this check, which could be quite harmful.
if (isCompatible(bundle)) {
return pathList;
} else {
LOGGER.info("Bundle {}/{} is not compatible with this blueprint extender", bundle.getSymbolicName(), bundle.getVersion());
}
} else {
LOGGER.debug("No blueprint application found in bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion());
}
return null;
}
private boolean isCompatible(Bundle bundle) {
// TODO
return true;
}
@Override
protected void debug(Bundle bundle, String msg) {
LOGGER.debug(msg + ": " + bundle.getSymbolicName() + "/" + bundle.getVersion());
}
@Override
protected void warn(Bundle bundle, String msg, Throwable t) {
LOGGER.warn(msg + ": " + bundle.getSymbolicName() + "/" + bundle.getVersion(), t);
}
@Override
protected void error(String msg, Throwable t) {
LOGGER.error(msg, t);
}
}
| 9,166 |
0 | Create_ds/aries/blueprint/blueprint-web-osgi/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-web-osgi/src/main/java/org/apache/aries/blueprint/web/BlueprintContextListener.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.blueprint.web;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.aries.blueprint.services.BlueprintExtenderService;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.container.BlueprintContainer;
/**
* OSGI Blueprint-aware ServletContextListener which use Aties BlueprintExtenderService
* to create Blueprint Container for the application bundle and save it as ServletContext attribute
*
*/
public class BlueprintContextListener implements ServletContextListener {
public static final String CONTAINER_ATTRIBUTE = "org.apache.aries.blueprint.container";
public static final String LOCATION_PARAM = "blueprintLocation";
public static final String DEFAULT_LOCATION = "OSGI-INF/blueprint.xml";
public static final String BUNDLE_CONTEXT_PARAM = "blueprintContext";
public static final String DEFAULT_BUNDLE_CONTEXT_ATTRIBUTE = "osgi-bundlecontext";
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
// Get bundle context
BundleContext bc = getBundleContext(sc);
if (bc == null) {
return;
}
// Get BlueprintExtenderService
BlueprintExtenderService blueprintExtender = getBlueprintExtenderService(bc);
if (blueprintExtender == null) {
return;
}
try {
// Check if the extender has already created a container
BlueprintContainer container = blueprintExtender.getContainer(bc.getBundle());
if (container == null) {
List<Object> blueprintResources = getBlueprintAppList(sc, bc.getBundle());
if (blueprintResources.isEmpty()) {
// The extender is expected to scan a bundle
container = blueprintExtender.createContainer(bc.getBundle());
} else {
// Use specified resources to create a container
container = blueprintExtender.createContainer(bc.getBundle(), blueprintResources);
}
}
if (container == null) {
sc.log("Failed to startup blueprint container.");
} else {
sc.setAttribute(CONTAINER_ATTRIBUTE, container);
}
} catch (Exception e) {
sc.log("Failed to startup blueprint container. " + e, e);
}
}
public void contextDestroyed(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
BlueprintContainer container = (BlueprintContainer)sc.getAttribute(CONTAINER_ATTRIBUTE);
if (container == null) {
return;
}
BundleContext bc = getBundleContext(sc);
if (bc == null) {
return;
}
BlueprintExtenderService blueprintExtender = getBlueprintExtenderService(bc);
if (blueprintExtender == null) {
return;
}
blueprintExtender.destroyContainer(bc.getBundle(), container);
}
private List<Object> getBlueprintAppList(ServletContext sc, Bundle applicationBundle) {
String location = sc.getInitParameter(LOCATION_PARAM);
if (location == null) {
location = DEFAULT_LOCATION;
}
List<Object> blueprintResources = new LinkedList<Object>();
URL entry = applicationBundle.getEntry(location);
if (entry != null) {
blueprintResources.add(entry);
}
return blueprintResources;
}
private BundleContext getBundleContext(ServletContext sc) {
String bundleContextAttributeName = sc
.getInitParameter(BUNDLE_CONTEXT_PARAM);
if (bundleContextAttributeName == null) {
bundleContextAttributeName = DEFAULT_BUNDLE_CONTEXT_ATTRIBUTE;
}
BundleContext bc = (BundleContext) sc.getAttribute(bundleContextAttributeName);
if (bc == null) {
sc.log("Failed to startup blueprint container: no BundleContext is available");
}
return bc;
}
private BlueprintExtenderService getBlueprintExtenderService(BundleContext bc) {
ServiceReference sref = bc
.getServiceReference(BlueprintExtenderService.class.getName());
if (sref != null) {
return (BlueprintExtenderService) bc.getService(sref);
} else {
return null;
}
}
}
| 9,167 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-pax-cdi-handlers/src/main/java/org/apache/aries/blueprint/plugin/handlers | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-pax-cdi-handlers/src/main/java/org/apache/aries/blueprint/plugin/handlers/paxcdi/OsgiServiceHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.handlers.paxcdi;
import org.apache.aries.blueprint.plugin.spi.ContextEnricher;
import org.apache.aries.blueprint.plugin.spi.CustomDependencyAnnotationHandler;
import org.apache.aries.blueprint.plugin.spi.XmlWriter;
import org.ops4j.pax.cdi.api.OsgiService;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class OsgiServiceHandler implements CustomDependencyAnnotationHandler<OsgiService> {
@Override
public Class<OsgiService> getAnnotation() {
return OsgiService.class;
}
@Override
public String handleDependencyAnnotation(AnnotatedElement annotatedElement, String name, ContextEnricher contextEnricher) {
final ServiceFilter serviceFilter = extractServiceFilter(annotatedElement);
final String id = name != null ? name : generateReferenceId(getClass(annotatedElement), serviceFilter);
final Class<?> clazz = getClass(annotatedElement);
contextEnricher.addBean(id, getClass(annotatedElement));
contextEnricher.addBlueprintContentWriter(getWriterId(id, clazz), getXmlWriter(id, clazz, serviceFilter));
return id;
}
@Override
public String handleDependencyAnnotation(final Class<?> clazz, OsgiService annotation, String name, ContextEnricher contextEnricher) {
final ServiceFilter serviceFilter = extractServiceFilter(annotation);
final String id = name != null ? name : generateReferenceId(clazz, serviceFilter);
contextEnricher.addBean(id, clazz);
contextEnricher.addBlueprintContentWriter(getWriterId(id, clazz), getXmlWriter(id, clazz, serviceFilter));
return id;
}
private XmlWriter getXmlWriter(final String id, final Class<?> clazz, final ServiceFilter serviceFilter) {
return new XmlWriter() {
@Override
public void write(XMLStreamWriter writer) throws XMLStreamException {
writer.writeEmptyElement("reference");
writer.writeAttribute("id", id);
writer.writeAttribute("interface", clazz.getName());
if (serviceFilter.filter != null && !"".equals(serviceFilter.filter)) {
writer.writeAttribute("filter", serviceFilter.filter);
}
if (serviceFilter.compName != null && !"".equals(serviceFilter.compName)) {
writer.writeAttribute("component-name", serviceFilter.compName);
}
}
};
}
private String getWriterId(String id, Class<?> clazz) {
return "osgiService/" + clazz.getName() + "/" + id;
}
private Class<?> getClass(AnnotatedElement annotatedElement) {
if (annotatedElement instanceof Class<?>) {
return (Class<?>) annotatedElement;
}
if (annotatedElement instanceof Method) {
return ((Method) annotatedElement).getParameterTypes()[0];
}
if (annotatedElement instanceof Field) {
return ((Field) annotatedElement).getType();
}
throw new RuntimeException("Unknown annotated element");
}
private ServiceFilter extractServiceFilter(AnnotatedElement annotatedElement) {
OsgiService osgiService = annotatedElement.getAnnotation(OsgiService.class);
return extractServiceFilter(osgiService);
}
private ServiceFilter extractServiceFilter(OsgiService osgiService) {
String filterValue = osgiService.filter();
return new ServiceFilter(filterValue);
}
private String generateReferenceId(Class clazz, ServiceFilter serviceFilter) {
String prefix = getBeanNameFromSimpleName(clazz.getSimpleName());
String suffix = createIdSuffix(serviceFilter);
return prefix + suffix;
}
private static String getBeanNameFromSimpleName(String name) {
return name.substring(0, 1).toLowerCase() + name.substring(1, name.length());
}
private String createIdSuffix(ServiceFilter serviceFilter) {
if (serviceFilter.filter != null) {
return "-" + getId(serviceFilter.filter);
}
if (serviceFilter.compName != null) {
return "-" + serviceFilter.compName;
}
return "";
}
private String getId(String raw) {
StringBuilder builder = new StringBuilder();
for (int c = 0; c < raw.length(); c++) {
char ch = raw.charAt(c);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') {
builder.append(ch);
}
}
return builder.toString();
}
private static class ServiceFilter {
final String filter;
final String compName;
ServiceFilter(String filterValue) {
if (filterValue == null || filterValue.isEmpty()) {
filter = null;
compName = null;
} else if (filterValue.contains("(")) {
filter = filterValue;
compName = null;
} else {
filter = null;
compName = filterValue;
}
}
}
}
| 9,168 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-pax-cdi-handlers/src/main/java/org/apache/aries/blueprint/plugin/handlers | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-pax-cdi-handlers/src/main/java/org/apache/aries/blueprint/plugin/handlers/paxcdi/ServiceProperty.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.handlers.paxcdi;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.util.Arrays;
import java.util.List;
class ServiceProperty {
final String name;
private final String type;
private final boolean isArray;
private final List<String> values;
ServiceProperty(String name, String value) {
if (hasTypeSignature(name)) {
String[] splitName = name.split(":");
this.name = splitName[0];
this.type = getType(splitName[1]);
this.isArray = splitName[1].endsWith("[]");
this.values = isArray ? Arrays.asList(value.split("\\|")) : Arrays.asList(value);
} else {
this.name = name;
this.type = null;
this.isArray = false;
this.values = Arrays.asList(value);
}
}
private static boolean hasTypeSignature(String name) {
return name.contains(":");
}
private static String getType(String typeSignature) {
String rawType;
if (typeSignature.endsWith("[]")) {
rawType = typeSignature.substring(0, typeSignature.length() - 2);
} else {
rawType = typeSignature;
}
if ("".equals(rawType)) {
return null;
}
if (rawType.contains(".")) {
return rawType;
} else {
return "java.lang." + rawType;
}
}
void write(XMLStreamWriter writer) throws XMLStreamException {
if (type == null && !isArray) {
writer.writeEmptyElement("entry");
writer.writeAttribute("key", name);
writer.writeAttribute("value", values.get(0));
} else {
writer.writeStartElement("entry");
writer.writeAttribute("key", name);
if (isArray) {
writer.writeStartElement("array");
if (type != null) {
writer.writeAttribute("value-type", type);
}
for (String value : values) {
writer.writeStartElement("value");
writer.writeCharacters(value);
writer.writeEndElement();
}
writer.writeEndElement();
} else {
writer.writeStartElement("value");
writer.writeAttribute("type", type);
writer.writeCharacters(values.get(0));
writer.writeEndElement();
}
writer.writeEndElement();
}
}
String getSingleValue() {
if (values.size() > 1) {
throw new IllegalArgumentException("Property has more than one value");
}
return values.get(0);
}
}
| 9,169 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-pax-cdi-handlers/src/main/java/org/apache/aries/blueprint/plugin/handlers | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-pax-cdi-handlers/src/main/java/org/apache/aries/blueprint/plugin/handlers/paxcdi/OsgiServiceProviderHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.handlers.paxcdi;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.aries.blueprint.plugin.spi.BeanAnnotationHandler;
import org.apache.aries.blueprint.plugin.spi.BeanEnricher;
import org.apache.aries.blueprint.plugin.spi.ContextEnricher;
import org.apache.aries.blueprint.plugin.spi.XmlWriter;
import org.ops4j.pax.cdi.api.OsgiServiceProvider;
import org.ops4j.pax.cdi.api.Properties;
import org.ops4j.pax.cdi.api.Property;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.lang.reflect.AnnotatedElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class OsgiServiceProviderHandler implements BeanAnnotationHandler<OsgiServiceProvider> {
private static final List<String> SPECIAL_PROPERTIES = Collections.singletonList("service.ranking");
@Override
public Class<OsgiServiceProvider> getAnnotation() {
return OsgiServiceProvider.class;
}
@Override
public void handleBeanAnnotation(AnnotatedElement annotatedElement, final String id, ContextEnricher contextEnricher, BeanEnricher beanEnricher) {
handleAnnotation(annotatedElement, id, contextEnricher);
}
private void handleAnnotation(AnnotatedElement annotatedElement, final String id, ContextEnricher contextEnricher) {
final OsgiServiceProvider serviceProvider = annotatedElement.getAnnotation(OsgiServiceProvider.class);
Properties properties = annotatedElement.getAnnotation(Properties.class);
final List<String> interfaceNames = extractServiceInterfaces(serviceProvider);
final List<ServiceProperty> serviceProperties = extractProperties(properties);
contextEnricher.addBlueprintContentWriter("OsgiServiceProvider/" + annotatedElement + "/" + id, new XmlWriter() {
@Override
public void write(XMLStreamWriter writer) throws XMLStreamException {
writeService(writer, serviceProperties, interfaceNames, id);
}
});
}
private void writeService(XMLStreamWriter writer, List<ServiceProperty> serviceProperties, List<String> interfaceNames, String id) throws XMLStreamException {
boolean writeEmptyElement = serviceProperties.isEmpty() && interfaceNames.size() < 2;
if (writeEmptyElement) {
writer.writeEmptyElement("service");
} else {
writer.writeStartElement("service");
}
writer.writeAttribute("ref", id);
if (interfaceNames.size() == 0) {
writer.writeAttribute("auto-export", "interfaces");
} else if (interfaceNames.size() == 1) {
writer.writeAttribute("interface", Iterables.getOnlyElement(interfaceNames));
} else {
writeInterfacesElement(writer, interfaceNames);
}
if (!serviceProperties.isEmpty()) {
writeRanking(writer, serviceProperties);
writeProperties(writer, serviceProperties);
}
if (!writeEmptyElement) {
writer.writeEndElement();
}
}
private static List<ServiceProperty> extractProperties(Properties properties) {
List<ServiceProperty> serviceProperties = new ArrayList<>();
if (properties != null) {
for (Property property : properties.value()) {
serviceProperties.add(new ServiceProperty(property.name(), property.value()));
}
}
return serviceProperties;
}
private static List<String> extractServiceInterfaces(OsgiServiceProvider serviceProvider) {
List<String> interfaceNames = Lists.newArrayList();
for (Class<?> serviceIf : serviceProvider.classes()) {
interfaceNames.add(serviceIf.getName());
}
return interfaceNames;
}
private void writeInterfacesElement(XMLStreamWriter writer, Iterable<String> interfaceNames) throws XMLStreamException {
writer.writeStartElement("interfaces");
for (String interfaceName : interfaceNames) {
writer.writeStartElement("value");
writer.writeCharacters(interfaceName);
writer.writeEndElement();
}
writer.writeEndElement();
}
private void writeRanking(XMLStreamWriter writer, List<ServiceProperty> serviceProperties) throws XMLStreamException {
for (ServiceProperty serviceProperty : serviceProperties) {
if ("service.ranking".equals(serviceProperty.name)) {
try {
Integer ranking = Integer.parseInt(serviceProperty.getSingleValue());
writer.writeAttribute("ranking", ranking.toString());
} catch (NumberFormatException e) {
throw new IllegalArgumentException("service.ranking property must be an integer!");
}
}
}
}
private void writeProperties(XMLStreamWriter writer, List<ServiceProperty> serviceProperties) throws XMLStreamException {
writer.writeStartElement("service-properties");
for (ServiceProperty serviceProperty : serviceProperties) {
if (!SPECIAL_PROPERTIES.contains(serviceProperty.name)) {
serviceProperty.write(writer);
}
}
writer.writeEndElement();
}
}
| 9,170 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/BeanAnnotationHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
/**
* Annotation A allows for enriching blueprint XML or add new bean to context when bean class or factory method is marked with such annotation
*/
public interface BeanAnnotationHandler<A extends Annotation> extends AnnotationHandler<A> {
/**
* Handle annotation A on bean or factory method
* @param annotatedElement bean class or factory method
* @param id id of bean
* @param contextEnricher context enricher
*/
void handleBeanAnnotation(AnnotatedElement annotatedElement, String id, ContextEnricher contextEnricher, BeanEnricher beanEnricher);
}
| 9,171 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/BeanEnricher.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
/**
* Interface allows for adding custom XML or adding attributes to bean element
* Instance of this interface is provided by plugin.
*/
public interface BeanEnricher {
/**
* Add attribute to bean element
* @param key name of attribute
* @param value value of attribute
*/
void addAttribute(String key, String value);
/**
* Add custom XML inside bean element
* @param id identifier of writer instance (should be unique)
* @param blueprintWriter callback used to write custom XML
*/
void addBeanContentWriter(String id, XmlWriter blueprintWriter);
}
| 9,172 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/MethodAnnotationHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
/**
* Annotation A on method could write custom XML in blueprint or add bean to blueprint context
*/
public interface MethodAnnotationHandler<A extends Annotation> extends AnnotationHandler<A> {
/**
* Handle annotations A on methods
* @param clazz class which contains annotated methods
* @param methods methods annotated with annotation A
* @param contextEnricher context enricher
* @param beanEnricher bean enricher
*/
void handleMethodAnnotation(Class<?> clazz, List<Method> methods, ContextEnricher contextEnricher, BeanEnricher beanEnricher);
}
| 9,173 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/CollectionDependencyAnnotationHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
/**
* Annotation A on constructor, setter or field adds inject collection (array, list, set) of beans into annotated element.
*/
public interface CollectionDependencyAnnotationHandler<A extends Annotation> extends AnnotationHandler<A> {
/**
* @param annotation instance of annotation A
* @return class of beans to inject
*/
Class<?> getBeanClass(Annotation annotation);
}
| 9,174 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/QualifingAnnotationFinder.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
/**
* Annotation A is qualifying another annotation, so such marked annotation could be used to inject beans which class are also annotated with this annotation
*/
public interface QualifingAnnotationFinder<A extends Annotation> extends AnnotationHandler<A> {
} | 9,175 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/BlueprintConfiguration.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.util.Map;
import java.util.Set;
/**
* Blueprint plugin configuration from pom.xml
*/
public interface BlueprintConfiguration {
/**
* @return values of namespaces parameter
*/
Set<String> getNamespaces();
/**
* @return value of default activation parameter
*/
Activation getDefaultActivation();
/**
* @return value of default availability parameter
*/
Availability getDefaultAvailability();
/**
* @return value of default timeout parameter
*/
Long getDefaultTimeout();
/**
* @return custom parameters
*/
Map<String, String> getCustomParameters();
}
| 9,176 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/CustomDependencyAnnotationHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
/**
* Annotation A allows for enriching blueprint XML or add new bean to context when injecting bean, e. g. for generating in bean which could be injected
*/
public interface CustomDependencyAnnotationHandler<A extends Annotation> extends AnnotationHandler<A> {
/**
* @param annotatedElement field or setter method
* @param name name of bean to inject (null if bean name is not provided)
* @param contextEnricher context enricher
* @return name of generated bean which should be injected or null
*/
String handleDependencyAnnotation(AnnotatedElement annotatedElement, String name, ContextEnricher contextEnricher);
/**
* @param clazz class of constructor parameter or setter parameter
* @param annotation instance of annotation A
* @param name name of bean to inject (null if bean name is not provided)
* @param contextEnricher context enricher
* @return name of generated bean which should be injected or null
*/
String handleDependencyAnnotation(Class<?> clazz, A annotation, String name, ContextEnricher contextEnricher);
}
| 9,177 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/NamedLikeHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
/**
* Annotation A on class provides id of bean in blueprint XML created from this class. Annotation could be also used to inject bean with provided id in constructor, setter or field.
*/
public interface NamedLikeHandler<A extends Annotation> extends AnnotationHandler<A> {
/**
* @param clazz depends on annotated element - if it is class then clazz is class itself, if setter then class of method argument and if field then class of field
* @param annotatedElement class, method, field annotated with A
* @return name of bean
*/
String getName(Class clazz, AnnotatedElement annotatedElement);
/**
* Using to get name of bean based only on annotation when:
* - inject via constructor
* - inject via setter
* @param annotation instance of A annotation
* @return name of bean
*/
String getName(Object annotation);
}
| 9,178 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/ContextInitializationHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
/**
* Handler called at the beginning of blueprint XML creation
*/
public interface ContextInitializationHandler {
/**
* Add custom XML or add bean to context
*
* @param contextEnricher context enricher
*/
void initContext(ContextEnricher contextEnricher);
}
| 9,179 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/InjectLikeHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
/**
* Annotation A on constructor, setter or field adds inject beans into annotated element.
*/
public interface InjectLikeHandler<A extends Annotation> extends AnnotationHandler<A> {
}
| 9,180 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/Availability.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
/**
* Availability of references and reference-lists
*/
public enum Availability {
MANDATORY,
OPTIONAL;
@Override
public String toString() {
return name().toLowerCase();
}
}
| 9,181 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/FieldAnnotationHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
/**
* Annotation A on field could write custom XML in blueprint or add bean to blueprint context
*/
public interface FieldAnnotationHandler<A extends Annotation> extends AnnotationHandler<A> {
/**
* Handle annotations A on methods
* @param clazz class which contains annotated fields\
* @param fields fields annotated with annotation A
* @param contextEnricher context enricher
* @param beanEnricher bean enricher
*/
void handleFieldAnnotation(Class<?> clazz, List<Field> fields, ContextEnricher contextEnricher, BeanEnricher beanEnricher);
}
| 9,182 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/XmlWriter.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* Write custom part of blueprint XML depends on context (inside bean or blueprint element)
*/
public interface XmlWriter {
/**
* Write custom XML
* @param xmlStreamWriter xml writer provided by plugin
* @throws XMLStreamException when exception occurred during writing XML
*/
void write(XMLStreamWriter xmlStreamWriter) throws XMLStreamException;
}
| 9,183 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/ContextEnricher.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
/**
* Interface allows for adding custom XML or adding beans to bean search context
* Instance of this interface is provided by plugin.
*/
public interface ContextEnricher {
/**
* Add bean to search context (id should be unique)
* @param id name of bean
* @param clazz class of bean
*/
void addBean(String id, Class<?> clazz);
/**
* Add custom XML to blueprint
* @param id identifier of writer instance (should be unique)
* @param blueprintWriter callback used to write custom XML
*/
void addBlueprintContentWriter(String id, XmlWriter blueprintWriter);
/**
* @return plugin configuration from pom.xml
*/
BlueprintConfiguration getBlueprintConfiguration();
}
| 9,184 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/AnnotationHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
/**
* Base annotation handler interface
*/
public interface AnnotationHandler<A extends Annotation> {
/**
* @return annotation class
*/
Class<A> getAnnotation();
}
| 9,185 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/ValueInjectionHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
/**
* Annotation on field, setter or constructor argument is used to generate argument or property elements with value attribute inside bean
*/
public interface ValueInjectionHandler<A extends Annotation> extends AnnotationHandler<A> {
/**
* Interpret annotation instance and create value of argument's or property's value attribute
*
* @param annotation instance of annotation A
* @return value of
*/
String getValue(Object annotation);
}
| 9,186 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/BeanFinder.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
/**
* Annotation A on class generates bean from this class
*/
public interface BeanFinder<A extends Annotation> extends AnnotationHandler<A> {
/**
* @return true if bean annotated with A should be generated in singleton scope, false otherwise
*/
boolean isSingleton();
}
| 9,187 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/FactoryMethodFinder.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
import java.lang.annotation.Annotation;
/**
* Annotation A on method marks this method as factory method
*/
public interface FactoryMethodFinder<A extends Annotation> extends AnnotationHandler<A> {
}
| 9,188 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-spi/src/main/java/org/apache/aries/blueprint/plugin/spi/Activation.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.plugin.spi;
/**
* Activation mode for bean
*/
public enum Activation {
EAGER,
LAZY;
@Override
public String toString() {
return name().toLowerCase();
}
}
| 9,189 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/collection/CollectionInject.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.collection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotating any field, setter or constructor parameter inject collection of beans.
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CollectionInject {
/**
* @return class of beans to inject
*/
Class<?> value();
}
| 9,190 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/collection/package-info.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@org.osgi.annotation.bundle.Export
@org.osgi.annotation.versioning.Version("1.0.0")
package org.apache.aries.blueprint.annotation.collection;
| 9,191 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/config/ConfigProperty.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotate fields with this to inject configuration like:
* <code>@ConfigProperty("${mykey}")</code>
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ConfigProperty {
String value();
}
| 9,192 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/config/ConfigProperties.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotating any parameter with this will create a
* cm:cm-properties element in blueprint and inject such
* properties into annotated place
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ConfigProperties {
/**
* @return persistent id of configuration
*/
String pid();
/**
* @return should update on each properties change
*/
boolean update() default false;
}
| 9,193 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/config/Config.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotating any class with this will create a
* cm:property-placeholder element in blueprint
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Config {
String pid();
String updatePolicy() default "reload";
String placeholderPrefix() default "${";
String placeholderSuffix() default "}";
DefaultProperty[] defaults() default {};
}
| 9,194 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/config/DefaultProperty.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.config;
public @interface DefaultProperty {
String key();
String value();
}
| 9,195 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/config/package-info.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@org.osgi.annotation.bundle.Export
@org.osgi.annotation.versioning.Version("1.1.0")
package org.apache.aries.blueprint.annotation.config;
| 9,196 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/bean/Scope.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.bean;
public enum Scope {
SINGLETON,
PROTOTYPE
}
| 9,197 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/bean/Bean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.bean;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotating any class or method will create a bean.
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Bean {
/**
* @return id or auto generated name from class name when id is empty
*/
String id() default "";
/**
* @return activation of bean: eager, lazy or defaut for whole blueprint file
*/
Activation activation() default Activation.DEFAULT;
/**
* @return array of bean ids on which this bean depends
*/
String[] dependsOn() default {};
/**
* @return bean scope
*/
Scope scope() default Scope.SINGLETON;
/**
* @return init method name, if empty then bean has no init method.
* Warning: if bean has another annotation which selects another init-method then cannot determine which method will be selected.
*/
String initMethod() default "";
/**
* @return destroy method name, if empty then bean has no destroy method
* * Warning: if bean has another annotation which selects another destroy-method then cannot determine which method will be selected.
*/
String destroyMethod() default "";
}
| 9,198 |
0 | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation | Create_ds/aries/blueprint/plugin/blueprint-maven-plugin-annotation/src/main/java/org/apache/aries/blueprint/annotation/bean/Activation.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.bean;
public enum Activation {
LAZY,
EAGER,
DEFAULT
}
| 9,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.