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/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/CreditRecord.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.blueprint.idverifier.client;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author forrestxm
*
*/
public class CreditRecord {
private String personid;
private String recordNO;
private Date happenedwhen;
private String recordjustification;
private String recorddescription;
public CreditRecord(){
}
public CreditRecord(String s){
this(s, ":");
}
public CreditRecord(String s, String delimiter) {
convert(s, delimiter);
}
private void convert(String s, String delimiter) {
String[] pieces = s.split(delimiter);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if (pieces.length == 5) {
this.setPersonid(pieces[0]);
this.setRecordNO(pieces[1]);
try {
this.setHappenedwhen(sdf.parse(pieces[2]));
} catch (ParseException e) {
e.printStackTrace();
}
this.setRecordjustification(pieces[3]);
this.setRecorddescription(pieces[4]);
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "CreditRecord [personid=" + personid + ", recordNO=" + recordNO
+ ", recordjustification=" + recordjustification
+ ", happenedwhen=" + happenedwhen + ", recorddescription="
+ recorddescription + "]";
}
/**
* @return the personid
*/
public String getPersonid() {
return personid;
}
/**
* @param personid
* the personid to set
*/
public void setPersonid(String personid) {
this.personid = personid;
}
/**
* @return the recordNO
*/
public String getRecordNO() {
return recordNO;
}
/**
* @param recordNO
* the recordNO to set
*/
public void setRecordNO(String recordNO) {
this.recordNO = recordNO;
}
/**
* @return the happenedwhen
*/
public Date getHappenedwhen() {
return happenedwhen;
}
/**
* @param happenedwhen
* the happenedwhen to set
*/
public void setHappenedwhen(Date happenedwhen) {
this.happenedwhen = happenedwhen;
}
/**
* @return the recordjustification
*/
public String getRecordjustification() {
return recordjustification;
}
/**
* @param recordjustification
* the recordjustification to set
*/
public void setRecordjustification(String recordjustification) {
this.recordjustification = recordjustification;
}
/**
* @return the recorddescription
*/
public String getRecorddescription() {
return recorddescription;
}
/**
* @param recorddescription
* the recorddescription to set
*/
public void setRecorddescription(String recorddescription) {
this.recorddescription = recorddescription;
}
}
| 8,300 |
0 | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/RandomIDChoice.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.blueprint.idverifier.client;
import java.util.Random;
/**
* @author forrestxm
*
*/
public class RandomIDChoice {
private static String[] idarray = {
"310115197011076874",
"310115197011277844",
"110108197710016853",
"11010819541001366X"
};
public RandomIDChoice(){
super();
}
public String getRandomID(){
Random randomintgenerator = new Random();
int randomint = randomintgenerator.nextInt(1000);
int remain = randomint % idarray.length;
if (remain < 0 || remain > idarray.length - 1) {
remain = randomintgenerator.nextInt(1000) % idarray.length;
}
return idarray[remain];
}
}
| 8,301 |
0 | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/CreditRecordStore.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.blueprint.idverifier.client;
import java.util.HashSet;
import java.util.Set;
/**
* @author forrestxm
*
*/
public class CreditRecordStore {
private Set<String> personidindex;
private Set<PersonCreditRecords> personrecords;
public CreditRecordStore(Set<CreditRecord> records){
init(records);
}
void init(Set<CreditRecord> records){
personidindex = new HashSet<String>();
personrecords = new HashSet<PersonCreditRecords>();
for (CreditRecord arecord : records){
personidindex.add(arecord.getPersonid());
}
for (String personid : personidindex){
personrecords.add(new PersonCreditRecords(personid));
}
for (CreditRecord arecord : records){
PersonCreditRecords target = getAPersonRecords(arecord.getPersonid());
if ( target != null){
target.add(arecord);
}
}
}
public synchronized boolean add(CreditRecord arecord){
boolean b = false;
PersonCreditRecords target = getAPersonRecords(arecord.getPersonid());
if ( target != null){
b = target.add(arecord);
} else {
PersonCreditRecords apersonrecords = new PersonCreditRecords(arecord.getPersonid());
apersonrecords.add(arecord);
personrecords.add(apersonrecords);
personidindex.add(arecord.getPersonid());
b = true;
}
return b;
}
public synchronized boolean remove(CreditRecord arecord){
boolean b = false;
if (personidindex.contains(arecord.getPersonid())) {
PersonCreditRecords target = getAPersonRecords(arecord.getPersonid());
b = target.remove(arecord);
if (target.isEmpty()){
personidindex.remove(arecord.getPersonid());
personrecords.remove(target);
}
}
return b;
}
public PersonCreditRecords getAPersonRecords(String personid){
PersonCreditRecords result = null;
for (PersonCreditRecords arecord : this.personrecords){
if (arecord.getPersonid().equals(personid)){
result = arecord;
break;
}
}
return result;
}
/**
* @return the personidindex
*/
public Set<String> getPersonidindex() {
return personidindex;
}
/**
* @return the personrecords
*/
public Set<PersonCreditRecords> getPersonrecords() {
return personrecords;
}
}
| 8,302 |
0 | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/BankInfo.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.blueprint.idverifier.client;
/**
* @author forrestxm
*
*/
public class BankInfo {
private String bankname;
private String bankaddress;
private String banklegalpersonname;
private String bankregistrationnumber;
/**
* @return the bankname
*/
public String getBankname() {
return bankname;
}
/**
* @param bankname the bankname to set
*/
public void setBankname(String bankname) {
this.bankname = bankname;
}
/**
* @return the bandaddress
*/
public String getBankaddress() {
return bankaddress;
}
/**
* @param bandaddress the bandaddress to set
*/
public void setBankaddress(String bankaddress) {
this.bankaddress = bankaddress;
}
/**
* @return the banklegalpersonname
*/
public String getBanklegalpersonname() {
return banklegalpersonname;
}
/**
* @param banklegalpersonname the banklegalpersonname to set
*/
public void setBanklegalpersonname(String banklegalpersonname) {
this.banklegalpersonname = banklegalpersonname;
}
/**
* @return the bankregistrationnumber
*/
public String getBankregistrationnumber() {
return bankregistrationnumber;
}
/**
* @param bankregistrationnumber the bankregistrationnumber to set
*/
public void setBankregistrationnumber(String bankregistrationnumber) {
this.bankregistrationnumber = bankregistrationnumber;
}
@Override
public String toString(){
System.out.println("********Start of Printing Bank Info**********");
System.out.println("Bank Name: " + this.getBankname());
System.out.println("Bank Address: " + this.getBankaddress());
System.out.println("Bank Legal Person: "+ this.getBanklegalpersonname());
System.out.println("Bank Reg. Number: "+ this.getBankregistrationnumber());
System.out.println("********End of Printing Bank Info**********");
String delimiter = ",";
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append("bankname=" + this.getBankname()+ delimiter);
sb.append("bankaddress=" + this.getBankaddress() + delimiter);
sb.append("banklegalpersonname="+ this.getBanklegalpersonname() + delimiter);
sb.append("bankregistrationnumber="+ this.getBankregistrationnumber());
sb.append("]");
return sb.toString();
}
}
| 8,303 |
0 | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/IDVerifierClientActivator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.blueprint.idverifier.client;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* @author forrestxm
*
*/
public class IDVerifierClientActivator implements BundleActivator {
MBeanServer mbs;
ServiceRegistration mbsr;
/* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundlectx) throws Exception {
mbs = ManagementFactory.getPlatformMBeanServer();
mbsr = bundlectx.registerService(MBeanServer.class.getCanonicalName(), mbs, null);
}
/* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundlectx) throws Exception {
// mbs = null;
// mbsr = null;
}
}
| 8,304 |
0 | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier | Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/CreditRecordFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.blueprint.idverifier.client;
/**
* @author forrestxm
*
*/
public class CreditRecordFactory {
public static CreditRecord staticCreateBean(String record) {
staticcount++;
return new CreditRecord(record);
}
private String targetbeanname;
private static int staticcount = 0;
private static int dynamiccount = 0;
public CreditRecordFactory(String beanname) {
this.targetbeanname = beanname;
}
public CreditRecord dynamicCreateBean(String record) {
dynamiccount++;
return new CreditRecord(record);
}
public void creationStatistics() {
System.out.println("**********Bean factory "
+ this.getClass().getSimpleName()
+ " says goodbye!************");
System.out.println("**********I created " + staticcount + " "
+ targetbeanname + " with static factory, " + dynamiccount
+ " " + targetbeanname + " with dynamic factory.***********");
}
}
| 8,305 |
0 | Create_ds/aries/jndi/jndi-core/src/test/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/test/java/org/apache/aries/jndi/ObjectFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.apache.aries.jndi.startup.Activator;
import org.apache.aries.jndi.urls.URLObjectFactoryFinder;
import org.apache.aries.mocks.BundleContextMock;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.Skeleton;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.service.jndi.JNDIConstants;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.naming.spi.NamingManager;
import javax.naming.spi.ObjectFactory;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Properties;
import static org.junit.Assert.*;
public class ObjectFactoryTest {
private Activator activator;
private BundleContext bc;
private Hashtable<Object, Object> env;
/**
* This method does the setup .
*
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
@Before
public void setup() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
System.setProperty("org.apache.aries.jndi.disable.builder", "false");
BundleContextMock mock = new BundleContextMock();
mock.addBundle(mock.getBundle());
bc = Skeleton.newMock(mock, BundleContext.class);
activator = new Activator();
activator.start(bc);
env = new Hashtable<Object, Object>();
env.put(JNDIConstants.BUNDLE_CONTEXT, bc);
}
/**
* Make sure we clear the caches out before the next test.
*/
@After
public void teardown() {
activator.stop(bc);
BundleContextMock.clear();
}
@Test
public void testURLReferenceWithNoMatchingHandler() throws Exception {
Reference ref = new Reference(null);
ref.add(new StringRefAddr("URL", "wibble"));
Object obj = NamingManager.getObjectInstance(ref, null, null, env);
assertSame("The naming manager should have returned the reference object", ref, obj);
}
@Test
public void testURLReferenceWithMatchingHandler() throws Exception {
String testObject = "Test object";
ObjectFactory factory = Skeleton.newMock(ObjectFactory.class);
Skeleton.getSkeleton(factory).setReturnValue(new MethodCall(ObjectFactory.class, "getObjectInstance", Object.class, Name.class, Context.class, Hashtable.class), testObject);
Properties props = new Properties();
props.setProperty("osgi.jndi.urlScheme", "wibble");
bc.registerService(ObjectFactory.class.getName(), factory, (Dictionary) props);
Reference ref = new Reference(null);
ref.add(new StringRefAddr("URL", "wibble"));
Object obj = NamingManager.getObjectInstance(ref, null, null, env);
assertEquals("The naming manager should have returned the test object", testObject, obj);
}
@Test
public void testURLReferenceUsingURLObjectFactoryFinder() throws Exception {
String testObject = "Test object";
URLObjectFactoryFinder factory = Skeleton.newMock(URLObjectFactoryFinder.class);
Skeleton.getSkeleton(factory).setReturnValue(new MethodCall(ObjectFactory.class, "getObjectInstance", Object.class, Name.class, Context.class, Hashtable.class), testObject);
bc.registerService(URLObjectFactoryFinder.class.getName(), factory, (Dictionary) new Properties());
Reference ref = new Reference(null);
ref.add(new StringRefAddr("URL", "wibble"));
Object obj = NamingManager.getObjectInstance(ref, null, null, env);
assertEquals("The naming manager should have returned the test object", testObject, obj);
}
@Test
public void testReferenceWithNoClassName() throws Exception {
String testObject = "Test object";
ObjectFactory factory = Skeleton.newMock(ObjectFactory.class);
Skeleton.getSkeleton(factory).setReturnValue(new MethodCall(ObjectFactory.class, "getObjectInstance", Object.class, Name.class, Context.class, Hashtable.class), testObject);
bc.registerService(ObjectFactory.class.getName(), factory, null);
Reference ref = new Reference(null);
Object obj = NamingManager.getObjectInstance(ref, null, null, env);
assertEquals("The naming manager should have returned the test object", testObject, obj);
}
@Test
public void testSpecifiedFactoryWithMatchingFactory() throws Exception {
String testObject = "Test object";
ObjectFactory factory = Skeleton.newMock(ObjectFactory.class);
Skeleton.getSkeleton(factory).setReturnValue(new MethodCall(ObjectFactory.class, "getObjectInstance", Object.class, Name.class, Context.class, Hashtable.class), testObject);
Reference ref = new Reference("dummy.class.name", factory.getClass().getName(), "");
bc.registerService(new String[]{ObjectFactory.class.getName(), factory.getClass().getName()},
factory, null);
Object obj = NamingManager.getObjectInstance(ref, null, null, env);
assertEquals("The naming manager should have returned the test object", testObject, obj);
}
@Test
public void testSpecifiedFactoryWithRegisteredButNotMatchingFactory() throws Exception {
String testObject = "Test object";
ObjectFactory factory = Skeleton.newMock(ObjectFactory.class);
Skeleton.getSkeleton(factory).setReturnValue(new MethodCall(ObjectFactory.class, "getObjectInstance", Object.class, Name.class, Context.class, Hashtable.class), testObject);
Reference ref = new Reference("dummy.class.name", "dummy.factory.class.name", "");
bc.registerService(new String[]{ObjectFactory.class.getName(), factory.getClass().getName()},
factory, null);
Object obj = NamingManager.getObjectInstance(ref, null, null, env);
assertSame("The naming manager should have returned the reference object", ref, obj);
}
@Test
public void testSpecifiedFactoryWithNoMatchingFactory() throws Exception {
Reference ref = new Reference("dummy.class.name");
Object obj = NamingManager.getObjectInstance(ref, null, null, env);
assertSame("The naming manager should have returned the reference object", ref, obj);
}
@Test
public void testFactoriesThatDoUnsafeCastsAreIgnored() throws Exception {
Hashtable<String, Object> props = new Hashtable<String, Object>();
props.put("aries.object.factory.requires.reference", Boolean.TRUE);
bc.registerService(ObjectFactory.class.getName(), new ObjectFactory() {
public Object getObjectInstance(Object arg0, Name arg1, Context arg2, Hashtable<?, ?> arg3)
throws Exception {
return (Reference) arg0;
}
}, props);
NamingManager.getObjectInstance("Some dummy data", null, null, env);
}
@Test
public void testContextDotObjectFactories() throws Exception {
env.put(Context.OBJECT_FACTORIES, "org.apache.aries.jndi.ObjectFactoryTest$DummyObjectFactory");
Reference ref = new Reference("anything");
Object obj = NamingManager.getObjectInstance(ref, null, null, env);
assertTrue(obj instanceof String);
assertEquals((String) obj, "pass");
env.remove(Context.OBJECT_FACTORIES);
}
@Test
public void testObjectFactoryThatThrowsIsIgnored() throws Exception {
final ObjectFactory factory = Skeleton.newMock(ObjectFactory.class);
bc.registerService(ObjectFactory.class.getName(), factory, null);
final Skeleton skeleton = Skeleton.getSkeleton(factory);
final MethodCall getObjectInstance = new MethodCall(ObjectFactory.class, "getObjectInstance", Object.class, Name.class, Context.class, Hashtable.class);
skeleton.setThrows(getObjectInstance, new Exception());
Object original = new Object(){};
Object processed = NamingManager.getObjectInstance(original, null, null, env);
skeleton.assertCalled(getObjectInstance);
assertEquals("The original object should be returned despite the object factory throwing an exception", original, processed);
}
public static class DummyObjectFactory implements ObjectFactory {
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?, ?> environment) throws Exception {
// TODO Auto-generated method stub
return new String("pass");
}
}
} | 8,306 |
0 | Create_ds/aries/jndi/jndi-core/src/test/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/test/java/org/apache/aries/jndi/InitialContextTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import junit.framework.Assert;
import org.apache.aries.jndi.startup.Activator;
import org.apache.aries.mocks.BundleContextMock;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.Skeleton;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.service.jndi.JNDIConstants;
import javax.naming.*;
import javax.naming.ldap.Control;
import javax.naming.ldap.ExtendedRequest;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
import javax.naming.spi.ObjectFactory;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.*;
public class InitialContextTest {
private Activator activator;
private BundleContext bc;
private InitialContext ic;
/**
* This method does the setup .
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
@Before
public void setup() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
System.setProperty("org.apache.aries.jndi.disable.builder", "false");
BundleContextMock mock = new BundleContextMock();
mock.addBundle(mock.getBundle());
bc = Skeleton.newMock(mock, BundleContext.class);
activator = new Activator();
activator.start(bc);
}
/**
* Make sure we clear the caches out before the next test.
*/
@After
public void teardown() {
activator.stop(bc);
BundleContextMock.clear();
}
@Test
public void testLookupWithICF() throws NamingException {
InitialContextFactory icf = Skeleton.newMock(InitialContextFactory.class);
bc.registerService(new String[]{InitialContextFactory.class.getName(), icf.getClass().getName()}, icf, (Dictionary) new Properties());
Skeleton.getSkeleton(icf).setReturnValue(new MethodCall(Context.class, "lookup", "/"), Skeleton.newMock(Context.class));
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, icf.getClass().getName());
props.put(JNDIConstants.BUNDLE_CONTEXT, bc);
InitialContext ctx = new InitialContext(props);
Context namingCtx = (Context) ctx.lookup("/");
assertTrue("Context returned isn't the raw naming context: " + namingCtx, Skeleton.isSkeleton(namingCtx));
}
@Test(expected = NoInitialContextException.class)
public void testLookupWithoutICF() throws NamingException {
Properties props = new Properties();
props.put(JNDIConstants.BUNDLE_CONTEXT, bc);
InitialContext ctx = new InitialContext(props);
ctx.lookup("/");
}
@Test
public void testLookupWithoutICFButWithURLLookup() throws NamingException {
ObjectFactory factory = Skeleton.newMock(ObjectFactory.class);
Context ctx = Skeleton.newMock(Context.class);
Skeleton.getSkeleton(factory).setReturnValue(new MethodCall(ObjectFactory.class, "getObjectInstance", Object.class, Name.class, Context.class, Hashtable.class),
ctx);
Skeleton.getSkeleton(ctx).setReturnValue(new MethodCall(Context.class, "lookup", String.class), "someText");
Properties props = new Properties();
props.put(JNDIConstants.JNDI_URLSCHEME, "testURL");
bc.registerService(ObjectFactory.class.getName(), factory, (Dictionary) props);
props = new Properties();
props.put(JNDIConstants.BUNDLE_CONTEXT, bc);
InitialContext initialCtx = new InitialContext(props);
Object someObject = initialCtx.lookup("testURL:somedata");
assertEquals("Expected to be given a string, but got something else.", "someText", someObject);
}
@Test
public void testLookFromLdapICF() throws Exception {
InitialContextFactoryBuilder icf = Skeleton.newMock(InitialContextFactoryBuilder.class);
bc.registerService(new String[]{InitialContextFactoryBuilder.class.getName(), icf.getClass().getName()}, icf, (Dictionary) new Properties());
LdapContext backCtx = Skeleton.newMock(LdapContext.class);
InitialContextFactory fac = Skeleton.newMock(InitialContextFactory.class);
Skeleton.getSkeleton(fac).setReturnValue(
new MethodCall(InitialContextFactory.class, "getInitialContext", Hashtable.class),
backCtx);
Skeleton.getSkeleton(icf).setReturnValue(
new MethodCall(InitialContextFactoryBuilder.class, "createInitialContextFactory", Hashtable.class),
fac);
Properties props = new Properties();
props.put(JNDIConstants.BUNDLE_CONTEXT, bc);
props.put(Context.INITIAL_CONTEXT_FACTORY, "dummy.factory");
InitialLdapContext ilc = new InitialLdapContext(props, new Control[0]);
ExtendedRequest req = Skeleton.newMock(ExtendedRequest.class);
ilc.extendedOperation(req);
Skeleton.getSkeleton(backCtx).assertCalled(new MethodCall(LdapContext.class, "extendedOperation", req));
}
@Test
public void testURLLookup() throws Exception {
ObjectFactory of = new ObjectFactory() {
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
return dummyContext("result");
}
};
registerURLObjectFactory(of, "test");
ic = initialContext();
assertEquals("result", ic.lookup("test:something"));
}
@Test
public void testNoURLContextCaching() throws Exception {
final AtomicBoolean second = new AtomicBoolean(false);
final Context ctx = dummyContext("one");
final Context ctx2 = dummyContext("two");
ObjectFactory of = new ObjectFactory() {
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
if (second.get()) return ctx2;
else {
second.set(true);
return ctx;
}
}
};
registerURLObjectFactory(of, "test");
ic = initialContext();
assertEquals("one", ic.lookup("test:something"));
assertEquals("two", ic.lookup("test:something"));
}
@Test
public void testURLContextErrorPropagation() throws Exception {
ObjectFactory of = new ObjectFactory() {
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?, ?> environment) throws Exception {
throw new Exception("doh");
}
};
registerURLObjectFactory(of, "test");
ic = initialContext();
try {
ic.lookup("test:something");
Assert.fail("Expected NamingException");
} catch (NamingException ne) {
assertNotNull(ne.getCause());
assertEquals("doh", ne.getCause().getMessage());
}
}
/**
* Create a minimal initial context with just the bundle context in the environment
* @return
* @throws Exception
*/
private InitialContext initialContext() throws Exception {
Properties props = new Properties();
props.put(JNDIConstants.BUNDLE_CONTEXT, bc);
InitialContext ic = new InitialContext(props);
return ic;
}
/**
* Registers an ObjectFactory to be used for creating URLContexts for the given scheme
* @param of
* @param scheme
*/
private void registerURLObjectFactory(ObjectFactory of, String scheme) {
Properties props = new Properties();
props.setProperty(JNDIConstants.JNDI_URLSCHEME, "test");
bc.registerService(ObjectFactory.class.getName(), of, (Dictionary) props);
}
/**
* Creates a context that always returns the given object
* @param toReturn
* @return
*/
private Context dummyContext(Object toReturn) {
Context ctx = Skeleton.newMock(Context.class);
Skeleton.getSkeleton(ctx).setReturnValue(new MethodCall(Context.class, "lookup", String.class), toReturn);
Skeleton.getSkeleton(ctx).setReturnValue(new MethodCall(Context.class, "lookup", Name.class), toReturn);
return ctx;
}
}
| 8,307 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/OSGiInitialContextFactoryBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.apache.aries.jndi.startup.Activator;
import org.osgi.framework.BundleContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.NoInitialContextException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
import java.util.Hashtable;
public class OSGiInitialContextFactoryBuilder implements InitialContextFactoryBuilder, InitialContextFactory {
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) {
return this;
}
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
Activator.getAugmenterInvoker().augmentEnvironment(environment);
BundleContext context = Utils.getBundleContext(environment, InitialContext.class);
if (context == null) {
throw new NoInitialContextException("The calling code's BundleContext could not be determined.");
}
Activator.getAugmenterInvoker().unaugmentEnvironment(environment);
return ContextHelper.getInitialContext(context, environment);
}
}
| 8,308 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/DirObjectFactoryHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.BundleContext;
import javax.naming.spi.DirObjectFactory;
public class DirObjectFactoryHelper extends ObjectFactoryHelper implements DirObjectFactory {
public DirObjectFactoryHelper(BundleContext defaultContext, BundleContext callerContext) {
super(defaultContext, callerContext);
}
}
| 8,309 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/URLContextProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
public class URLContextProvider extends ContextProvider {
private final ObjectFactory factory;
private final Hashtable<?, ?> environment;
public URLContextProvider(BundleContext bc, ServiceReference<?> reference, ObjectFactory factory, Hashtable<?, ?> environment) {
super(bc, reference);
this.factory = factory;
this.environment = environment;
}
@Override
public Context getContext() throws NamingException {
try {
return (Context) factory.getObjectInstance(null, null, null, environment);
} catch (Exception e) {
throw (NamingException) new NamingException().initCause(e);
}
}
}
| 8,310 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/SingleContextProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import javax.naming.Context;
import javax.naming.NamingException;
public class SingleContextProvider extends ContextProvider {
private final Context context;
public SingleContextProvider(BundleContext bc, ServiceReference<?> ref, Context ctx) {
super(bc, ref);
this.context = ctx;
}
public Context getContext() {
return context;
}
public void close() throws NamingException {
super.close();
context.close();
}
}
| 8,311 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/ContextProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import javax.naming.Context;
import javax.naming.NamingException;
public abstract class ContextProvider {
private final ServiceReference<?> reference;
private final BundleContext bc;
public ContextProvider(BundleContext ctx, ServiceReference<?> reference) {
bc = ctx;
this.reference = reference;
}
public boolean isValid() {
return (reference.getBundle() != null);
}
public void close() throws NamingException {
}
public abstract Context getContext() throws NamingException;
}
| 8,312 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/JREInitialContextFactoryBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
import java.util.Hashtable;
public class JREInitialContextFactoryBuilder implements InitialContextFactoryBuilder {
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment)
throws NamingException {
String contextFactoryClass = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
if (contextFactoryClass != null) {
return Utils.doPrivileged(() -> {
try {
@SuppressWarnings("unchecked")
Class<? extends InitialContextFactory> clazz = (Class<? extends InitialContextFactory>) ClassLoader.
getSystemClassLoader().loadClass(contextFactoryClass);
return InitialContextFactory.class.cast(clazz.newInstance());
} catch (Exception e) {
return null;
}
});
}
return null;
}
}
| 8,313 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/ContextManagerService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.BundleContext;
import org.osgi.service.jndi.JNDIContextManager;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import java.util.*;
public class ContextManagerService implements JNDIContextManager {
private Set<Context> contexts = Collections.synchronizedSet(new HashSet<Context>());
private BundleContext callerContext;
public ContextManagerService(BundleContext callerContext) {
this.callerContext = callerContext;
}
public void close() {
synchronized (contexts) {
for (Context context : contexts) {
try {
context.close();
} catch (NamingException e) {
// ignore
}
}
contexts.clear();
}
}
public Context newInitialContext() throws NamingException {
return newInitialContext(new Hashtable<Object, Object>());
}
public Context newInitialContext(Map<?, ?> environment) throws NamingException {
return getInitialContext(environment);
}
public DirContext newInitialDirContext() throws NamingException {
return newInitialDirContext(new Hashtable<Object, Object>());
}
public DirContext newInitialDirContext(Map<?, ?> environment) throws NamingException {
return DirContext.class.cast(getInitialContext(environment));
}
private Context getInitialContext(Map<?, ?> environment) throws NamingException {
Hashtable<?, ?> env = Utils.toHashtable(environment);
Context context = ContextHelper.getInitialContext(callerContext, env);
contexts.add(context);
return context;
}
}
| 8,314 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/DelegateContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.BundleContext;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.Control;
import javax.naming.ldap.ExtendedRequest;
import javax.naming.ldap.ExtendedResponse;
import javax.naming.ldap.LdapContext;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class DelegateContext implements DirContext, LdapContext {
private final Hashtable<Object, Object> env = new Hashtable<>();
private final BundleContext bundleContext;
private final Map<String, ContextProvider> urlContexts = new HashMap<>();
private final boolean rebind;
private ContextProvider contextProvider;
public DelegateContext(BundleContext bundleContext, Hashtable<?, ?> theEnv) {
this.bundleContext = bundleContext;
env.putAll(theEnv);
rebind = false;
}
public DelegateContext(BundleContext bundleContext, ContextProvider contextProvider) throws NamingException {
this.bundleContext = bundleContext;
this.contextProvider = contextProvider;
env.putAll(contextProvider.getContext().getEnvironment());
rebind = true;
}
public Object addToEnvironment(String propName, Object propVal) throws NamingException {
Context ctx = getDefaultContext();
if (ctx != null) {
ctx.addToEnvironment(propName, propVal);
}
return env.put(propName, propVal);
}
public void bind(Name name, Object obj) throws NamingException {
findContext(name).bind(name, obj);
}
public void bind(String name, Object obj) throws NamingException {
findContext(name).bind(name, obj);
}
public void close() throws NamingException {
if (contextProvider != null) {
contextProvider.close();
}
for (ContextProvider provider : urlContexts.values()) {
provider.close();
}
urlContexts.clear();
env.clear();
}
public Name composeName(Name name, Name prefix) throws NamingException {
return findContext(name).composeName(name, prefix);
}
public String composeName(String name, String prefix) throws NamingException {
return findContext(name).composeName(name, prefix);
}
public Context createSubcontext(Name name) throws NamingException {
return findContext(name).createSubcontext(name);
}
public Context createSubcontext(String name) throws NamingException {
return findContext(name).createSubcontext(name);
}
public void destroySubcontext(Name name) throws NamingException {
findContext(name).destroySubcontext(name);
}
public void destroySubcontext(String name) throws NamingException {
findContext(name).destroySubcontext(name);
}
public Hashtable<?, ?> getEnvironment() throws NamingException {
Hashtable<Object, Object> theEnv = new Hashtable<>();
theEnv.putAll(env);
return theEnv;
}
public String getNameInNamespace() throws NamingException {
return getDefaultContext().getNameInNamespace();
}
public NameParser getNameParser(Name name) throws NamingException {
return findContext(name).getNameParser(name);
}
public NameParser getNameParser(String name) throws NamingException {
return findContext(name).getNameParser(name);
}
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
return findContext(name).list(name);
}
public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
return findContext(name).list(name);
}
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return findContext(name).listBindings(name);
}
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
return findContext(name).listBindings(name);
}
public Object lookup(Name name) throws NamingException {
return findContext(name).lookup(name);
}
public Object lookup(String name) throws NamingException {
return findContext(name).lookup(name);
}
public Object lookupLink(Name name) throws NamingException {
return findContext(name).lookupLink(name);
}
public Object lookupLink(String name) throws NamingException {
return findContext(name).lookupLink(name);
}
public void rebind(Name name, Object obj) throws NamingException {
findContext(name).rebind(name, obj);
}
public void rebind(String name, Object obj) throws NamingException {
findContext(name).rebind(name, obj);
}
public Object removeFromEnvironment(String propName) throws NamingException {
Context ctx = getDefaultContext();
if (ctx != null) {
ctx.removeFromEnvironment(propName);
}
return env.remove(propName);
}
public void rename(Name oldName, Name newName) throws NamingException {
findContext(oldName).rename(oldName, newName);
}
public void rename(String oldName, String newName) throws NamingException {
findContext(oldName).rename(oldName, newName);
}
public void unbind(Name name) throws NamingException {
findContext(name).unbind(name);
}
public void unbind(String name) throws NamingException {
findContext(name).unbind(name);
}
protected Context findContext(Name name) throws NamingException {
return findContext(name.toString());
}
protected Context findContext(String name) throws NamingException {
Context toReturn;
if (name.contains(":")) {
toReturn = getURLContext(name);
} else {
toReturn = getDefaultContext();
}
return toReturn;
}
private Context getDefaultContext() throws NamingException {
if (rebind) {
if (contextProvider == null || !contextProvider.isValid()) {
contextProvider = ContextHelper.getContextProvider(bundleContext, env);
}
if (contextProvider == null) {
throw new NoInitialContextException();
} else {
return contextProvider.getContext();
}
} else {
throw new NoInitialContextException();
}
}
private Context getURLContext(String name) throws NamingException {
Context ctx = null;
int index = name.indexOf(':');
if (index != -1) {
String scheme = name.substring(0, index);
ContextProvider provider = urlContexts.get(scheme);
if (provider == null || !provider.isValid()) {
provider = ContextHelper.createURLContext(bundleContext, scheme, env);
if (provider != null) urlContexts.put(scheme, provider);
}
if (provider != null) ctx = provider.getContext();
}
if (ctx == null) {
ctx = getDefaultContext();
}
return ctx;
}
public Attributes getAttributes(Name name) throws NamingException {
return ((DirContext) findContext(name)).getAttributes(name);
}
public Attributes getAttributes(String name) throws NamingException {
return ((DirContext) findContext(name)).getAttributes(name);
}
public Attributes getAttributes(Name name, String[] attrIds) throws NamingException {
return ((DirContext) findContext(name)).getAttributes(name, attrIds);
}
public Attributes getAttributes(String name, String[] attrIds) throws NamingException {
return ((DirContext) findContext(name)).getAttributes(name, attrIds);
}
public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException {
((DirContext) findContext(name)).modifyAttributes(name, mod_op, attrs);
}
public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException {
((DirContext) findContext(name)).modifyAttributes(name, mod_op, attrs);
}
public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException {
((DirContext) findContext(name)).modifyAttributes(name, mods);
}
public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException {
((DirContext) findContext(name)).modifyAttributes(name, mods);
}
public void bind(Name name, Object obj, Attributes attrs) throws NamingException {
((DirContext) findContext(name)).bind(name, obj, attrs);
}
public void bind(String name, Object obj, Attributes attrs) throws NamingException {
((DirContext) findContext(name)).bind(name, obj, attrs);
}
public void rebind(Name name, Object obj, Attributes attrs) throws NamingException {
((DirContext) findContext(name)).rebind(name, obj, attrs);
}
public void rebind(String name, Object obj, Attributes attrs) throws NamingException {
((DirContext) findContext(name)).rebind(name, obj, attrs);
}
public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException {
return ((DirContext) findContext(name)).createSubcontext(name, attrs);
}
public DirContext createSubcontext(String name, Attributes attrs) throws NamingException {
return ((DirContext) findContext(name)).createSubcontext(name, attrs);
}
public DirContext getSchema(Name name) throws NamingException {
return ((DirContext) findContext(name)).getSchema(name);
}
public DirContext getSchema(String name) throws NamingException {
return ((DirContext) findContext(name)).getSchema(name);
}
public DirContext getSchemaClassDefinition(Name name) throws NamingException {
return ((DirContext) findContext(name)).getSchemaClassDefinition(name);
}
public DirContext getSchemaClassDefinition(String name) throws NamingException {
return ((DirContext) findContext(name)).getSchemaClassDefinition(name);
}
public NamingEnumeration<SearchResult> search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn) throws NamingException {
return ((DirContext) findContext(name))
.search(name, matchingAttributes, attributesToReturn);
}
public NamingEnumeration<SearchResult> search(String name,
Attributes matchingAttributes,
String[] attributesToReturn) throws NamingException {
return ((DirContext) findContext(name))
.search(name, matchingAttributes, attributesToReturn);
}
public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes)
throws NamingException {
return ((DirContext) findContext(name)).search(name, matchingAttributes);
}
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes)
throws NamingException {
return ((DirContext) findContext(name)).search(name, matchingAttributes);
}
public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons)
throws NamingException {
return ((DirContext) findContext(name)).search(name, filter, cons);
}
public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons)
throws NamingException {
return ((DirContext) findContext(name)).search(name, filter, cons);
}
public NamingEnumeration<SearchResult> search(Name name,
String filterExpr,
Object[] filterArgs,
SearchControls cons) throws NamingException {
return ((DirContext) findContext(name)).search(name, filterExpr, filterArgs, cons);
}
public NamingEnumeration<SearchResult> search(String name,
String filterExpr,
Object[] filterArgs,
SearchControls cons) throws NamingException {
return ((DirContext) findContext(name)).search(name, filterExpr, filterArgs, cons);
}
public ExtendedResponse extendedOperation(ExtendedRequest request)
throws NamingException {
return ((LdapContext) getDefaultContext()).extendedOperation(request);
}
public Control[] getConnectControls() throws NamingException {
return ((LdapContext) getDefaultContext()).getConnectControls();
}
public Control[] getRequestControls() throws NamingException {
return ((LdapContext) getDefaultContext()).getRequestControls();
}
public void setRequestControls(Control[] requestControls)
throws NamingException {
((LdapContext) getDefaultContext()).setRequestControls(requestControls);
}
public Control[] getResponseControls() throws NamingException {
return ((LdapContext) getDefaultContext()).getResponseControls();
}
public LdapContext newInstance(Control[] requestControls)
throws NamingException {
return ((LdapContext) getDefaultContext()).newInstance(requestControls);
}
public void reconnect(Control[] connCtls) throws NamingException {
((LdapContext) getDefaultContext()).reconnect(connCtls);
}
} | 8,315 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/ContextManagerServiceFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
public class ContextManagerServiceFactory implements ServiceFactory<ContextManagerService> {
public ContextManagerService getService(Bundle bundle, ServiceRegistration<ContextManagerService> registration) {
return new ContextManagerService(bundle.getBundleContext());
}
public void ungetService(Bundle bundle, ServiceRegistration<ContextManagerService> registration, ContextManagerService service) {
service.close();
}
}
| 8,316 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/Utils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleReference;
import org.osgi.service.jndi.JNDIConstants;
import javax.naming.NamingException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.function.Supplier;
/**
*/
public final class Utils {
/**
* Ensure no one constructs us
*/
private Utils() {
throw new RuntimeException();
}
/**
* @param env
* @return the bundle context for the caller.
* @throws NamingException
*/
public static BundleContext getBundleContext(final Map<?, ?> env, final Class<?> namingClass) {
return doPrivileged(() -> doGetBundleContext(env, namingClass));
}
private static BundleContext doGetBundleContext(Map<?, ?> env, Class<?> namingClass) {
BundleContext result;
Object bc = (env == null) ? null : env.get(JNDIConstants.BUNDLE_CONTEXT);
if (bc != null && bc instanceof BundleContext) {
result = (BundleContext) bc;
} else {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
result = getBundleContext(cl);
}
if (result == null) {
StackFinder finder = new StackFinder();
Class<?>[] classStack = finder.getClassContext();
// working from the root of the stack look for the first instance in the stack of this class
int i = classStack.length - 1;
for (; i >= 0; i--) {
if (namingClass.isAssignableFrom(classStack[i])) {
break;
}
}
// then go to the parent of the namingClass down the stack until we find a BundleContext
for (i++; i < classStack.length && result == null; i++) {
result = getBundleContext(classStack[i].getClassLoader());
}
}
return result;
}
private static BundleContext getBundleContext(ClassLoader cl2) {
ClassLoader cl = cl2;
BundleContext result = null;
while (result == null && cl != null) {
if (cl instanceof BundleReference) {
Bundle b = ((BundleReference) cl).getBundle();
result = b.getBundleContext();
if (result == null) {
try {
b.start();
result = b.getBundleContext();
} catch (BundleException e) {
}
break;
}
} else if (cl != null) {
cl = cl.getParent();
}
}
return result;
}
public static String getSystemProperty(final String key, final String defaultValue) {
return doPrivileged(() -> System.getProperty(key, defaultValue));
}
public static Hashtable<?, ?> toHashtable(Map<?, ?> map) {
Hashtable<?, ?> env;
if (map instanceof Hashtable<?, ?>) {
env = (Hashtable<?, ?>) map;
} else if (map == null) {
env = new Hashtable<>();
} else {
env = new Hashtable<Object, Object>(map);
}
return env;
}
public static <T> T doPrivileged(Supplier<T> action) {
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged((PrivilegedAction<T>) action::get);
} else {
return action.get();
}
}
public interface Callable<V, E extends Exception> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws E if unable to compute a result
*/
V call() throws E;
}
@SuppressWarnings("unchecked")
public static <T, E extends Exception> T doPrivilegedE(Callable<T, E> action) throws E {
if (System.getSecurityManager() != null) {
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<T>) action::call);
} catch (PrivilegedActionException e) {
throw (E) e.getException();
}
} else {
return action.call();
}
}
private static class StackFinder extends SecurityManager {
public Class<?>[] getClassContext() {
return super.getClassContext();
}
}
public static <U, V> Iterator<V> map(Iterator<U> iterator, Function<U, V> mapper) {
return new MappedIterator<>(iterator, mapper);
}
private static class MappedIterator<U, V> implements Iterator<V> {
private final Iterator<U> iterator;
private final Function<U, V> mapper;
private V nextElement;
private boolean hasNext;
public MappedIterator(Iterator<U> iterator, Function<U, V> mapper) {
this.iterator = iterator;
this.mapper = mapper;
nextMatch();
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public V next() {
if (!hasNext) {
throw new NoSuchElementException();
}
return nextMatch();
}
private V nextMatch() {
V oldMatch = nextElement;
while (iterator.hasNext()) {
V o = mapper.apply(iterator.next());
if (o != null) {
hasNext = true;
nextElement = o;
return oldMatch;
}
}
hasNext = false;
return oldMatch;
}
}
}
| 8,317 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/ObjectFactoryHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.apache.aries.jndi.startup.Activator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import javax.naming.*;
import javax.naming.directory.Attributes;
import javax.naming.spi.DirObjectFactory;
import javax.naming.spi.ObjectFactory;
import javax.naming.spi.ObjectFactoryBuilder;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.osgi.service.jndi.JNDIConstants.JNDI_URLSCHEME;
public class ObjectFactoryHelper implements ObjectFactory {
private static final Logger logger = Logger.getLogger(ObjectFactoryHelper.class.getName());
protected BundleContext defaultContext;
protected BundleContext callerContext;
public ObjectFactoryHelper(BundleContext defaultContext, BundleContext callerContext) {
this.defaultContext = defaultContext;
this.callerContext = callerContext;
}
public Object getObjectInstance(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment) throws Exception {
return getObjectInstance(obj, name, nameCtx, environment, null);
}
public Object getObjectInstance(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment,
Attributes attrs) throws Exception {
return Utils.doPrivilegedE(() -> doGetObjectInstance(obj, name, nameCtx, environment, attrs));
}
private Object doGetObjectInstance(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment,
Attributes attrs) throws Exception {
// Step 1
if (obj instanceof Referenceable) {
obj = ((Referenceable) obj).getReference();
}
Object result = obj;
// Step 2
if (obj instanceof Reference) {
Reference ref = (Reference) obj;
String className = ref.getFactoryClassName();
if (className != null) {
// Step 3
result = getObjectInstanceUsingClassName(obj, className, obj, name, nameCtx, environment, attrs);
} else {
// Step 4 - look, assuming url string ref addrs, for a url context object factory.
result = getObjectInstanceUsingRefAddress(ref.getAll(), obj, name, nameCtx, environment, attrs);
}
}
// Step 4
if (result == null || result == obj) {
result = getObjectInstanceUsingObjectFactoryBuilders(obj, name, nameCtx, environment, attrs);
}
// Step 5
if (result == null || result == obj) {
if (!(obj instanceof Reference) || ((Reference) obj).getFactoryClassName() == null) {
result = getObjectInstanceUsingObjectFactories(obj, name, nameCtx, environment, attrs);
}
}
// Extra, non-standard, bonus step. If javax.naming.OBJECT_FACTORIES is set as
// a property in the environment, use its value to construct additional object factories.
// Added under Aries-822, with reference
// to https://www.osgi.org/bugzilla/show_bug.cgi?id=138
if (result == null || result == obj) {
result = getObjectInstanceViaContextDotObjectFactories(obj, name, nameCtx, environment, attrs);
}
return (result == null) ? obj : result;
}
private Object getObjectInstanceUsingObjectFactories(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment,
Attributes attrs) throws Exception {
for (ServiceReference<ObjectFactory> ref : Activator.getReferences(callerContext, ObjectFactory.class)) {
if (canCallObjectFactory(obj, ref)) {
ObjectFactory factory = Activator.getService(callerContext, ref);
if (factory != null) {
try {
Object result = getObjectFromFactory(obj, name, nameCtx, environment, attrs, factory);
// if the result comes back and is not null and not the reference
// object then we should return the result, so break out of the
// loop we are in.
if (result != null && result != obj) {
return result;
}
} catch (Exception ignored) {} // only care about factories that CAN transform this object
}
}
}
return obj;
}
private boolean canCallObjectFactory(Object obj, ServiceReference ref) {
if (obj instanceof Reference) return true;
Object prop = ref.getProperty("aries.object.factory.requires.reference");
// if the ObjectFactory needs a reference, then give up straight away
if (Boolean.TRUE.equals(prop)) return false;
// ObjectFactory services with an osgi.jndi.url.scheme property are only for converting URLs
if (ref.getProperty(JNDI_URLSCHEME) != null) return false;
// TODO: ObjectFactory services registered with their implementation class names are for References that specify the ObjectFactory class
// We've eliminated all other possibilities, so this factory IS callable.
return true;
}
private Object getObjectInstanceUsingClassName(Object reference,
String className,
Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment,
Attributes attrs)
throws Exception {
Object result = null;
ObjectFactory factory = ObjectFactoryHelper.findObjectFactoryByClassName(defaultContext, className);
if (factory != null) {
result = getObjectFromFactory(reference, name, nameCtx, environment, attrs, factory);
}
return (result == null) ? obj : result;
}
private Object getObjectInstanceUsingObjectFactoryBuilders(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment,
Attributes attrs)
throws Exception {
ObjectFactory factory = null;
for (ObjectFactoryBuilder ofb : Activator.getServices(callerContext, ObjectFactoryBuilder.class)) {
try {
factory = ofb.createObjectFactory(obj, environment);
} catch (NamingException e) {
// TODO: log it
}
if (factory != null) {
break;
}
}
Object result = null;
if (factory != null) {
result = getObjectFromFactory(obj, name, nameCtx, environment, attrs, factory);
}
return (result == null) ? obj : result;
}
/*
* Attempt to obtain an Object instance via the java.naming.factory.object property
*/
private Object getObjectInstanceViaContextDotObjectFactories(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment,
Attributes attrs) throws Exception {
Object result = null;
String factories = (String) environment.get(Context.OBJECT_FACTORIES);
if (factories != null && factories.length() > 0) {
String[] candidates = factories.split(":");
ClassLoader cl = Utils.doPrivileged(Thread.currentThread()::getContextClassLoader);
for (String cand : candidates) {
ObjectFactory factory;
try {
@SuppressWarnings("unchecked")
Class<ObjectFactory> clz = (Class<ObjectFactory>) cl.loadClass(cand);
factory = clz.newInstance();
} catch (Exception e) {
if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Exception instantiating factory: " + e);
continue;
}
if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "cand=" + cand + " factory=" + factory);
if (factory != null) {
result = getObjectFromFactory(obj, name, nameCtx, environment, attrs, factory);
}
if (result != null && result != obj) break;
}
}
if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "result = " + result);
return (result == null) ? obj : result;
}
private Object getObjectInstanceUsingRefAddress(Enumeration<RefAddr> addresses,
Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment,
Attributes attrs)
throws Exception {
while (addresses.hasMoreElements()) {
RefAddr address = addresses.nextElement();
if (address instanceof StringRefAddr && "URL".equals(address.getType())) {
String urlScheme = getUrlScheme((String) address.getContent());
ServicePair<ObjectFactory> factoryService = ContextHelper.getURLObjectFactory(callerContext, urlScheme, environment);
if (factoryService != null) {
ObjectFactory factory = factoryService.get();
String value = (String) address.getContent();
Object result = getObjectFromFactory(value, name, nameCtx, environment, attrs, factory);
// if the result comes back and is not null and not the reference
// object then we should return the result, so break out of the
// loop we are in.
if (result != null && result != obj) {
return result;
}
}
}
}
return obj;
}
private Object getObjectFromFactory(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment, Attributes attrs, ObjectFactory factory) throws Exception {
Object result;
if (factory instanceof DirObjectFactory) {
result = ((DirObjectFactory) factory).getObjectInstance(obj, name, nameCtx, environment, attrs);
} else {
result = factory.getObjectInstance(obj, name, nameCtx, environment);
}
return result;
}
private static String getUrlScheme(String name) {
String scheme = name;
int index = name.indexOf(':');
if (index != -1) {
scheme = name.substring(0, index);
}
return scheme;
}
private static ObjectFactory findObjectFactoryByClassName(final BundleContext ctx, final String className) {
return Utils.doPrivileged(() -> {
ServiceReference<?> ref = ctx.getServiceReference(className);
if (ref != null) {
return (ObjectFactory) Activator.getService(ctx, ref);
}
return null;
});
}
} | 8,318 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/ProviderAdminService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.BundleContext;
import org.osgi.service.jndi.JNDIProviderAdmin;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.directory.Attributes;
import java.util.Hashtable;
import java.util.Map;
public class ProviderAdminService implements JNDIProviderAdmin {
private DirObjectFactoryHelper helper;
public ProviderAdminService(BundleContext defaultContext, BundleContext callerContext) {
helper = new DirObjectFactoryHelper(defaultContext, callerContext);
}
public Object getObjectInstance(Object obj,
Name name,
Context context,
Map<?, ?> environment)
throws Exception {
Hashtable<?, ?> env = Utils.toHashtable(environment);
return helper.getObjectInstance(obj, name, context, env);
}
public Object getObjectInstance(Object obj,
Name name,
Context context,
Map<?, ?> environment,
Attributes attributes)
throws Exception {
Hashtable<?, ?> env = Utils.toHashtable(environment);
return helper.getObjectInstance(obj, name, context, env, attributes);
}
public void close() {
}
}
| 8,319 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/ProviderAdminServiceFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
public class ProviderAdminServiceFactory implements ServiceFactory<ProviderAdminService> {
private BundleContext defaultContext;
public ProviderAdminServiceFactory(BundleContext defaultContext) {
this.defaultContext = defaultContext;
}
public ProviderAdminService getService(Bundle bundle, ServiceRegistration registration) {
return new ProviderAdminService(defaultContext, bundle.getBundleContext());
}
public void ungetService(Bundle bundle, ServiceRegistration registration, ProviderAdminService service) {
service.close();
}
}
| 8,320 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/OSGiObjectFactoryBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.apache.aries.jndi.startup.Activator;
import org.osgi.framework.BundleContext;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.spi.*;
import java.util.Hashtable;
public class OSGiObjectFactoryBuilder implements ObjectFactoryBuilder, ObjectFactory, DirObjectFactory {
private BundleContext defaultContext;
public OSGiObjectFactoryBuilder(BundleContext ctx) {
defaultContext = ctx;
}
public ObjectFactory createObjectFactory(Object obj, Hashtable<?, ?> environment) {
return this;
}
public Object getObjectInstance(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment) throws Exception {
return getObjectInstance(obj, name, nameCtx, environment, null);
}
public Object getObjectInstance(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment,
Attributes attrs) throws Exception {
if (environment == null) {
environment = new Hashtable();
}
BundleContext callerContext = getCallerBundleContext(environment);
if (callerContext == null) {
return obj;
}
DirObjectFactoryHelper helper = new DirObjectFactoryHelper(defaultContext, callerContext);
return helper.getObjectInstance(obj, name, nameCtx, environment, attrs);
}
private BundleContext getCallerBundleContext(Hashtable<?, ?> environment) {
Activator.getAugmenterInvoker().augmentEnvironment(environment);
BundleContext context = Utils.getBundleContext(environment, NamingManager.class);
if (context == null) {
context = Utils.getBundleContext(environment, DirectoryManager.class);
}
Activator.getAugmenterInvoker().unaugmentEnvironment(environment);
return context;
}
}
| 8,321 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/AugmenterInvokerImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.apache.aries.jndi.spi.AugmenterInvoker;
import org.apache.aries.jndi.spi.EnvironmentAugmentation;
import org.apache.aries.jndi.spi.EnvironmentUnaugmentation;
import org.apache.aries.jndi.startup.Activator;
import org.osgi.framework.BundleContext;
import java.util.Hashtable;
public class AugmenterInvokerImpl implements AugmenterInvoker {
private final BundleContext context;
public AugmenterInvokerImpl(BundleContext context) {
this.context = context;
}
public void augmentEnvironment(Hashtable<?, ?> environment) {
for (EnvironmentAugmentation svc : Activator.getServices(context, EnvironmentAugmentation.class)) {
svc.augmentEnvironment(environment);
}
}
public void unaugmentEnvironment(Hashtable<?, ?> environment) {
for (EnvironmentUnaugmentation svc : Activator.getServices(context, EnvironmentUnaugmentation.class)) {
svc.unaugmentEnvironment(environment);
}
}
}
| 8,322 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/ServicePair.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.apache.aries.jndi.startup.Activator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import java.util.function.Supplier;
public class ServicePair<T> implements Supplier<T> {
private BundleContext ctx;
private ServiceReference<?> ref;
private T svc;
public ServicePair(BundleContext context, ServiceReference<T> serviceRef) {
this.ctx = context;
this.ref = serviceRef;
}
public ServicePair(BundleContext context, ServiceReference<?> serviceRef, T service) {
this.ctx = context;
this.ref = serviceRef;
this.svc = service;
}
@SuppressWarnings("unchecked")
public T get() {
return svc != null ? svc : ref != null ? (T) Activator.getService(ctx, ref) : null;
}
public boolean isValid() {
return ref.getBundle() != null;
}
public ServiceReference<?> getReference() {
return ref;
}
}
| 8,323 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/ContextHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi;
import org.apache.aries.jndi.startup.Activator;
import org.apache.aries.jndi.urls.URLObjectFactoryFinder;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.NoInitialContextException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
import javax.naming.spi.ObjectFactory;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Provides helper methods for the DelegateContext. This provides the methods so
* there can be many DelegateContexts, but few service trackers.
*/
public final class ContextHelper {
private static final Logger logger = Logger.getLogger(ContextHelper.class.getName());
/**
* Ensure no one constructs us
*/
private ContextHelper() {
throw new RuntimeException();
}
/**
* This method is used to create a URL Context. It does this by looking for
* the URL context's ObjectFactory in the service registry.
*/
public static ContextProvider createURLContext(final BundleContext context,
final String urlScheme,
final Hashtable<?, ?> env)
throws NamingException {
ServicePair<ObjectFactory> urlObjectFactory = getURLObjectFactory(context, urlScheme, env);
if (urlObjectFactory != null) {
ObjectFactory factory = urlObjectFactory.get();
if (factory != null) {
return new URLContextProvider(context, urlObjectFactory.getReference(), factory, env);
}
}
// if we got here then we couldn't find a URL context factory so return null.
return null;
}
public static ServicePair<ObjectFactory> getURLObjectFactory(final BundleContext ctx, String urlScheme, Hashtable<?, ?> environment)
throws NamingException {
ServicePair<ObjectFactory> result = null;
ServiceReference<ObjectFactory> ref = Activator.getUrlFactory(urlScheme);
if (ref == null) {
Collection<ServiceReference<URLObjectFactoryFinder>> refs = Activator.getURLObjectFactoryFinderServices();
for (final ServiceReference<URLObjectFactoryFinder> finderRef : refs) {
URLObjectFactoryFinder finder = Activator.getService(ctx, finderRef);
if (finder != null) {
ObjectFactory f = finder.findFactory(urlScheme, environment);
if (f != null) {
result = new ServicePair<>(ctx, finderRef, f);
break;
}
}
}
} else {
result = new ServicePair<>(ctx, ref);
}
return result;
}
public static Context getInitialContext(BundleContext context, Hashtable<?, ?> environment)
throws NamingException {
final Bundle jndiBundle = FrameworkUtil.getBundle(ContextHelper.class);
// if we are outside OSGi (like in our unittests) then we would get Null back here, so just make sure we don't.
if (jndiBundle != null) {
BundleContext jndiBundleContext = Utils.doPrivileged(jndiBundle::getBundleContext);
if (!jndiBundleContext.getClass().equals(context.getClass())) {
//the context passed in must have come from a child framework
//use the parent context instead
context = jndiBundleContext;
}
}
ContextProvider provider = getContextProvider(context, environment);
if (provider != null) {
return new DelegateContext(context, provider);
} else {
String contextFactoryClass = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
if (contextFactoryClass == null) {
return new DelegateContext(context, environment);
} else {
throw new NoInitialContextException("Unable to find the InitialContextFactory " + contextFactoryClass + ".");
}
}
}
public static ContextProvider getContextProvider(BundleContext context,
Hashtable<?, ?> environment)
throws NamingException {
ContextProvider provider = null;
String contextFactoryClass = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
if (contextFactoryClass == null) {
// 1. get ContextFactory using builder
provider = getInitialContextUsingBuilder(context, environment)
// 2. lookup all ContextFactory services
.orElseGet(() -> getInitialContextUsingFactoryServices(context, environment)
.orElse(null));
} else {
// 1. lookup using specified InitialContextFactory
ServiceReference<InitialContextFactory> ref = Activator.getInitialContextFactory(contextFactoryClass);
if (ref != null) {
InitialContextFactory factory = Activator.getService(context, ref);
if (factory != null) {
Context initialContext = factory.getInitialContext(environment);
provider = new SingleContextProvider(context, ref, initialContext);
}
}
// 2. get ContextFactory using builder
if (provider == null) {
provider = getInitialContextUsingBuilder(context, environment).orElse(null);
}
}
return provider;
}
private static Optional<ContextProvider> getInitialContextUsingFactoryServices(BundleContext context, Hashtable<?, ?> environment) {
for (ServiceReference<InitialContextFactory> reference : Activator.getInitialContextFactoryServices()) {
try {
InitialContextFactory factory = Activator.getService(context, reference);
Context initialContext = factory.getInitialContext(environment);
if (initialContext != null) {
return Optional.of(new SingleContextProvider(context, reference, initialContext));
}
} catch (NamingException e) {
// ignore this, if the builder fails we want to move onto the next one
logger.log(Level.FINE, "Exception caught", e);
}
}
return Optional.empty();
}
private static Optional<ContextProvider> getInitialContextUsingBuilder(BundleContext context,
Hashtable<?, ?> environment) throws NamingException {
for (ServiceReference<InitialContextFactoryBuilder> ref : Activator.getInitialContextFactoryBuilderServices()) {
InitialContextFactoryBuilder builder = Activator.getService(context, ref);
InitialContextFactory factory=null;
try {
factory = builder.createInitialContextFactory(environment);
} catch (NamingException ne) {
// ignore this, if the builder fails we want to move onto the next one
logger.log(Level.FINE, "Exception caught", ne);
} catch (NullPointerException npe) {
logger.log(Level.SEVERE, "NPE caught in ContextHelper.getInitialContextUsingBuilder. context=" + context + " ref=" + ref);
throw npe;
}
if (factory != null) {
return Optional.of(new SingleContextProvider(context, ref, factory.getInitialContext(environment)));
}
}
return Optional.empty();
}
}
| 8,324 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/tracker/CachingServiceTracker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.tracker;
import org.apache.aries.jndi.Utils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import java.util.*;
import java.util.function.Function;
public class CachingServiceTracker<S> extends ServiceTracker<S, ServiceReference<S>> {
/** The cached references */
private volatile Map<String, ServiceReference<S>> cache;
/** The funtion to obtain the identifiers */
private final Function<ServiceReference<S>, Iterable<String>> properties;
public CachingServiceTracker(BundleContext context, Class<S> clazz) {
this(context, clazz, ref -> Collections.emptyList());
}
public CachingServiceTracker(BundleContext context, Class<S> clazz, Function<ServiceReference<S>, Iterable<String>> properties) {
super(context, clazz, null);
this.properties = properties;
open();
}
public ServiceReference<S> find(String identifier) {
if (cache == null) {
synchronized (this) {
Map<String, ServiceReference<S>> c = new HashMap<>();
if (cache == null) {
for (ServiceReference<S> ref : getReferences()) {
for (String key : properties.apply(ref)) {
c.putIfAbsent(key, ref);
}
}
cache = c;
}
}
}
return cache.get(identifier);
}
public List<ServiceReference<S>> getReferences() {
ServiceReference<S>[] refs = Utils.doPrivileged(this::getServiceReferences);
if (refs != null) {
Arrays.sort(refs, Comparator.reverseOrder());
return Arrays.asList(refs);
} else {
return Collections.emptyList();
}
}
public synchronized ServiceReference<S> addingService(ServiceReference<S> reference) {
cache = null;
return reference;
}
public synchronized void removedService(ServiceReference<S> reference, ServiceReference<S> service) {
cache = null;
}
public void modifiedService(ServiceReference<S> reference, ServiceReference<S> service) {
cache = null;
}
}
| 8,325 |
0 | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-core/src/main/java/org/apache/aries/jndi/startup/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.jndi.startup;
import org.apache.aries.jndi.*;
import org.apache.aries.jndi.spi.AugmenterInvoker;
import org.apache.aries.jndi.tracker.CachingServiceTracker;
import org.apache.aries.jndi.urls.URLObjectFactoryFinder;
import org.osgi.framework.*;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.service.jndi.JNDIConstants;
import org.osgi.service.jndi.JNDIContextManager;
import org.osgi.service.jndi.JNDIProviderAdmin;
import org.osgi.util.tracker.BundleTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.NamingException;
import javax.naming.spi.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* The activator for this bundle makes sure the static classes in it are
* driven so they can do their magic stuff properly.
*/
public class Activator implements BundleActivator {
private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class.getName());
private static final String DISABLE_BUILDER = "org.apache.aries.jndi.disable.builder";
private static final String FORCE_BUILDER = "org.apache.aries.jndi.force.builder";
private static volatile Activator instance;
private BundleTracker<ServiceCache> bundleServiceCaches;
private CachingServiceTracker<InitialContextFactoryBuilder> icfBuilders;
private CachingServiceTracker<URLObjectFactoryFinder> urlObjectFactoryFinders;
private CachingServiceTracker<InitialContextFactory> initialContextFactories;
private CachingServiceTracker<ObjectFactory> objectFactories;
private AugmenterInvoker augmenterInvoker;
private InitialContextFactoryBuilder originalICFBuilder;
private OSGiInitialContextFactoryBuilder icfBuilder;
private ObjectFactoryBuilder originalOFBuilder;
private OSGiObjectFactoryBuilder ofBuilder;
public static Collection<ServiceReference<InitialContextFactoryBuilder>> getInitialContextFactoryBuilderServices() {
return instance.icfBuilders.getReferences();
}
public static Collection<ServiceReference<InitialContextFactory>> getInitialContextFactoryServices() {
return instance.initialContextFactories.getReferences();
}
public static Collection<ServiceReference<URLObjectFactoryFinder>> getURLObjectFactoryFinderServices() {
return instance.urlObjectFactoryFinders.getReferences();
}
public static ServiceReference<ObjectFactory> getUrlFactory(String scheme) {
return instance.objectFactories.find(scheme);
}
public static ServiceReference<InitialContextFactory> getInitialContextFactory(String interfaceName) {
return instance.initialContextFactories.find(interfaceName);
}
public static AugmenterInvoker getAugmenterInvoker() {
return instance.augmenterInvoker;
}
public static <T> T getService(BundleContext context, ServiceReference<T> ref) {
ServiceCache cache = getServiceCache(context);
return cache.getService(ref);
}
public static <T> Collection<ServiceReference<T>> getReferences(BundleContext context, Class<T> clazz) {
ServiceCache cache = getServiceCache(context);
return cache.getReferences(clazz);
}
public static <T> Iterable<T> getServices(BundleContext context, Class<T> clazz) {
ServiceCache cache = getServiceCache(context);
if (cache == null) {
cache = new ServiceCache(context);
}
Collection<ServiceReference<T>> refs = cache.getReferences(clazz);
return () -> Utils.map(refs.iterator(), ref -> Activator.getService(context, ref));
}
private static ServiceCache getServiceCache(BundleContext context) {
ServiceCache cache = instance.bundleServiceCaches.getObject(context.getBundle());
if (cache == null) {
cache = new ServiceCache(context);
}
return cache;
}
public void start(BundleContext context) {
instance = this;
BundleContext trackerBundleContext;
/* Use system context to allow trackers full bundle/service visibility. */
if ( !Boolean.getBoolean("org.apache.aries.jndi.trackersUseLocalContext") ){
trackerBundleContext = context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).getBundleContext();
if (trackerBundleContext==null) {
throw new IllegalStateException("Bundle could not aquire system bundle context.");
}
}
else {
trackerBundleContext = context;
}
bundleServiceCaches =
new BundleTracker<ServiceCache>(trackerBundleContext, Bundle.STARTING | Bundle.ACTIVE | Bundle.STOPPING , null) {
@Override
public ServiceCache addingBundle(Bundle bundle, BundleEvent event) {
return new ServiceCache(bundle.getBundleContext());
}
@Override
public void modifiedBundle(Bundle bundle, BundleEvent event, ServiceCache object) {
}
};
bundleServiceCaches.open();
initialContextFactories = new CachingServiceTracker<>(trackerBundleContext, InitialContextFactory.class, Activator::getInitialContextFactoryInterfaces);
objectFactories = new CachingServiceTracker<>(trackerBundleContext, ObjectFactory.class, Activator::getObjectFactorySchemes);
icfBuilders = new CachingServiceTracker<>(trackerBundleContext, InitialContextFactoryBuilder.class);
urlObjectFactoryFinders = new CachingServiceTracker<>(trackerBundleContext, URLObjectFactoryFinder.class);
if (!isPropertyEnabled(context, DISABLE_BUILDER)) {
try {
OSGiInitialContextFactoryBuilder builder = new OSGiInitialContextFactoryBuilder();
try {
NamingManager.setInitialContextFactoryBuilder(builder);
} catch (IllegalStateException e) {
// use reflection to force the builder to be used
if (isPropertyEnabled(context, FORCE_BUILDER)) {
originalICFBuilder = swapStaticField(InitialContextFactoryBuilder.class, builder);
}
}
icfBuilder = builder;
} catch (NamingException e) {
LOGGER.debug("A failure occurred when attempting to register an InitialContextFactoryBuilder with the NamingManager. " +
"Support for calling new InitialContext() will not be enabled.", e);
} catch (IllegalStateException e) {
// Log the problem at info level, but only log the exception at debug level, as in many cases this is not a real issue and people
// don't want to see stack traces at info level when everything it working as expected.
String msg = "It was not possible to register an InitialContextFactoryBuilder with the NamingManager because " +
"another builder called " + getClassName(InitialContextFactoryBuilder.class) + " was already registered. Support for calling new InitialContext() will not be enabled.";
LOGGER.info(msg);
LOGGER.debug(msg, e);
}
try {
OSGiObjectFactoryBuilder builder = new OSGiObjectFactoryBuilder(context);
try {
NamingManager.setObjectFactoryBuilder(builder);
} catch (IllegalStateException e) {
// use reflection to force the builder to be used
if (isPropertyEnabled(context, FORCE_BUILDER)) {
originalOFBuilder = swapStaticField(ObjectFactoryBuilder.class, builder);
}
}
ofBuilder = builder;
} catch (NamingException e) {
LOGGER.info("A failure occurred when attempting to register an ObjectFactoryBuilder with the NamingManager. " +
"Looking up certain objects may not work correctly.", e);
} catch (IllegalStateException e) {
// Log the problem at info level, but only log the exception at debug level, as in many cases this is not a real issue and people
// don't want to see stack traces at info level when everything it working as expected.
String msg = "It was not possible to register an ObjectFactoryBuilder with the NamingManager because " +
"another builder called " + getClassName(ObjectFactoryBuilder.class) + " was already registered. Looking up certain objects may not work correctly.";
LOGGER.info(msg);
LOGGER.debug(msg, e);
}
}
context.registerService(JNDIProviderAdmin.class.getName(), new ProviderAdminServiceFactory(context), null);
context.registerService(InitialContextFactoryBuilder.class.getName(), new JREInitialContextFactoryBuilder(), null);
context.registerService(JNDIContextManager.class.getName(), new ContextManagerServiceFactory(), null);
context.registerService(AugmenterInvoker.class.getName(), augmenterInvoker = new AugmenterInvokerImpl(context), null);
}
public void stop(BundleContext context) {
bundleServiceCaches.close();
/*
* Try to reset the InitialContextFactoryBuilder and ObjectFactoryBuilder
* on the NamingManager.
*/
if (icfBuilder != null) {
swapStaticField(InitialContextFactoryBuilder.class, originalICFBuilder);
}
if (ofBuilder != null) {
swapStaticField(ObjectFactoryBuilder.class, originalOFBuilder);
}
icfBuilders.close();
urlObjectFactoryFinders.close();
objectFactories.close();
initialContextFactories.close();
instance = null;
}
private boolean isPropertyEnabled(BundleContext context, String key) {
String value = context.getProperty(key);
if ("false".equals(value)) return false;
if ("no".equals(value)) return false;
if (null != value) return true;
Object revision = context.getBundle().adapt(BundleRevision.class);
// in a unit test adapt() may return an incompatible object
if (!!! (revision instanceof BundleRevision)) return false;
final BundleRevision bundleRevision = (BundleRevision) revision;
return bundleRevision.getDeclaredCapabilities(key).size() > 0;
}
private String getClassName(Class<?> expectedType) {
try {
for (Field field : NamingManager.class.getDeclaredFields()) {
if (expectedType.equals(field.getType())) {
field.setAccessible(true);
Object icf = field.get(null);
return icf.getClass().getName();
}
}
} catch (Throwable t) {
// Ignore
}
return "";
}
/*
* There are no public API to reset the InitialContextFactoryBuilder or
* ObjectFactoryBuilder on the NamingManager so try to use reflection.
*/
private static <T> T swapStaticField(Class<T> expectedType, Object value) throws IllegalStateException {
try {
for (Field field : NamingManager.class.getDeclaredFields()) {
if (expectedType.equals(field.getType())) {
field.setAccessible(true);
T original = expectedType.cast(field.get(null));
field.set(null, value);
return original;
}
}
} catch (Throwable t) {
// Ignore
LOGGER.debug("Error setting field.", t);
throw new IllegalStateException(t);
}
throw new IllegalStateException("Error setting field: no field found for type " + expectedType);
}
private static List<String> getInitialContextFactoryInterfaces(ServiceReference<InitialContextFactory> ref) {
String[] interfaces = (String[]) ref.getProperty(Constants.OBJECTCLASS);
List<String> resultList = new ArrayList<>();
for (String interfaceName : interfaces) {
if (!InitialContextFactory.class.getName().equals(interfaceName)) {
resultList.add(interfaceName);
}
}
return resultList;
}
private static List<String> getObjectFactorySchemes(ServiceReference<ObjectFactory> reference) {
Object scheme = reference.getProperty(JNDIConstants.JNDI_URLSCHEME);
List<String> result;
if (scheme instanceof String) {
result = new ArrayList<>();
result.add((String) scheme);
} else if (scheme instanceof String[]) {
result = Arrays.asList((String[]) scheme);
} else {
result = Collections.emptyList();
}
return result;
}
private static class ServiceCache {
private final BundleContext context;
private final Map<ServiceReference<?>, Object> cache = new ConcurrentHashMap<>();
private final Map<Class<?>, CachingServiceTracker<?>> trackers = new ConcurrentHashMap<>();
ServiceCache(BundleContext context) {
this.context = context;
}
@SuppressWarnings("unchecked")
<T> T getService(ServiceReference<T> ref) {
return (T) cache.computeIfAbsent(ref, this::doGetService);
}
@SuppressWarnings("unchecked")
<T> Collection<ServiceReference<T>> getReferences(Class<T> clazz) {
return (List) trackers.computeIfAbsent(clazz, c -> new CachingServiceTracker<>(context, c)).getReferences();
}
Object doGetService(ServiceReference<?> ref) {
return Utils.doPrivileged(() -> context.getService(ref));
}
}
}
| 8,326 |
0 | Create_ds/aries/jndi/jndi-bundle/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-bundle/src/main/java/org/apache/aries/jndi/priv/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.jndi.priv;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private BundleActivator[] activators;
public Activator() {
this.activators = new BundleActivator[]{
new org.apache.aries.jndi.startup.Activator(),
new org.apache.aries.jndi.url.Activator()
// new org.apache.aries.jndi.rmi.Activator()
};
}
public void start(BundleContext bundleContext) throws Exception {
for (BundleActivator activator : activators) {
activator.start(bundleContext);
}
}
public void stop(BundleContext bundleContext) throws Exception {
for (BundleActivator activator : activators) {
activator.stop(bundleContext);
}
}
}
| 8,327 |
0 | Create_ds/aries/jndi/jndi-rmi/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-rmi/src/main/java/org/apache/aries/jndi/rmi/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.jndi.rmi;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.jndi.JNDIConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
public class Activator implements BundleActivator {
private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class.getName());
private ServiceRegistration reg;
public void start(BundleContext context) {
LOGGER.debug("Registering RMI url handler");
try {
Hashtable<String, Object> props = new Hashtable<>();
props.put(JNDIConstants.JNDI_URLSCHEME, new String[]{"rmi"});
reg = context.registerService(
ObjectFactory.class.getName(),
ClassLoader.getSystemClassLoader().loadClass("com.sun.jndi.url.rmi.rmiURLContextFactory").newInstance(),
props);
} catch (Exception e) {
LOGGER.info("A failure occurred while attempting to create the handler for the rmi JNDI URL scheme.", e);
}
}
public void stop(BundleContext context) {
safeUnregisterService(reg);
}
private static void safeUnregisterService(ServiceRegistration reg) {
if (reg != null) {
try {
reg.unregister();
} catch (IllegalStateException e) {
//This can be safely ignored
}
}
}
}
| 8,328 |
0 | Create_ds/aries/jndi/jndi-api/src/main/java/org/osgi/service | Create_ds/aries/jndi/jndi-api/src/main/java/org/osgi/service/jndi/JNDIProviderAdmin.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.service.jndi;
import java.util.Map;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.directory.Attributes;
/**
* This interface defines the OSGi service interface for the JNDIProviderAdmin
* service.
*
* This service provides the ability to resolve JNDI References in a dynamic
* fashion that does not require calls to
* <code>NamingManager.getObjectInstance()</code>. The methods of this service
* provide similar reference resolution, but rely on the OSGi Service Registry
* in order to find <code>ObjectFactory</code> instances that can convert a
* Reference to an Object.
*
* This service will typically be used by OSGi-aware JNDI Service Providers.
*
* @version $Revision$
* @ThreadSafe
*/
public interface JNDIProviderAdmin {
/**
* Resolve the object from the given reference.
*
* @param refInfo Reference info
* @param name the JNDI name associated with this reference
* @param context the JNDI context associated with this reference
* @param environment the JNDI environment associated with this JNDI context
* @return an Object based on the reference passed in, or the original
* reference object if the reference could not be resolved.
* @throws Exception in the event that an error occurs while attempting to
* resolve the JNDI reference.
*/
public Object getObjectInstance(Object refInfo, Name name, Context context,
Map<?,?> environment) throws Exception;
/**
* Resolve the object from the given reference.
*
* @param refInfo Reference info
* @param name the JNDI name associated with this reference
* @param context the JNDI context associated with this reference
* @param environment the JNDI environment associated with this JNDI context
* @param attributes the naming attributes to use when resolving this object
* @return an Object based on the reference passed in, or the original
* reference object if the reference could not be resolved.
* @throws Exception in the event that an error occurs while attempting to
* resolve the JNDI reference.
*/
public Object getObjectInstance(Object refInfo, Name name, Context context,
Map<?,?> environment, Attributes attributes) throws Exception;
} | 8,329 |
0 | Create_ds/aries/jndi/jndi-api/src/main/java/org/osgi/service | Create_ds/aries/jndi/jndi-api/src/main/java/org/osgi/service/jndi/JNDIConstants.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.service.jndi;
/**
* Constants for the JNDI implementation.
*
* @version $Revision$
* @Immutable
*/
public class JNDIConstants {
/**
* This service property is set by JNDI Providers that publish URL Context
* Factories as OSGi Services. The value of this property should be the URL
* scheme that is supported by the published service.
*/
public static final String JNDI_URLSCHEME = "osgi.jndi.url.scheme";
/**
* This service property is set on an OSGi service to provide a name that
* can be used to locate the service other than the service interface name.
*/
public static final String JNDI_SERVICENAME = "osgi.jndi.service.name";
/**
* This JNDI environment property can be used by a JNDI client to indicate
* the caller's BundleContext. This property can be set and passed to an
* InitialContext constructor. This property is only useful in the
* "traditional" mode of JNDI.
*/
public static final String BUNDLE_CONTEXT = "osgi.service.jndi.bundleContext";
private JNDIConstants() {
// non-instantiable
}
}
| 8,330 |
0 | Create_ds/aries/jndi/jndi-api/src/main/java/org/osgi/service | Create_ds/aries/jndi/jndi-api/src/main/java/org/osgi/service/jndi/JNDIContextManager.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.service.jndi;
import java.util.Map;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
/**
* This interface defines the OSGi service interface for the JNDIContextManager.
*
* This service provides the ability to create new JNDI Context instances
* without relying on the InitialContext constructor.
*
* @version $Revision$
* @ThreadSafe
*/
public interface JNDIContextManager {
/**
* Creates a new JNDI initial context with the default JNDI environment
* properties.
*
* @return an instance of javax.naming.Context
* @throws NamingException upon any error that occurs during context
* creation
*/
public Context newInitialContext() throws NamingException;
/**
* Creates a new JNDI initial context with the specified JNDI environment
* properties.
*
* @param environment JNDI environment properties specified by caller
* @return an instance of javax.naming.Context
* @throws NamingException upon any error that occurs during context
* creation
*/
public Context newInitialContext(Map<?,?> environment) throws NamingException;
/**
* Creates a new initial DirContext with the default JNDI environment
* properties.
*
* @return an instance of javax.naming.directory.DirContext
* @throws NamingException upon any error that occurs during context
* creation
*/
public DirContext newInitialDirContext() throws NamingException;
/**
* Creates a new initial DirContext with the specified JNDI environment
* properties.
*
* @param environment JNDI environment properties specified by the caller
* @return an instance of javax.naming.directory.DirContext
* @throws NamingException upon any error that occurs during context
* creation
*/
public DirContext newInitialDirContext(Map<?,?> environment)
throws NamingException;
}
| 8,331 |
0 | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi/spi/EnvironmentAugmentation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.spi;
import java.util.Hashtable;
public interface EnvironmentAugmentation {
void augmentEnvironment(Hashtable<?, ?> env);
}
| 8,332 |
0 | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi/spi/AugmenterInvoker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.spi;
import java.util.Hashtable;
public interface AugmenterInvoker {
void augmentEnvironment(Hashtable<?, ?> environment);
void unaugmentEnvironment(Hashtable<?, ?> environment);
}
| 8,333 |
0 | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi/spi/EnvironmentUnaugmentation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.spi;
import java.util.Hashtable;
public interface EnvironmentUnaugmentation {
void unaugmentEnvironment(Hashtable<?, ?> env);
}
| 8,334 |
0 | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi/urls/URLObjectFactoryFinder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.urls;
import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
public interface URLObjectFactoryFinder {
ObjectFactory findFactory(String url, Hashtable<?, ?> env) throws NamingException;
}
| 8,335 |
0 | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-api/src/main/java/org/apache/aries/jndi/api/JNDIConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.api;
public final class JNDIConstants {
public static final String REBIND_TIMEOUT = "org.apache.aries.jndi.rebind.timeout";
private JNDIConstants() {
}
}
| 8,336 |
0 | Create_ds/aries/jndi/jndi-url-itest-web/src/main/java/org/apache/aries/jndiurl | Create_ds/aries/jndi/jndi-url-itest-web/src/main/java/org/apache/aries/jndiurl/itest/JndiUrlItestServlet.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndiurl.itest;
import org.apache.aries.jndiurl.itest.beans.ConfigBean;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class JndiUrlItestServlet extends HttpServlet {
private static final long serialVersionUID = -4610850218411296469L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
StringBuilder result = new StringBuilder();
try {
InitialContext ctx = new InitialContext();
ConfigBean cb = (ConfigBean) ctx.lookup("blueprint:comp/config");
result.append(cb.getSimple().getOwner());
result.append(".");
result.append(cb.getVersion()); // Expected output is now "Mark.2.0"
// Now lookup and use a service published from another bundle
@SuppressWarnings("unchecked")
List<String> listService = (List<String>) ctx.lookup("blueprint:comp/listRef");
result.append(".");
String thirdListEntry = listService.get(2);
result.append(thirdListEntry);
} catch (NamingException nx) {
IOException ex = new IOException(nx.getMessage());
ex.initCause(nx);
throw ex;
}
resp.getWriter().print(result.toString());
resp.getWriter().close();
}
}
| 8,337 |
0 | Create_ds/aries/jndi/jndi-url-itest-web/src/main/java/org/apache/aries/jndiurl/itest | Create_ds/aries/jndi/jndi-url-itest-web/src/main/java/org/apache/aries/jndiurl/itest/beans/SimpleBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.jndiurl.itest.beans;
public class SimpleBean {
private String _owner;
public String getOwner() {
return _owner;
}
public void setOwner(String s) {
_owner = s;
}
}
| 8,338 |
0 | Create_ds/aries/jndi/jndi-url-itest-web/src/main/java/org/apache/aries/jndiurl/itest | Create_ds/aries/jndi/jndi-url-itest-web/src/main/java/org/apache/aries/jndiurl/itest/beans/ConfigBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndiurl.itest.beans;
public class ConfigBean {
SimpleBean _simple;
String _version;
public SimpleBean getSimple() {
return _simple;
}
public void setSimple(SimpleBean s) {
_simple = s;
}
public String getVersion() {
return _version;
}
public void setVersion(String v) {
_version = v;
}
}
| 8,339 |
0 | Create_ds/aries/jndi/jndi-url/src/test/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/test/java/org/apache/aries/jndi/url/BlueprintURLContextTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndi.url;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Set;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import org.apache.aries.mocks.BundleContextMock;
import org.apache.aries.mocks.BundleMock;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.unittest.mocks.Skeleton;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.NoSuchComponentException;
public class BlueprintURLContextTest {
private static Bundle bundle;
static class SimpleComponent {
String id;
public SimpleComponent (String i) {
id = i;
}
public String getIdMessage () {
return id + "_message";
}
}
static class AnotherComponent extends SimpleComponent {
public AnotherComponent (String i) {
super(i);
}
@Override
public String getIdMessage () {
return "AnotherComponent with id " + id;
}
}
static class BlueprintContainerStub
{
SimpleComponent comp1 = new SimpleComponent ("comp1");
AnotherComponent comp2 = new AnotherComponent ("comp2");
public Object getComponentInstance (String compId) throws NoSuchComponentException {
if (compId.equals("comp1")) {
return comp1;
} else if (compId.equals("comp2")) {
return comp2;
}
throw new NoSuchComponentException("Component does not exist", compId);
}
public Set<String> getComponentIds() {
return new HashSet<String>(Arrays.asList("comp1", "comp2"));
}
}
@BeforeClass
public static void setup() throws Exception {
System.setProperty("org.apache.aries.jndi.disable.builder", "false");
bundle = Skeleton.newMock(new BundleMock("aBundle", new Hashtable<String, String>()), Bundle.class);
BundleContext bc = bundle.getBundleContext();
new org.apache.aries.jndi.startup.Activator().start(bc);
Activator a = new Activator();
a.start(bc);
ProxyManager pm = (ProxyManager) Proxy.newProxyInstance(
BlueprintURLContext.class.getClassLoader(),
new Class[]{ProxyManager.class},
(proxy, method, args) -> null);
a.serviceChanged(null, pm);
// Register a BlueprintContainer mock that will answer getComponentInstance(String id) calls
BlueprintContainer bpc = Skeleton.newMock(new BlueprintContainerStub(), BlueprintContainer.class);
bc.registerService("org.osgi.service.blueprint.container.BlueprintContainer", bpc, new Hashtable<String, String>());
}
@AfterClass
public static void teardown() {
BundleContextMock.clear();
}
@Before
public void setupClassLoader() {
BundleMock mock = new BundleMock("bundle.for.new.initial.context", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
}
@After
public void restoreClassLoader() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
/**
* Check that we can directly address a blueprint component
*/
@Test
public void testSimpleComponentLookup() throws Exception {
BlueprintURLContext bpURLc = new BlueprintURLContext (bundle, new Hashtable<String, String>());
SimpleComponent sc = (SimpleComponent) bpURLc.lookup("blueprint:comp/comp1");
assertNotNull (sc);
String msg = sc.getIdMessage();
assertEquals ("comp1 message wrong", "comp1_message", msg);
}
/**
* Validate that we can create an InitialContext at blueprint:comp scope, and then
* look components up within it
*/
@Test
public void testTwoLevelComponentLookup() throws Exception {
InitialContext ctx = new InitialContext();
Context ctx2 = (Context) ctx.lookup("blueprint:comp");
SimpleComponent sc = (SimpleComponent) ctx2.lookup("comp2");
assertNotNull (sc);
String msg = sc.getIdMessage();
assertEquals ("comp2 message wrong", "AnotherComponent with id comp2", msg);
}
/**
* Check that we get a NameNotFoundException if we lookup something not in the
* registry.
*
* @throws NamingException
*/
@Test(expected=NameNotFoundException.class)
public void testLookupForServiceWeNeverHad() throws NamingException
{
InitialContext ctx = new InitialContext();
ctx.lookup("blueprint:comp/this.is.not.a.component");
}
/**
* Validate that list() function works for BlueprintURLContext.
* This returns an enumeration of component id -> component class name pairs
*/
@Test
public void testList() throws Exception {
InitialContext ctx = new InitialContext();
NamingEnumeration<NameClassPair> compList = ctx.list("blueprint:comp");
Set<String> expectedCompIds = new BlueprintContainerStub().getComponentIds();
while (compList.hasMore()) {
NameClassPair ncp = compList.next();
String compId = ncp.getName();
String compClass = ncp.getClassName();
if (compId.equals("comp1")) {
assertEquals ("comp1 class wrong in list", SimpleComponent.class.getName(), compClass);
} else if (compId.equals("comp2")) {
assertEquals ("comp2 class wrong in list", AnotherComponent.class.getName(), compClass);
}
expectedCompIds.remove(compId);
}
assertEquals ("Not all expected components were found", expectedCompIds.size(), 0);
}
/**
* Test BlueprintURLContext.listBindings()
* This returns an enumeration of component id -> component pairs
*/
@Test
public void testListBindings() throws Exception {
InitialContext ctx = new InitialContext();
NamingEnumeration<Binding> bindings = ctx.listBindings("blueprint:comp");
Set<String> expectedCompIds = new BlueprintContainerStub().getComponentIds();
while (bindings.hasMore()) {
Binding b = bindings.next();
String compId = b.getName();
Object component = b.getObject();
if (compId.equals("comp1")) {
SimpleComponent sc = (SimpleComponent) component;
assertEquals ("comp1 message wrong", "comp1_message", sc.getIdMessage());
} else if (compId.equals("comp2")) {
AnotherComponent ac = (AnotherComponent) component;
assertEquals ("comp2 message wrong", "AnotherComponent with id comp2", ac.getIdMessage());
}
expectedCompIds.remove(compId);
}
assertEquals ("Not all expected components were found", expectedCompIds.size(), 0);
}
@Test
public void testBlueprintTimeoutExtractionBothSpecified() {
Bundle b = bundleMock ("bundle.name;x=y;p:=q;blueprint.graceperiod:=true;blueprint.timeout:=10000;a=b;c:=d");
int timeout = BlueprintURLContext.getGracePeriod(b);
assertEquals ("graceperiod wrong", 10000, timeout);
}
@Test
public void testGracePeriodFalseHandled() throws Exception {
Bundle b = bundleMock ("bundle.name;x=y;p:=q;blueprint.graceperiod:=false;blueprint.timeout:=10000;a=b;c:=d");
int timeout = BlueprintURLContext.getGracePeriod(b);
assertEquals ("graceperiod wrong", -1, timeout);
b = bundleMock ("bundle.name;x=y;p:=q;blueprint.graceperiod:=false;a=b;c:=d");
timeout = BlueprintURLContext.getGracePeriod(b);
assertEquals ("graceperiod wrong", -1, timeout);
}
@Test
public void testDefaultsReturnedByDefault() throws Exception {
Bundle b = bundleMock("bundle.name;x=y;p:=q;blueprint.graceperiod:=true;a=b;c:=d");
int timeout = BlueprintURLContext.getGracePeriod(b);
assertEquals ("graceperiod wrong", 300000, timeout);
b = bundleMock ("bundle.name;x=y;p:=q;a=b;c:=d");
timeout = BlueprintURLContext.getGracePeriod(b);
assertEquals ("graceperiod wrong", 300000, timeout);
}
Bundle bundleMock (String bundleSymbolicNameHeader) {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put(Constants.BUNDLE_SYMBOLICNAME, bundleSymbolicNameHeader);
Bundle result = Skeleton.newMock(new BundleMock("aBundle", props), Bundle.class);
return result;
}
}
| 8,340 |
0 | Create_ds/aries/jndi/jndi-url/src/test/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/test/java/org/apache/aries/jndi/url/ServiceRegistryContextTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.Callable;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;
import javax.sql.DataSource;
import org.apache.aries.jndi.api.JNDIConstants;
import org.apache.aries.mocks.BundleContextMock;
import org.apache.aries.mocks.BundleMock;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.MethodCallHandler;
import org.apache.aries.unittest.mocks.Skeleton;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
/**
* Tests for our JNDI implementation for the service registry.
*/
public class ServiceRegistryContextTest
{
/** The service we register by default */
private Runnable service;
/** The bundle context for the test */
private BundleContext bc;
/** The service registration for the service */
private ServiceRegistration reg;
/**
* This method does the setup to ensure we always have a service.
* @throws NamingException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
@Before
public void registerService() throws Exception
{
bc = Skeleton.newMock(new BundleContextMock(), BundleContext.class);
registerProxyManager();
new org.apache.aries.jndi.startup.Activator().start(bc);
new Activator().start(bc);
service = Skeleton.newMock(Runnable.class);
registerService(service);
}
private void registerProxyManager()
{
ProxyManager mgr = Skeleton.newMock(ProxyManager.class);
// public Object createDelegatingProxy(Bundle clientBundle, Collection<Class<?>> classes, Callable<Object> dispatcher, Object template) throws UnableToProxyException;
Skeleton.getSkeleton(mgr).registerMethodCallHandler(new MethodCall(ProxyManager.class, "createDelegatingProxy", Bundle.class, Collection.class, Callable.class, Object.class),
new MethodCallHandler()
{
public Object handle(MethodCall methodCall, Skeleton skeleton) throws Exception
{
@SuppressWarnings("unchecked")
Collection<Class<?>> interfaceClasses = (Collection<Class<?>>) methodCall.getArguments()[1];
Class<?>[] classes = new Class<?>[interfaceClasses.size()];
Iterator<Class<?>> it = interfaceClasses.iterator();
for (int i = 0; it.hasNext(); i++) {
classes[i] = it.next();
}
@SuppressWarnings("unchecked")
final Callable<Object> target = (Callable<Object>) methodCall.getArguments()[2];
return Proxy.newProxyInstance(this.getClass().getClassLoader(), classes, new InvocationHandler()
{
public Object invoke(Object mock, Method method, Object[] arguments)
throws Throwable
{
return method.invoke(target.call(), arguments);
}
});
}
});
bc.registerService(ProxyManager.class.getName(), mgr, null);
}
/**
* Register a service in our map.
*
* @param service2 The service to register.
*/
private void registerService(Runnable service2)
{
ServiceFactory factory = Skeleton.newMock(ServiceFactory.class);
Skeleton skel = Skeleton.getSkeleton(factory);
skel.setReturnValue(new MethodCall(ServiceFactory.class, "getService", Bundle.class, ServiceRegistration.class), service2);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("rubbish", "smelly");
reg = bc.registerService(new String[] {"java.lang.Runnable"}, factory, props);
}
/**
* Make sure we clear the caches out before the next test.
*/
@After
public void teardown()
{
BundleContextMock.clear();
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
@Test
public void testBaseLookup() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
Context ctx2 = (Context) ctx.lookup("osgi:service");
Runnable r1 = (Runnable) ctx2.lookup("java.lang.Runnable");
assertNotNull(r1);
assertTrue("expected proxied service class", r1 != service);
Runnable r2 = (Runnable) ctx.lookup("aries:services/java.lang.Runnable");
assertNotNull(r2);
assertTrue("expected non-proxied service class", r2 == service);
}
@Test
public void testLookupWithPause() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
Hashtable<Object, Object> env = new Hashtable<Object, Object>();
env.put(JNDIConstants.REBIND_TIMEOUT, 1000);
InitialContext ctx = new InitialContext(env);
Context ctx2 = (Context) ctx.lookup("osgi:service");
Runnable r1 = (Runnable) ctx2.lookup("java.lang.Runnable");
reg.unregister();
long startTime = System.currentTimeMillis();
try {
r1.run();
fail("Should have received an exception");
} catch (ServiceException e) {
long endTime = System.currentTimeMillis();
long diff = endTime - startTime;
assertTrue("The run method did not fail in the expected time (1s): " + diff, diff >= 1000);
}
}
/**
* This test checks that we correctly register and deregister the url context
* object factory in the service registry.
*/
@Test
public void testJNDIRegistration()
{
ServiceReference ref = bc.getServiceReference(ObjectFactory.class.getName());
assertNotNull("The aries url context object factory was not registered", ref);
ObjectFactory factory = (ObjectFactory) bc.getService(ref);
assertNotNull("The aries url context object factory was null", factory);
}
@Test
public void jndiLookupServiceNameTest() throws NamingException, SQLException
{
InitialContext ctx = new InitialContext(new Hashtable<Object, Object>());
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
DataSource first = Skeleton.newMock(DataSource.class);
DataSource second = Skeleton.newMock(DataSource.class);
Hashtable<String, String> properties = new Hashtable<String, String>();
properties.put("osgi.jndi.service.name", "jdbc/myDataSource");
bc.registerService(DataSource.class.getName(), first, properties);
properties = new Hashtable<String, String>();
properties.put("osgi.jndi.service.name", "jdbc/myDataSource2");
bc.registerService(DataSource.class.getName(), second, properties);
DataSource s = (DataSource) ctx.lookup("osgi:service/jdbc/myDataSource");
assertNotNull(s);
s = (DataSource) ctx.lookup("osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/myDataSource2)");
assertNotNull(s);
s.isWrapperFor(DataSource.class); // don't care about the method, just need to call something.
Skeleton.getSkeleton(second).assertCalled(new MethodCall(DataSource.class, "isWrapperFor", Class.class));
}
/**
* This test does a simple JNDI lookup to prove that works.
* @throws NamingException
*/
@Test
public void simpleJNDILookup() throws NamingException
{
System.setProperty(Context.URL_PKG_PREFIXES, "helloMatey");
InitialContext ctx = new InitialContext(new Hashtable<Object, Object>());
BundleMock mock = new BundleMock("scooby.doo.1", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
Runnable s = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable");
assertNotNull("We didn't get a service back from our lookup :(", s);
s.run();
Skeleton.getSkeleton(service).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1);
Skeleton skel = Skeleton.getSkeleton(mock.getBundleContext());
skel.assertCalled(new MethodCall(BundleContext.class, "getServiceReferences", "java.lang.Runnable", null));
ctx = new InitialContext(new Hashtable<Object, Object>());
mock = new BundleMock("scooby.doo.2", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
s = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable");
// Check we have the packages set correctly
String packages = System.getProperty(Context.URL_PKG_PREFIXES, null);
assertTrue(ctx.getEnvironment().containsValue(packages));
assertNotNull("We didn't get a service back from our lookup :(", s);
s.run();
Skeleton.getSkeleton(service).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 2);
skel = Skeleton.getSkeleton(mock.getBundleContext());
skel.assertCalled(new MethodCall(BundleContext.class, "getServiceReferences", "java.lang.Runnable", null));
}
/**
* This test checks that we can pass a filter in without things blowing up.
* Right now our mock service registry does not implement filtering, so the
* effect is the same as simpleJNDILookup, but we at least know it is not
* blowing up.
*
* @throws NamingException
*/
@Test
public void jndiLookupWithFilter() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
Object s = ctx.lookup("osgi:service/java.lang.Runnable/(rubbish=smelly)");
assertNotNull("We didn't get a service back from our lookup :(", s);
service.run();
Skeleton.getSkeleton(service).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1);
Skeleton.getSkeleton(mock.getBundleContext()).assertCalled(new MethodCall(BundleContext.class, "getServiceReferences", "java.lang.Runnable", "(rubbish=smelly)"));
}
/**
* Check that we get a NameNotFoundException if we lookup after the service
* has been unregistered.
*
* @throws NamingException
*/
@Test(expected=NameNotFoundException.class)
public void testLookupWhenServiceHasBeenRemoved() throws NamingException
{
reg.unregister();
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
ctx.lookup("osgi:service/java.lang.Runnable");
}
/**
* Check that we get a NameNotFoundException if we lookup something not in the
* registry.
*
* @throws NamingException
*/
@Test(expected=NameNotFoundException.class)
public void testLookupForServiceWeNeverHad() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
ctx.lookup("osgi:service/java.lang.Integer");
}
/**
* This test checks that we can list the contents of the repository using the
* list method
*
* @throws NamingException
*/
public void listRepositoryContents() throws NamingException
{
InitialContext ctx = new InitialContext();
NamingEnumeration<NameClassPair> serviceList = ctx.list("osgi:service/java.lang.Runnable/(rubbish=smelly)");
checkThreadRetrievedViaListMethod(serviceList);
assertFalse("The repository contained more objects than we expected", serviceList.hasMoreElements());
//Now add a second service
registerService(new Thread());
serviceList = ctx.list("osgi:service/java.lang.Runnable/(rubbish=smelly)");
checkThreadRetrievedViaListMethod(serviceList);
checkThreadRetrievedViaListMethod(serviceList);
assertFalse("The repository contained more objects than we expected", serviceList.hasMoreElements());
}
@Test
public void checkProxyDynamism() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
String className = Runnable.class.getName();
Runnable t = Skeleton.newMock(Runnable.class);
Runnable t2 = Skeleton.newMock(Runnable.class);
// we don't want the default service
reg.unregister();
ServiceRegistration reg = bc.registerService(className, t, null);
bc.registerService(className, t2, null);
Runnable r = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable");
r.run();
Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1);
Skeleton.getSkeleton(t2).assertNotCalled(new MethodCall(Runnable.class, "run"));
reg.unregister();
r.run();
Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1);
Skeleton.getSkeleton(t2).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1);
}
@Test
public void checkServiceListLookup() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
String className = Runnable.class.getName();
Runnable t = Skeleton.newMock(Runnable.class);
// we don't want the default service
reg.unregister();
ServiceRegistration reg = bc.registerService(className, t, null);
ServiceRegistration reg2 = bc.registerService("java.lang.Thread", new Thread(), null);
Context ctx2 = (Context) ctx.lookup("osgi:servicelist/java.lang.Runnable");
Runnable r = (Runnable) ctx2.lookup(String.valueOf(reg.getReference().getProperty(Constants.SERVICE_ID)));
r.run();
Skeleton.getSkeleton(t).assertCalled(new MethodCall(Runnable.class, "run"));
reg.unregister();
try {
r.run();
fail("Should have received a ServiceException");
} catch (ServiceException e) {
assertEquals("service exception has the wrong type", ServiceException.UNREGISTERED, e.getType());
}
try {
ctx2.lookup(String.valueOf(reg2.getReference().getProperty(Constants.SERVICE_ID)));
fail("Expected a NameNotFoundException");
} catch (NameNotFoundException e) {
}
}
@Test
public void checkServiceListList() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
String className = Runnable.class.getName();
Runnable t = Skeleton.newMock(Runnable.class);
// we don't want the default service
reg.unregister();
ServiceRegistration reg = bc.registerService(className, t, null);
ServiceRegistration reg2 = bc.registerService(className, new Thread(), null);
NamingEnumeration<NameClassPair> ne = ctx.list("osgi:servicelist/" + className);
assertTrue(ne.hasMoreElements());
NameClassPair ncp = ne.nextElement();
assertEquals(String.valueOf(reg.getReference().getProperty(Constants.SERVICE_ID)), ncp.getName());
assertTrue("Class name not correct. Was: " + ncp.getClassName(), ncp.getClassName().contains("Proxy"));
assertTrue(ne.hasMoreElements());
ncp = ne.nextElement();
assertEquals(String.valueOf(reg2.getReference().getProperty(Constants.SERVICE_ID)), ncp.getName());
assertEquals("Class name not correct.", Thread.class.getName(), ncp.getClassName());
assertFalse(ne.hasMoreElements());
}
@Test
public void checkServiceListListBindings() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
String className = Runnable.class.getName();
MethodCall run = new MethodCall(Runnable.class, "run");
Runnable t = Skeleton.newMock(Runnable.class);
Runnable t2 = Skeleton.newMock(Runnable.class);
// we don't want the default service
reg.unregister();
ServiceRegistration reg = bc.registerService(className, t, null);
ServiceRegistration reg2 = bc.registerService(className, t2, null);
NamingEnumeration<Binding> ne = ctx.listBindings("osgi:servicelist/" + className);
assertTrue(ne.hasMoreElements());
Binding bnd = ne.nextElement();
assertEquals(String.valueOf(reg.getReference().getProperty(Constants.SERVICE_ID)), bnd.getName());
assertTrue("Class name not correct. Was: " + bnd.getClassName(), bnd.getClassName().contains("Proxy") || bnd.getClassName().contains("EnhancerByCGLIB"));
Runnable r = (Runnable) bnd.getObject();
assertNotNull(r);
r.run();
Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(run, 1);
Skeleton.getSkeleton(t2).assertNotCalled(run);
assertTrue(ne.hasMoreElements());
bnd = ne.nextElement();
assertEquals(String.valueOf(reg2.getReference().getProperty(Constants.SERVICE_ID)), bnd.getName());
assertTrue("Class name not correct. Was: " + bnd.getClassName(), bnd.getClassName().contains("Proxy") || bnd.getClassName().contains("EnhancerByCGLIB"));
r = (Runnable) bnd.getObject();
assertNotNull(r);
r.run();
Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(run, 1);
Skeleton.getSkeleton(t2).assertCalledExactNumberOfTimes(run, 1);
assertFalse(ne.hasMoreElements());
}
@Test(expected=ServiceException.class)
public void checkProxyWhenServiceGoes() throws ServiceException, NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
Runnable r = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable");
r.run();
Skeleton.getSkeleton(service).assertCalled(new MethodCall(Runnable.class, "run"));
reg.unregister();
r.run();
}
@Test
public void checkServiceOrderObserved() throws NamingException
{
BundleMock mock = new BundleMock("scooby.doo", new Properties());
Thread.currentThread().setContextClassLoader(mock.getClassLoader());
InitialContext ctx = new InitialContext();
String className = Runnable.class.getName();
Runnable t = Skeleton.newMock(Runnable.class);
Runnable t2 = Skeleton.newMock(Runnable.class);
// we don't want the default service
reg.unregister();
ServiceRegistration reg = bc.registerService(className, t, null);
ServiceRegistration reg2 = bc.registerService(className, t2, null);
Runnable r = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable");
r.run();
Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1);
Skeleton.getSkeleton(t2).assertNotCalled(new MethodCall(Runnable.class, "run"));
reg.unregister();
reg2.unregister();
Hashtable<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_RANKING, 55);
t = Skeleton.newMock(Runnable.class);
t2 = Skeleton.newMock(Runnable.class);
bc.registerService(className, t, null);
bc.registerService(className, t2, props);
r = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable");
r.run();
Skeleton.getSkeleton(t).assertNotCalled(new MethodCall(Runnable.class, "run"));
Skeleton.getSkeleton(t2).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1);
}
/**
* Check that the NamingEnumeration passed in has another element, which represents a java.lang.Thread
* @param serviceList
* @throws NamingException
*/
private void checkThreadRetrievedViaListMethod(NamingEnumeration<NameClassPair> serviceList)
throws NamingException
{
assertTrue("The repository was empty", serviceList.hasMoreElements());
NameClassPair ncp = serviceList.next();
assertNotNull("We didn't get a service back from our lookup :(", ncp);
assertNotNull("The object from the SR was null", ncp.getClassName());
assertEquals("The service retrieved was not of the correct type", "java.lang.Thread", ncp.getClassName());
assertEquals("osgi:service/java.lang.Runnable/(rubbish=smelly)", ncp.getName().toString());
}
/**
* This test checks that we can list the contents of the repository using the
* list method
*
* @throws NamingException
*/
public void listRepositoryBindings() throws NamingException
{
InitialContext ctx = new InitialContext();
NamingEnumeration<Binding> serviceList = ctx.listBindings("osgi:service/java.lang.Runnable/(rubbish=smelly)");
Object returnedService = checkThreadRetrievedViaListBindingsMethod(serviceList);
assertFalse("The repository contained more objects than we expected", serviceList.hasMoreElements());
assertTrue("The returned service was not the service we expected", returnedService == service);
//Now add a second service
Thread secondService = new Thread();
registerService(secondService);
serviceList = ctx.listBindings("osgi:service/java.lang.Runnable/(rubbish=smelly)");
Object returnedService1 = checkThreadRetrievedViaListBindingsMethod(serviceList);
Object returnedService2 = checkThreadRetrievedViaListBindingsMethod(serviceList);
assertFalse("The repository contained more objects than we expected", serviceList.hasMoreElements());
assertTrue("The services were not the ones we expected!",(returnedService1 == service || returnedService2 == service) && (returnedService1 == secondService || returnedService2 == secondService) && (returnedService1 != returnedService2));
}
/**
* Check that the NamingEnumeration passed in has another element, which represents a java.lang.Thread
* @param serviceList
* @return the object in the registry
* @throws NamingException
*/
private Object checkThreadRetrievedViaListBindingsMethod(NamingEnumeration<Binding> serviceList)
throws NamingException
{
assertTrue("The repository was empty", serviceList.hasMoreElements());
Binding binding = serviceList.nextElement();
assertNotNull("We didn't get a service back from our lookup :(", binding);
assertNotNull("The object from the SR was null", binding.getObject());
assertTrue("The service retrieved was not of the correct type", binding.getObject() instanceof Thread);
assertEquals("osgi:service/java.lang.Runnable/(rubbish=smelly)", binding.getName().toString());
return binding.getObject();
}
} | 8,341 |
0 | Create_ds/aries/jndi/jndi-url/src/test/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/test/java/org/apache/aries/jndi/url/OsgiNameParserTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import javax.naming.InvalidNameException;
import javax.naming.NameParser;
import javax.naming.NamingException;
import org.junit.Test;
/**
* This is where we test the service registry name parser.
*/
public class OsgiNameParserTest
{
/** The parser we are going to use for testing */
private NameParser parser = new OsgiNameParser();
/**
* OK, so we check that we can call checkNames multiple times.
* @throws NamingException
*/
@Test
public void checkValidNames() throws NamingException
{
checkName("aries","services","java.lang.Runnable","(a=b)");
checkName("aries","services","java.lang.Runnable");
checkName("osgi","service","java.lang.Runnable");
checkName("osgi","service","java.lang.Runnable", "(a=b)");
checkName("osgi","servicelist","java.lang.Runnable");
checkName("osgi","servicelist","java.lang.Runnable", "(a=b)");
checkName("osgi","servicelist","jdbc", "grok", "DataSource");
checkName("osgi", "framework", "bundleContext");
checkName("osgi","service","javax.sql.DataSource", "(osgi.jndi.servicee.name=jdbc/myDataSource)");
checkName("osgi","service","javax.sql.DataSource", "(&(a=/b)(c=/d))");
checkName("osgi", "service");
}
/**
* Make sure it fails if we try to parse something that isn't in aries:services
* @throws NamingException
*/
@Test(expected=InvalidNameException.class)
public void checkOutsideNamespace() throws NamingException
{
checkName("java","comp","env","jms","cf");
}
@Test(expected=InvalidNameException.class)
public void checkIncorrectPath() throws NamingException
{
checkName("osgi", "services", "java.lang.Runnable");
}
@Test(expected=InvalidNameException.class)
public void checkIllegalPath() throws NamingException
{
checkName("osgi", "wibble", "java.lang.Runnable");
}
private void checkName(String scheme, String path, String ... elements)
throws NamingException
{
StringBuilder builder = new StringBuilder();
StringBuilder serviceName = new StringBuilder();
builder.append(scheme);
builder.append(':');
builder.append(path);
if (elements.length > 0) {
builder.append('/');
for (String element : elements) {
serviceName.append(element);
serviceName.append('/');
}
serviceName.deleteCharAt(serviceName.length() - 1);
builder.append(serviceName);
}
OsgiName n = (OsgiName) parser.parse(builder.toString());
assertEquals(scheme, n.getScheme());
assertEquals(path, n.getSchemePath());
if (elements.length > 1) {
assertEquals(elements[0], n.getInterface());
if (elements.length == 2) {
assertTrue("There is no filter in the name", n.hasFilter());
assertEquals(elements[1], n.getFilter());
} else assertFalse(n.hasFilter());
}
if (elements.length == 1) {
assertFalse("There is a filter in the name", n.hasFilter());
}
assertEquals(serviceName.toString(), n.getServiceName());
}
} | 8,342 |
0 | Create_ds/aries/jndi/jndi-url/src/test/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/test/java/org/apache/aries/jndi/services/ServiceHelperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.services;
import java.util.Collection;
import org.apache.aries.jndi.services.ServiceHelper;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ServiceHelperTest {
interface A {};
interface B extends A{};
interface C {};
interface D extends A, C{};
@Test
public void testGetAllInterfaces() throws Exception {
Class<?>[] classes = { B.class, D.class };
Collection<Class<?>> cx = ServiceHelper.getAllInterfaces(classes);
assertTrue (cx.contains(A.class));
assertTrue (cx.contains(B.class));
assertTrue (cx.contains(C.class));
assertTrue (cx.contains(D.class));
assertTrue (cx.size() == 4);
}
}
| 8,343 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractServiceRegistryContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import org.apache.aries.jndi.spi.AugmenterInvoker;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.jndi.JNDIConstants;
import javax.naming.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public abstract class AbstractServiceRegistryContext implements Context {
private static final String ARIES_SERVICES = "aries:services/";
private static AugmenterInvoker augmenterInvoker = null;
protected BundleContext callerContext;
/**
* The environment for this context
*/
protected Map<String, Object> env;
/**
* The name parser for the service registry name space
*/
protected NameParser parser = new OsgiNameParser();
@SuppressWarnings("unchecked")
public AbstractServiceRegistryContext(BundleContext callerContext, Hashtable<?, ?> environment) {
env = new HashMap<String, Object>();
env.putAll((Map<? extends String, ? extends Object>) environment);
// ARIES-397:, If the caller has provided a BundleContext
// in the hashtable, use this in preference to callerContext
if (augmenterInvoker == null && callerContext != null) {
ServiceReference augmenterSR = callerContext.getServiceReference(AugmenterInvoker.class.getName());
if (augmenterSR != null) augmenterInvoker = (AugmenterInvoker) callerContext.getService(augmenterSR);
}
if (augmenterInvoker != null) augmenterInvoker.augmentEnvironment(environment);
BundleContext bc = (BundleContext) env.get(JNDIConstants.BUNDLE_CONTEXT);
if (augmenterInvoker != null) augmenterInvoker.unaugmentEnvironment(environment);
if (bc != null) {
this.callerContext = bc;
} else {
this.callerContext = callerContext;
}
}
@SuppressWarnings("unchecked")
public AbstractServiceRegistryContext(BundleContext callerContext, Map<?, ?> environment) {
env = new HashMap<>();
env.putAll((Map<? extends String, Object>) environment);
Hashtable<String, Object> environmentHT = new Hashtable<>();
environmentHT.putAll(env);
// ARIES-397: If the caller has provided a BundleContext
// in the hashtable, use this in preference to callerContext
if (augmenterInvoker == null && callerContext != null) {
ServiceReference augmenterSR = callerContext.getServiceReference(AugmenterInvoker.class.getName());
if (augmenterSR != null) augmenterInvoker = (AugmenterInvoker) callerContext.getService(augmenterSR);
}
if (augmenterInvoker != null) augmenterInvoker.augmentEnvironment(environmentHT);
BundleContext bc = (BundleContext) env.get(JNDIConstants.BUNDLE_CONTEXT);
if (augmenterInvoker != null) augmenterInvoker.unaugmentEnvironment(environmentHT);
if (bc != null) {
this.callerContext = bc;
} else {
this.callerContext = callerContext;
}
}
public Object addToEnvironment(String propName, Object propVal) throws NamingException {
return env.put(propName, propVal);
}
public void bind(Name name, Object obj) throws NamingException {
throw new OperationNotSupportedException();
}
public void bind(String name, Object obj) throws NamingException {
throw new OperationNotSupportedException();
}
public void close() throws NamingException {
env = null;
parser = null;
}
public Name composeName(Name name, Name prefix) throws NamingException {
String result = prefix + "/" + name;
String ns = ARIES_SERVICES;
if (result.startsWith(ns)) {
ns = "";
}
return parser.parse(ns + result);
}
public String composeName(String name, String prefix) throws NamingException {
String result = prefix + "/" + name;
String ns = ARIES_SERVICES;
if (result.startsWith(ns)) {
ns = "";
}
parser.parse(ns + result);
return result;
}
public Context createSubcontext(Name name) throws NamingException {
throw new OperationNotSupportedException();
}
public Context createSubcontext(String name) throws NamingException {
throw new OperationNotSupportedException();
}
public void destroySubcontext(Name name) throws NamingException {
//No-op we don't support sub-contexts in our context
}
public void destroySubcontext(String name) throws NamingException {
//No-op we don't support sub-contexts in our context
}
public Hashtable<?, ?> getEnvironment() throws NamingException {
Hashtable<Object, Object> environment = new Hashtable<Object, Object>();
environment.putAll(env);
return environment;
}
public String getNameInNamespace() throws NamingException {
throw new OperationNotSupportedException();
}
public NameParser getNameParser(Name name) throws NamingException {
return parser;
}
public NameParser getNameParser(String name) throws NamingException {
return parser;
}
public Object lookupLink(Name name) throws NamingException {
throw new OperationNotSupportedException();
}
public Object lookupLink(String name) throws NamingException {
throw new OperationNotSupportedException();
}
public void rebind(Name name, Object obj) throws NamingException {
throw new OperationNotSupportedException();
}
public void rebind(String name, Object obj) throws NamingException {
throw new OperationNotSupportedException();
}
public Object removeFromEnvironment(String propName) throws NamingException {
return env.remove(propName);
}
public void rename(Name oldName, Name newName) throws NamingException {
throw new OperationNotSupportedException();
}
public void rename(String oldName, String newName) throws NamingException {
throw new OperationNotSupportedException();
}
public void unbind(Name name) throws NamingException {
throw new OperationNotSupportedException();
}
public void unbind(String name) throws NamingException {
throw new OperationNotSupportedException();
}
}
| 8,344 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/OsgiName.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import java.util.Enumeration;
/**
* A composite name for the aries namespace. This provides useful utility methods
* for accessing the name.
* <p>
* component 0: osgi:service, aries:services, osgi:servicelist
* component 1: interface
* component 2: filter
*/
public final class OsgiName extends AbstractName {
public static final String OSGI_SCHEME = "osgi";
public static final String ARIES_SCHEME = "aries";
public static final String SERVICE_PATH = "service";
public static final String SERVICES_PATH = "services";
public static final String SERVICE_LIST_PATH = "servicelist";
public static final String FRAMEWORK_PATH = "framework";
/**
* The serial version UID
*/
private static final long serialVersionUID = 6617580228852444656L;
public OsgiName(String name) throws InvalidNameException {
super(name);
}
public OsgiName(Name name) throws InvalidNameException {
this(name.toString());
}
public boolean hasFilter() {
return size() == 3;
}
public boolean isServiceNameBased() {
return size() > 3;
}
public String getInterface() {
return get(1);
}
public String getFilter() {
return hasFilter() ? get(2) : null;
}
public String getServiceName() {
Enumeration<String> parts = getAll();
parts.nextElement();
StringBuilder builder = new StringBuilder();
if (parts.hasMoreElements()) {
while (parts.hasMoreElements()) {
builder.append(parts.nextElement());
builder.append('/');
}
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
public boolean hasInterface() {
return size() > 1;
}
} | 8,345 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintURLContextFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndi.url;
import org.apache.aries.jndi.spi.AugmenterInvoker;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.jndi.JNDIConstants;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
public class BlueprintURLContextFactory implements ObjectFactory {
private static AugmenterInvoker augmenterInvoker = null;
final private Bundle _callersBundle;
public BlueprintURLContextFactory(Bundle callersBundle) {
_callersBundle = callersBundle;
}
@Override
public Object getObjectInstance(Object obj, Name name, Context callersCtx, Hashtable<?, ?> envmt) throws Exception {
if (augmenterInvoker == null && _callersBundle != null) {
BundleContext callerBundleContext = _callersBundle.getBundleContext();
ServiceReference<?> augmenterSR = callerBundleContext.getServiceReference(AugmenterInvoker.class.getName());
if (augmenterSR != null) augmenterInvoker = (AugmenterInvoker) callerBundleContext.getService(augmenterSR);
}
if (augmenterInvoker != null) augmenterInvoker.augmentEnvironment(envmt);
BundleContext bc = (BundleContext) envmt.get(JNDIConstants.BUNDLE_CONTEXT);
if (augmenterInvoker != null) augmenterInvoker.unaugmentEnvironment(envmt);
Bundle b = (bc != null) ? bc.getBundle() : null;
Object result = null;
if (obj == null) {
result = new BlueprintURLContext((b == null) ? _callersBundle : b, envmt);
} else if (obj instanceof String) {
Context ctx = new BlueprintURLContext((b == null) ? _callersBundle : b, envmt);
try {
result = ctx.lookup((String) obj);
} finally {
ctx.close();
}
}
return result;
}
}
| 8,346 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintURLContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndi.url;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.NoSuchComponentException;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import javax.naming.*;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BlueprintURLContext implements Context {
static final Pattern graceP = Pattern.compile(".*;\\s*blueprint.graceperiod\\s*:=\\s*\"?([A-Za-z]+).*");
static final Pattern timeoutP = Pattern.compile(".*;\\s*blueprint.timeout\\s*:=\\s*\"?([0-9]+).*");
private static final String BLUEPRINT_NAMESPACE = "blueprint:comp/";
private Bundle _callersBundle;
private Map<String, Object> _env;
private NameParser _parser = new BlueprintNameParser();
private BlueprintName _parentName;
@SuppressWarnings("unchecked")
public BlueprintURLContext(Bundle callersBundle, Hashtable<?, ?> env) {
_callersBundle = callersBundle;
_env = new HashMap<>();
_env.putAll((Map<? extends String, Object>) env);
_parentName = null;
}
private BlueprintURLContext(Bundle callersBundle, BlueprintName parentName, Map<String, Object> env) {
_callersBundle = callersBundle;
_parentName = parentName;
_env = env;
}
/**
* Look for a BluepintContainer service in a given bundle
*
* @param b Bundle to look in
* @return BlueprintContainer service, or null if none available
*/
private static ServiceReference<BlueprintContainer> findBPCRef(Bundle b) {
ServiceReference<?>[] refs = b.getRegisteredServices();
ServiceReference<?> result = null;
if (refs != null) {
outer:
for (ServiceReference<?> r : refs) {
String[] objectClasses = (String[]) r.getProperty(Constants.OBJECTCLASS);
for (String objectClass : objectClasses) {
if (objectClass.equals(BlueprintContainer.class.getName())) {
// Arguably we could put an r.isAssignableTo(jndi-url-bundle, BlueprintContainer.class.getName())
// check here. But if you've got multiple, class-space inconsistent instances of blueprint in
// your environment, you've almost certainly got other problems.
result = r;
break outer;
}
}
}
}
return (ServiceReference<BlueprintContainer>) result;
}
/**
* Obtain a BlueprintContainerService for the given bundle. If the service isn't there, wait for up
* to the blueprint.graceperiod defined for that bundle for one to be published.
*
* @param b The Bundle to look in
* @return BlueprintContainerService instance for that bundle
* @throws ServiceUnavailableException If no BlueprinContainerService found
*/
private static ServiceReference<BlueprintContainer> getBlueprintContainerRef(Bundle b) throws ServiceUnavailableException {
ServiceReference<BlueprintContainer> result = findBPCRef(b);
if (result == null) {
Semaphore s = new Semaphore(0);
AtomicReference<ServiceReference<BlueprintContainer>> bpcRef = new AtomicReference<>();
ServiceTracker<BlueprintContainer, BlueprintContainer> st = new ServiceTracker<>(b.getBundleContext(), BlueprintContainer.class,
new BlueprintContainerServiceTrackerCustomizer(b, s, bpcRef));
st.open();
// Make another check for the BlueprintContainer service in case it came up just before our tracker engaged
int graceperiod = getGracePeriod(b);
result = findBPCRef(b);
if (result == null && graceperiod >= 0) {
if (graceperiod == 0) { // Wait for an unlimited period
try {
s.acquire();
} catch (InterruptedException ix) {
}
} else {
try {
s.tryAcquire(graceperiod, TimeUnit.MILLISECONDS);
} catch (InterruptedException ix) {
}
}
}
result = bpcRef.get();
st.close();
}
if (result == null) {
throw new ServiceUnavailableException("The BlueprintContainer service for bundle " + b.getSymbolicName() + '/' + b.getVersion() + " can not be located");
}
return result;
}
/**
* Determine the blueprint.timeout set for a given bundle
*
* @param b The bundle to inspect
* @return -1 if blueprint.graceperiod is false, otherwise the value of blueprint.timeout,
* or 300000 if blueprint.graceperiod is true and no value is given for
* blueprint.timeout.
*/
public static int getGracePeriod(Bundle b) {
int result = 300000; // Blueprint default
boolean gracePeriodSet = true; // Blueprint default
String bundleSymbolicName = b.getHeaders().get(Constants.BUNDLE_SYMBOLICNAME);
// I'd like to use ManifestHeaderProcessor here but as of December 15th 2010 it lives
// application-utils, and I don't want to make that a dependency of jndi-url
Matcher m = graceP.matcher(bundleSymbolicName);
if (m.matches()) {
String gracePeriod = m.group(1);
gracePeriodSet = !gracePeriod.equalsIgnoreCase("false"); // See OSGi Enterprise spec 4.2 section 121.3.2.1 step 6
}
if (!gracePeriodSet) {
result = -1;
} else {
m = timeoutP.matcher(bundleSymbolicName);
if (m.matches()) {
String timeout = m.group(1);
try {
result = Integer.valueOf(timeout);
} catch (NumberFormatException nfx) {
// Noop: result stays at its default value
}
}
}
return result;
}
@Override
protected void finalize() throws NamingException {
close();
}
@Override
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
return _env.put(propName, propVal);
}
@Override
public void bind(Name n, Object o) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void bind(String s, Object o) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void close() throws NamingException {
_env = null;
}
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
String result = prefix + "/" + name;
String ns = BLUEPRINT_NAMESPACE;
if (result.startsWith(ns)) {
ns = "";
}
return _parser.parse(ns + result);
}
@Override
public String composeName(String name, String prefix) throws NamingException {
String result = prefix + "/" + name;
String ns = BLUEPRINT_NAMESPACE;
if (result.startsWith(ns)) {
ns = "";
}
_parser.parse(ns + result);
return result;
}
@Override
public Context createSubcontext(Name n) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public Context createSubcontext(String s) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void destroySubcontext(Name n) throws NamingException {
// No-op we don't support sub-contexts in our context
}
@Override
public void destroySubcontext(String s) throws NamingException {
// No-op we don't support sub-contexts in our context
}
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException {
Hashtable<Object, Object> environment = new Hashtable<>();
environment.putAll(_env);
return environment;
}
@Override
public String getNameInNamespace() throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public NameParser getNameParser(Name n) throws NamingException {
return _parser;
}
@Override
public NameParser getNameParser(String s) throws NamingException {
return _parser;
}
@Override
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
return list(name.toString());
}
@Override
public NamingEnumeration<NameClassPair> list(String s) throws NamingException {
return new BlueprintComponentNamingEnumeration<>(_callersBundle,
b -> new NameClassPair(b.getName(), b.getClassName()));
}
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return listBindings(name.toString());
}
@Override
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException {
return new BlueprintComponentNamingEnumeration<>(_callersBundle, b -> b);
}
@Override
public Object lookup(Name name) throws NamingException, ServiceUnavailableException {
ServiceReference<BlueprintContainer> blueprintContainerRef = getBlueprintContainerRef(_callersBundle);
Object result;
try {
BlueprintContainer blueprintContainer = _callersBundle.getBundleContext().getService(blueprintContainerRef);
BlueprintName bpName;
if (name instanceof BlueprintName) {
bpName = (BlueprintName) name;
} else if (_parentName != null) {
bpName = new BlueprintName(_parentName.toString() + "/" + name.toString());
} else {
bpName = (BlueprintName) _parser.parse(name.toString());
}
if (bpName.hasComponent()) {
String componentId = bpName.getComponentId();
try {
result = blueprintContainer.getComponentInstance(componentId);
} catch (NoSuchComponentException nsce) {
throw new NameNotFoundException(nsce.getMessage());
}
} else {
result = new BlueprintURLContext(_callersBundle, bpName, _env);
}
} finally {
_callersBundle.getBundleContext().ungetService(blueprintContainerRef);
}
return result;
}
@Override
public Object lookup(String name) throws NamingException {
if (_parentName != null) {
name = _parentName.toString() + "/" + name;
}
Object result = lookup(_parser.parse(name));
return result;
}
@Override
public Object lookupLink(Name n) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public Object lookupLink(String s) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void rebind(Name n, Object o) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void rebind(String s, Object o) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public Object removeFromEnvironment(String propName) throws NamingException {
return _env.remove(propName);
}
@Override
public void rename(Name nOld, Name nNew) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void rename(String sOld, String sNew) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void unbind(Name n) throws NamingException {
throw new OperationNotSupportedException();
}
@Override
public void unbind(String s) throws NamingException {
throw new OperationNotSupportedException();
}
// listBindings wants a NamingEnumeration<Binding>
// list wants a NamingEnumeration<NameClassPair>
// Both are very similar. As per ServiceRegistryListContext we delegate to a closure to do the final processing
private interface ComponentProcessor<T> {
T get(Binding b);
}
private static class BlueprintComponentNamingEnumeration<T> implements NamingEnumeration<T> {
private Binding[] blueprintIdToComponentBindings;
private int position = 0;
private ComponentProcessor<T> processor;
public BlueprintComponentNamingEnumeration(Bundle callersBundle, ComponentProcessor<T> p) throws ServiceUnavailableException {
ServiceReference blueprintContainerRef = getBlueprintContainerRef(callersBundle);
try {
BlueprintContainer blueprintContainer = (BlueprintContainer) callersBundle.getBundleContext().getService(blueprintContainerRef);
@SuppressWarnings("unchecked")
Set<String> componentIds = blueprintContainer.getComponentIds();
blueprintIdToComponentBindings = new Binding[componentIds.size()];
Iterator<String> idIterator = componentIds.iterator();
for (int i = 0; i < blueprintIdToComponentBindings.length; i++) {
String id = idIterator.next();
Object o = blueprintContainer.getComponentInstance(id);
blueprintIdToComponentBindings[i] = new Binding(id, o);
}
processor = p;
} finally {
callersBundle.getBundleContext().ungetService(blueprintContainerRef);
}
}
@Override
public boolean hasMoreElements() {
return position < blueprintIdToComponentBindings.length;
}
@Override
public T nextElement() {
if (!hasMoreElements()) throw new NoSuchElementException();
Binding bindingToProcess = blueprintIdToComponentBindings[position];
position++;
T result = processor.get(bindingToProcess);
return result;
}
@Override
public T next() throws NamingException {
return nextElement();
}
@Override
public boolean hasMore() throws NamingException {
return hasMoreElements();
}
@Override
public void close() throws NamingException {
// Nothing to do
}
}
private static class BlueprintContainerServiceTrackerCustomizer implements ServiceTrackerCustomizer<BlueprintContainer, BlueprintContainer> {
Bundle bundleToFindBPCServiceIn;
Semaphore semaphore;
AtomicReference<ServiceReference<BlueprintContainer>> atomicRef;
public BlueprintContainerServiceTrackerCustomizer(Bundle b, Semaphore s, AtomicReference<ServiceReference<BlueprintContainer>> aref) {
bundleToFindBPCServiceIn = b;
semaphore = s;
atomicRef = aref;
}
@Override
public BlueprintContainer addingService(ServiceReference<BlueprintContainer> reference) {
BlueprintContainer result = null;
if (bundleToFindBPCServiceIn.equals(reference.getBundle())) {
atomicRef.set(reference);
semaphore.release();
result = reference.getBundle().getBundleContext().getService(reference);
}
return result;
}
@Override
public void modifiedService(ServiceReference<BlueprintContainer> reference, BlueprintContainer service) {
}
@Override
public void removedService(ServiceReference<BlueprintContainer> reference, BlueprintContainer service) {
}
}
}
| 8,347 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintNameParser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndi.url;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingException;
/**
* A parser for the aries namespace
*/
public final class BlueprintNameParser implements NameParser {
private static final String BLUEPRINT_SCHEME = "blueprint";
private static final String COMP_PATH = "comp";
@Override
public Name parse(String name) throws NamingException {
BlueprintName result = new BlueprintName(name);
String urlScheme = result.getScheme();
String schemePath = result.getSchemePath();
if (!BLUEPRINT_SCHEME.equals(urlScheme) || !COMP_PATH.equals(schemePath)) {
throw new InvalidNameException(name);
}
return result;
}
@Override
public boolean equals(Object other) {
return other instanceof OsgiNameParser;
}
@Override
public int hashCode() {
return 100004;
}
} | 8,348 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintName.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndi.url;
import javax.naming.InvalidNameException;
import javax.naming.Name;
public class BlueprintName extends AbstractName {
/**
*
*/
private static final long serialVersionUID = 7460901600614300179L;
public BlueprintName(String name) throws InvalidNameException {
super(name);
}
public BlueprintName(Name name) throws InvalidNameException {
this(name.toString());
}
public String getComponentId() {
return get(1);
}
public boolean hasComponent() {
return size() > 1;
}
}
| 8,349 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/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.jndi.url;
import org.apache.aries.proxy.ProxyManager;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.jndi.JNDIConstants;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Activator implements BundleActivator {
private static SingleServiceTracker<ProxyManager> proxyManager;
private BundleContext ctx;
private volatile ServiceRegistration<?> osgiUrlReg = null;
private volatile ServiceRegistration<?> blueprintUrlReg = null;
public static ProxyManager getProxyManager() {
return proxyManager == null ? null : proxyManager.getService();
}
@Override
public void start(BundleContext context) throws InvalidSyntaxException {
ctx = context;
proxyManager = new SingleServiceTracker<>(context, ProxyManager.class, this::serviceChanged);
proxyManager.open();
// Blueprint URL scheme requires access to the BlueprintContainer service.
// We have an optional import
// on org.osgi.service.blueprint.container: only register the blueprint:comp/URL
// scheme if it's present
try {
ctx.getBundle().loadClass("org.osgi.service.blueprint.container.BlueprintContainer");
Hashtable<String, Object> blueprintURlSchemeProps = new Hashtable<>();
blueprintURlSchemeProps.put(JNDIConstants.JNDI_URLSCHEME, new String[]{"blueprint"});
blueprintUrlReg = ctx.registerService(ObjectFactory.class.getName(),
new BlueprintURLContextServiceFactory(), blueprintURlSchemeProps);
} catch (ClassNotFoundException cnfe) {
// The blueprint packages aren't available, so do nothing. That's fine.
Logger logger = Logger.getLogger("org.apache.aries.jndi");
logger.log(Level.INFO, "Blueprint support disabled: " + cnfe);
logger.log(Level.FINE, "Blueprint support disabled", cnfe);
}
}
@Override
public void stop(BundleContext context) {
proxyManager.close();
safeUnregisterService(osgiUrlReg);
safeUnregisterService(blueprintUrlReg);
}
void serviceChanged(ProxyManager oldPm, ProxyManager newPm) {
if (newPm == null) {
safeUnregisterService(osgiUrlReg);
osgiUrlReg = null;
} else {
Hashtable<String, Object> osgiUrlprops = new Hashtable<>();
osgiUrlprops.put(JNDIConstants.JNDI_URLSCHEME, new String[]{"osgi", "aries"});
osgiUrlReg = ctx.registerService(ObjectFactory.class.getName(),
new OsgiURLContextServiceFactory(), osgiUrlprops);
}
}
private static void safeUnregisterService(ServiceRegistration<?> reg) {
if (reg != null) {
try {
reg.unregister();
} catch (IllegalStateException e) {
//This can be safely ignored
}
}
}
} | 8,350 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/AbstractName.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndi.url;
import javax.naming.CompositeName;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
@SuppressWarnings("serial")
public abstract class AbstractName extends CompositeName {
public AbstractName(String name) {
super(split(name));
}
protected static Enumeration<String> split(String name) {
List<String> elements = new ArrayList<>();
StringBuilder builder = new StringBuilder();
int len = name.length();
int count = 0;
for (int i = 0; i < len; i++) {
char c = name.charAt(i);
if (c == '/' && count == 0) {
elements.add(builder.toString());
builder = new StringBuilder();
continue;
} else if (c == '(') count++;
else if (c == ')') count++;
builder.append(c);
}
elements.add(builder.toString());
return Collections.enumeration(elements);
}
public String getScheme() {
String part0 = get(0);
int index = part0.indexOf(':');
if (index > 0) {
return part0.substring(0, index);
} else {
return null;
}
}
public String getSchemePath() {
String part0 = get(0);
int index = part0.indexOf(':');
String result;
if (index > 0) {
result = part0.substring(index + 1);
} else {
result = null;
}
return result;
}
}
| 8,351 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/ServiceRegistryListContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import org.apache.aries.jndi.services.ServiceHelper;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import javax.naming.*;
import java.util.Map;
import java.util.NoSuchElementException;
public class ServiceRegistryListContext extends AbstractServiceRegistryContext implements Context {
/**
* The osgi lookup name
**/
private OsgiName parentName;
public ServiceRegistryListContext(BundleContext callerContext, Map<String, Object> env, OsgiName validName) {
super(callerContext, env);
parentName = validName;
}
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
return list(name.toString());
}
public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
if (!"".equals(name)) throw new NameNotFoundException(name);
final ServiceReference[] refs = getServiceRefs();
return new ServiceNamingEnumeration<>(callerContext, refs, new ThingManager<NameClassPair>() {
public NameClassPair get(BundleContext ctx, ServiceReference<?> ref) {
Object service = ctx.getService(ref);
String className = (service != null) ? service.getClass().getName() : null;
ctx.ungetService(ref);
return new NameClassPair(serviceId(ref), className, true);
}
public void release(BundleContext ctx, ServiceReference<?> ref) {
}
});
}
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
return listBindings(name.toString());
}
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
if (!"".equals(name)) throw new NameNotFoundException(name);
final ServiceReference<?>[] refs = getServiceRefs();
return new ServiceNamingEnumeration<>(callerContext, refs, new ThingManager<Binding>() {
public Binding get(BundleContext ctx, ServiceReference<?> ref) {
Object service = ServiceHelper.getService(ctx, ref);
return new Binding(serviceId(ref), service, true);
}
public void release(BundleContext ctx, ServiceReference<?> ref) {
ctx.ungetService(ref);
}
});
}
public Object lookup(Name name) throws NamingException {
return lookup(name.toString());
}
public Object lookup(String name) throws NamingException {
Object result = ServiceHelper.getService(callerContext, parentName, name, false, env, true);
if (result == null) {
throw new NameNotFoundException(name);
}
return result;
}
private String serviceId(ServiceReference ref) {
return String.valueOf(ref.getProperty(Constants.SERVICE_ID));
}
private ServiceReference<?>[] getServiceRefs() throws NamingException {
return ServiceHelper.getServiceReferences(callerContext, parentName.getInterface(), parentName.getFilter(), parentName.getServiceName(), env);
}
private interface ThingManager<T> {
T get(BundleContext ctx, ServiceReference<?> ref);
void release(BundleContext ctx, ServiceReference<?> ref);
}
private static class ServiceNamingEnumeration<T> implements NamingEnumeration<T> {
private BundleContext ctx;
private ServiceReference<?>[] refs;
private int position = 0;
private ThingManager<T> mgr;
private T last;
private ServiceNamingEnumeration(BundleContext context, ServiceReference<?>[] theRefs, ThingManager<T> manager) {
ctx = context;
refs = (theRefs != null) ? theRefs : new ServiceReference[0];
mgr = manager;
}
public void close() throws NamingException {
mgr.release(ctx, refs[position - 1]);
last = null;
}
public boolean hasMore() throws NamingException {
return hasMoreElements();
}
public T next() throws NamingException {
return nextElement();
}
public boolean hasMoreElements() {
return position < refs.length;
}
public T nextElement() {
if (!hasMoreElements()) throw new NoSuchElementException();
if (position > 0) mgr.release(ctx, refs[position - 1]);
last = mgr.get(ctx, refs[position++]);
return last;
}
}
} | 8,352 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/OsgiURLContextFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import org.osgi.framework.BundleContext;
import javax.naming.ConfigurationException;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
/**
* A factory for the aries JNDI context
*/
public class OsgiURLContextFactory implements ObjectFactory {
private BundleContext callerContext;
public OsgiURLContextFactory(BundleContext callerContext) {
this.callerContext = callerContext;
}
public Object getObjectInstance(Object obj,
Name name,
Context nameCtx,
Hashtable<?, ?> environment) throws Exception {
if (obj == null) {
return new ServiceRegistryContext(callerContext, environment);
} else if (obj instanceof String) {
return findAny(environment, (String) obj);
} else if (obj instanceof String[]) {
return findAny(environment, (String[]) obj);
} else {
return null;
}
}
/**
* Try each URL until either lookup succeeds or they all fail
*/
private Object findAny(Hashtable<?, ?> environment, String... urls)
throws ConfigurationException, NamingException {
if (urls.length == 0) {
throw new ConfigurationException("0");
}
Context context = new ServiceRegistryContext(callerContext, environment);
try {
NamingException ne = null;
for (int i = 0; i < urls.length; i++) {
try {
return context.lookup(urls[i]);
} catch (NamingException e) {
ne = e;
}
}
throw ne;
} finally {
context.close();
}
}
}
| 8,353 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/ServiceRegistryContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import org.apache.aries.jndi.services.ServiceHelper;
import org.osgi.framework.AdminPermission;
import org.osgi.framework.BundleContext;
import javax.naming.*;
import java.security.AccessControlException;
import java.security.AccessController;
import java.util.Hashtable;
import java.util.Map;
/**
* A JNDI context for looking stuff up from the service registry.
*/
public class ServiceRegistryContext extends AbstractServiceRegistryContext implements Context {
/**
* The parent name, if one is provided, of this context
*/
private OsgiName parentName;
/**
* Why Mr Java this class does indeed take a fine copy of the provided
* environment. One might imagine that it is worried that the provider is
* not to be trusted.
*
* @param environment
*/
public ServiceRegistryContext(BundleContext callerContext, Hashtable<?, ?> environment) {
super(callerContext, environment);
}
public ServiceRegistryContext(BundleContext callerContext, OsgiName validName, Map<String, Object> env) {
super(callerContext, env);
parentName = validName;
}
public NamingEnumeration<NameClassPair> list(final Name name) throws NamingException {
return new ServiceRegistryListContext(callerContext, env, convert(name)).list("");
}
public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
return list(parse(name));
}
public NamingEnumeration<Binding> listBindings(final Name name) throws NamingException {
return new ServiceRegistryListContext(callerContext, env, convert(name)).listBindings("");
}
public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
return listBindings(parse(name));
}
public Object lookup(Name name) throws NamingException {
Object result;
OsgiName validName = convert(name);
String pathFragment = validName.getSchemePath();
String schemeName = validName.getScheme();
if (validName.hasInterface()) {
if (OsgiName.FRAMEWORK_PATH.equals(pathFragment) && "bundleContext".equals(validName.getServiceName())) {
try {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
AdminPermission adminPermission =
new AdminPermission(callerContext.getBundle(), AdminPermission.CONTEXT);
sm.checkPermission(adminPermission);
}
} catch (AccessControlException accessControlException) {
NamingException namingException = new NameNotFoundException("The Caller does not have permissions to get the BundleContext.");
namingException.setRootCause(accessControlException);
throw namingException;
}
return callerContext;
} else if ((OsgiName.SERVICE_PATH.equals(pathFragment) && OsgiName.OSGI_SCHEME.equals(schemeName))
|| (OsgiName.SERVICES_PATH.equals(pathFragment) && OsgiName.ARIES_SCHEME.equals(schemeName))) {
result = ServiceHelper.getService(callerContext, validName, null, true, env, OsgiName.OSGI_SCHEME.equals(schemeName));
} else if (OsgiName.SERVICE_LIST_PATH.equals(pathFragment)) {
result = new ServiceRegistryListContext(callerContext, env, validName);
} else {
result = null;
}
} else {
result = new ServiceRegistryContext(callerContext, validName, env);
}
if (result == null) {
throw new NameNotFoundException(name.toString());
}
return result;
}
private OsgiName convert(Name name) throws NamingException {
if (name instanceof OsgiName) {
return (OsgiName) name;
} else if (parentName != null) {
return new OsgiName(parentName.toString() + "/" + name.toString());
} else {
return (OsgiName) parser.parse(name.toString());
}
}
private Name parse(String name) throws NamingException {
if (parentName != null) {
name = parentName.toString() + "/" + name;
}
return parser.parse(name);
}
public Object lookup(String name) throws NamingException {
return lookup(parse(name));
}
}
| 8,354 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/OsgiNameParser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingException;
/**
* A parser for the aries namespace
*/
public final class OsgiNameParser implements NameParser {
private static final String OSGI_SCHEME = "osgi";
private static final String ARIES_SCHEME = "aries";
private static final String SERVICE_PATH = "service";
private static final String SERVICES_PATH = "services";
private static final String SERVICE_LIST_PATH = "servicelist";
private static final String FRAMEWORK_PATH = "framework";
public Name parse(String name) throws NamingException {
OsgiName result = new OsgiName(name);
String urlScheme = result.getScheme();
String schemePath = result.getSchemePath();
if (!(OSGI_SCHEME.equals(urlScheme) || ARIES_SCHEME.equals(urlScheme))) {
throw new InvalidNameException(name);
}
if (ARIES_SCHEME.equals(urlScheme) && !SERVICES_PATH.equals(schemePath)) {
throw new InvalidNameException(name);
}
if (OSGI_SCHEME.equals(urlScheme) && !(SERVICE_PATH.equals(schemePath)
|| SERVICE_LIST_PATH.equals(schemePath)
|| FRAMEWORK_PATH.equals(schemePath))) {
throw new InvalidNameException(name);
}
return result;
}
@Override
public boolean equals(Object other) {
return other instanceof OsgiNameParser;
}
@Override
public int hashCode() {
return 100003;
}
} | 8,355 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/SingleServiceTracker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import org.osgi.framework.*;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
//This is from aries util
public final class SingleServiceTracker<T> implements ServiceListener {
private final BundleContext ctx;
private final String className;
private final AtomicReference<T> service = new AtomicReference<>();
private final AtomicReference<ServiceReference> ref = new AtomicReference<>();
private final AtomicBoolean open = new AtomicBoolean(false);
private final BiConsumer<T, T> serviceListener;
private final String filterString;
private final Filter filter;
public SingleServiceTracker(BundleContext context, Class<T> clazz, BiConsumer<T, T> sl) throws InvalidSyntaxException {
this(context, clazz, null, sl);
}
public SingleServiceTracker(BundleContext context, Class<T> clazz, String filterString, BiConsumer<T, T> sl) throws InvalidSyntaxException {
this(context, clazz.getName(), filterString, sl);
}
public SingleServiceTracker(BundleContext context, String className, String filterString, BiConsumer<T, T> sl) throws InvalidSyntaxException {
this.ctx = context;
this.className = className;
this.serviceListener = sl;
if (filterString == null || filterString.isEmpty()) {
this.filterString = null;
this.filter = null;
} else {
this.filterString = filterString;
this.filter = context.createFilter(filterString);
}
}
public T getService() {
return service.get();
}
public ServiceReference getServiceReference() {
return ref.get();
}
public void open() {
if (open.compareAndSet(false, true)) {
try {
String filterString = '(' + Constants.OBJECTCLASS + '=' + className + ')';
if (filter != null) filterString = "(&" + filterString + filter + ')';
ctx.addServiceListener(this, filterString);
findMatchingReference(null);
} catch (InvalidSyntaxException e) {
// this can never happen. (famous last words :)
}
}
}
public void serviceChanged(ServiceEvent event) {
if (open.get()) {
if (event.getType() == ServiceEvent.UNREGISTERING) {
ServiceReference deadRef = event.getServiceReference();
if (deadRef.equals(ref.get())) {
findMatchingReference(deadRef);
}
} else if (event.getType() == ServiceEvent.REGISTERED && ref.get() == null) {
findMatchingReference(null);
}
}
}
private void findMatchingReference(ServiceReference original) {
try {
boolean clear = true;
ServiceReference[] refs = ctx.getServiceReferences(className, filterString);
if (refs != null && refs.length > 0) {
if (refs.length > 1) {
Arrays.sort(refs);
}
@SuppressWarnings("unchecked")
T service = (T) ctx.getService(refs[0]);
if (service != null) {
clear = false;
// We do the unget out of the lock so we don't exit this class while holding a lock.
if (!update(original, refs[0], service)) {
ctx.ungetService(refs[0]);
}
}
} else if (original == null) {
clear = false;
}
if (clear) {
update(original, null, null);
}
} catch (InvalidSyntaxException e) {
// this can never happen. (famous last words :)
}
}
private boolean update(ServiceReference deadRef, ServiceReference newRef, T service) {
boolean result = false;
T prev = null;
// Make sure we don't try to get a lock on null
Object lock;
// we have to choose our lock.
if (newRef != null) lock = newRef;
else if (deadRef != null) lock = deadRef;
else lock = this;
// This lock is here to ensure that no two threads can set the ref and service
// at the same time.
synchronized (lock) {
if (open.get()) {
result = this.ref.compareAndSet(deadRef, newRef);
if (result) {
prev = this.service.getAndSet(service);
}
}
}
if (result && serviceListener != null) {
serviceListener.accept(prev, service);
}
return result;
}
public void close() {
if (open.compareAndSet(true, false)) {
ctx.removeServiceListener(this);
ServiceReference deadRef;
T prev;
synchronized (this) {
deadRef = ref.getAndSet(null);
prev = service.getAndSet(null);
}
if (deadRef != null) {
serviceListener.accept(prev, null);
ctx.ungetService(deadRef);
}
}
}
}
| 8,356 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/OsgiURLContextServiceFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.url;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
import javax.naming.spi.ObjectFactory;
/**
* A factory for the aries JNDI context
*/
public class OsgiURLContextServiceFactory implements ServiceFactory<ObjectFactory> {
public ObjectFactory getService(Bundle bundle, ServiceRegistration<ObjectFactory> registration) {
return new OsgiURLContextFactory(bundle.getBundleContext());
}
public void ungetService(Bundle bundle, ServiceRegistration<ObjectFactory> registration, ObjectFactory service) {
}
}
| 8,357 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/url/BlueprintURLContextServiceFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndi.url;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
import javax.naming.spi.ObjectFactory;
/**
* A factory for the aries blueprint context
*/
public class BlueprintURLContextServiceFactory implements ServiceFactory<ObjectFactory> {
@Override
public ObjectFactory getService(Bundle bundle, ServiceRegistration<ObjectFactory> registration) {
return new BlueprintURLContextFactory(bundle);
}
@Override
public void ungetService(Bundle bundle, ServiceRegistration registration, ObjectFactory service) {
}
}
| 8,358 |
0 | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url/src/main/java/org/apache/aries/jndi/services/ServiceHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.services;
import org.apache.aries.jndi.url.Activator;
import org.apache.aries.jndi.url.OsgiName;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.proxy.UnableToProxyException;
import org.osgi.framework.*;
import org.osgi.service.jndi.JNDIConstants;
import javax.naming.NamingException;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* This helper provides access to services registered in the OSGi service registry.
* If a matching service cannot be located null may be returned. A caller should not
* expect to get the same object if multiple requests are made to this API. A caller
* should not expect to get a different object if multiple requests are made to this API.
* A caller should avoid caching the returned service. OSGi is a dynamic environment and
* the service may become unavailable while a reference to it is held. To minimize this
* risk the caller should hold onto the service for the minimum length of time.
* <p>
* <p>This API should not be used from within an OSGi bundle. When in an OSGi environment
* the BundleContext for the bundle should be used to obtain the service.
* </p>
*/
public final class ServiceHelper {
/**
* A cache of proxies returned to the client
*/
private static final ConcurrentMap<ServiceKey, WeakReference<Object>> proxyCache = new ConcurrentHashMap<>();
private static final CacheClearoutListener cacheClearoutListener = new CacheClearoutListener(proxyCache);
public static Object getService(BundleContext ctx, OsgiName lookupName, String id,
boolean dynamicRebind, Map<String, Object> env, boolean requireProxy) throws NamingException {
String interfaceName = lookupName.getInterface();
String filter = lookupName.getFilter();
String serviceName = lookupName.getServiceName();
if (id != null) {
if (filter == null) {
filter = '(' + Constants.SERVICE_ID + '=' + id + ')';
} else {
filter = "(&(" + Constants.SERVICE_ID + '=' + id + ')' + filter + ')';
}
}
ServicePair pair = null;
if (!lookupName.isServiceNameBased()) {
pair = findService(ctx, interfaceName, filter);
}
if (pair == null) {
interfaceName = null;
if (id == null) {
filter = "(" + JNDIConstants.JNDI_SERVICENAME + "=" + serviceName + ')';
} else {
filter = "(&(" + Constants.SERVICE_ID + '=' + id + ")(" + JNDIConstants.JNDI_SERVICENAME
+ "=" + serviceName + "))";
}
pair = findService(ctx, interfaceName, filter);
}
Object result = null;
if (pair != null) {
if (requireProxy) {
Object obj = env.get(org.apache.aries.jndi.api.JNDIConstants.REBIND_TIMEOUT);
int timeout = 0;
if (obj instanceof String) {
timeout = Integer.parseInt((String) obj);
} else if (obj instanceof Integer) {
timeout = (Integer) obj;
}
result = proxy(interfaceName, filter, dynamicRebind, ctx, pair, timeout);
} else {
result = pair.service;
}
}
return result;
}
private static Object proxy(final String interface1, final String filter, final boolean rebind,
final BundleContext ctx, final ServicePair pair, final int timeout) {
Object result = null;
Bundle owningBundle = ctx.getBundle();
ServiceKey k = new ServiceKey(owningBundle, pair.ref.getBundle(), (Long) pair.ref.getProperty(Constants.SERVICE_ID));
WeakReference<Object> proxyRef = proxyCache.get(k);
if (proxyRef != null) {
result = proxyRef.get();
if (result == null) {
proxyCache.remove(k, proxyRef);
}
}
if (result == null) {
if (System.getSecurityManager() != null) {
result = AccessController.doPrivileged((PrivilegedAction<Object>) () -> proxyPrivileged(interface1, filter, rebind, ctx, pair, timeout));
} else {
result = proxyPrivileged(interface1, filter, rebind, ctx, pair, timeout);
}
proxyRef = new WeakReference<>(result);
// if we have two threads doing a put and then clashing we ignore it. The code to ensure only
// one wins is quite complex to save a few bytes of memory and millis of execution time.
proxyCache.putIfAbsent(k, proxyRef);
cacheClearoutListener.add(ctx, k);
}
return result;
}
private static Object proxyPrivileged(String interface1, String filter, boolean dynamicRebind, BundleContext ctx, ServicePair pair, int timeout) {
String[] interfaces;
if (interface1 != null) {
interfaces = new String[]{interface1};
} else {
interfaces = (String[]) pair.ref.getProperty(Constants.OBJECTCLASS);
}
List<Class<?>> clazz = new ArrayList<>(interfaces.length);
// We load the interface classes the service is registered under using the defining bundle.
// This is ok because the service must be able to see the classes to be registered using them.
// We then check to see if isAssignableTo on the reference works for the owning bundle and
// the interface name and only use the interface if true is returned there.
// This might seem odd, but equinox and felix return true for isAssignableTo if the
// Bundle provided does not import the package. This is under the assumption the
// caller will then use reflection. The upshot of doing it this way is that a utility
// bundle can be created which centralizes JNDI lookups, but the service will be used
// by another bundle. It is true that class space consistency is less safe, but we
// are enabling a slightly odd use case anyway.
// August 13th 2013: We've found valid use cases in which a Bundle is exporting
// services that the Bundle itself cannot load. We deal with this rare case by
// noting the classes that we failed to load. If as a result we have no classes
// to proxy, we try those classes again but instead pull the Class objects off
// the service rather than from the bundle exporting that service.
Bundle serviceProviderBundle = pair.ref.getBundle();
Bundle owningBundle = ctx.getBundle();
ProxyManager proxyManager = Activator.getProxyManager();
Collection<String> classesNotFound = new ArrayList<>();
for (String interfaceName : interfaces) {
try {
Class<?> potentialClass = serviceProviderBundle.loadClass(interfaceName);
if (pair.ref.isAssignableTo(owningBundle, interfaceName)) {
clazz.add(potentialClass);
}
} catch (ClassNotFoundException e) {
classesNotFound.add(interfaceName);
}
}
if (clazz.isEmpty() && !classesNotFound.isEmpty()) {
Class<?> ifacesOnService[] = ctx.getService(pair.ref).getClass().getInterfaces();
for (String interfaceName : classesNotFound) {
Class<?> thisClass = null;
for (Class<?> c : getAllInterfaces(ifacesOnService)) {
if (c.getName().equals(interfaceName)) {
thisClass = c;
break;
}
}
if (thisClass != null) {
if (pair.ref.isAssignableTo(owningBundle, interfaceName)) {
clazz.add(thisClass);
}
}
}
}
if (clazz.isEmpty()) {
throw new IllegalArgumentException(Arrays.asList(interfaces).toString());
}
Callable<Object> ih = new JNDIServiceDamper(ctx, interface1, filter, pair, dynamicRebind, timeout);
// The ClassLoader needs to be able to load the service interface
// classes so it needs to be
// wrapping the service provider bundle. The class is actually defined
// on this adapter.
try {
return proxyManager.createDelegatingProxy(serviceProviderBundle, clazz, ih, null);
} catch (UnableToProxyException e) {
throw new IllegalArgumentException(e);
} catch (RuntimeException e) {
throw new IllegalArgumentException("Unable to create a proxy for " + pair.ref + ".", e);
}
}
private static ServicePair findService(BundleContext ctx, String interface1, String filter)
throws NamingException {
ServicePair p = null;
try {
ServiceReference<?>[] refs = ctx.getServiceReferences(interface1, filter);
if (refs != null) {
// natural order is the exact opposite of the order we desire.
Arrays.sort(refs, Comparator.reverseOrder());
for (ServiceReference<?> ref : refs) {
Object service = ctx.getService(ref);
if (service != null) {
p = new ServicePair();
p.ref = ref;
p.service = service;
break;
}
}
}
} catch (InvalidSyntaxException e) {
// If we get an invalid syntax exception we just ignore it. Null
// will be returned which
// is valid and that may result in a NameNotFoundException if that
// is the right thing to do
}
return p;
}
public static ServiceReference<?>[] getServiceReferences(BundleContext ctx, String interface1,
String filter, String serviceName, Map<String, Object> env) throws NamingException {
ServiceReference<?>[] refs;
try {
refs = ctx.getServiceReferences(interface1, filter);
if (refs == null || refs.length == 0) {
refs = ctx.getServiceReferences((String) null, "(" + JNDIConstants.JNDI_SERVICENAME + "="
+ serviceName + ')');
}
} catch (InvalidSyntaxException e) {
throw (NamingException) new NamingException(e.getFilter()).initCause(e);
}
if (refs != null) {
// natural order is the exact opposite of the order we desire.
Arrays.sort(refs, Comparator.reverseOrder());
}
return refs;
}
public static Object getService(BundleContext ctx, ServiceReference<?> ref) {
Object service = ctx.getService(ref);
if (service == null) {
return null;
}
ServicePair pair = new ServicePair();
pair.ref = ref;
pair.service = service;
return proxy(null, null, false, ctx, pair, 0);
}
static Collection<Class<?>> getAllInterfaces(Class<?>[] baseInterfaces) {
Set<Class<?>> result = new HashSet<>();
for (Class<?> c : baseInterfaces) {
if (!c.equals(Object.class)) {
result.add(c);
Class<?> ifaces[] = c.getInterfaces();
if (ifaces.length != 0) {
result.addAll(getAllInterfaces(ifaces));
}
}
}
return result;
}
public static final class CacheClearoutListener implements BundleListener, ServiceListener {
/**
* The cache to purge
*/
private final ConcurrentMap<ServiceKey, WeakReference<Object>> cache;
public CacheClearoutListener(ConcurrentMap<ServiceKey, WeakReference<Object>> pc) {
cache = pc;
}
public void bundleChanged(BundleEvent event) {
if (event.getType() == BundleEvent.STOPPED) {
Bundle b = event.getBundle();
cache.keySet().removeIf(key -> key.requesting == b);
}
}
public void serviceChanged(ServiceEvent event) {
if (event.getType() == ServiceEvent.UNREGISTERING) {
ServiceReference ref = event.getServiceReference();
Long serviceId = (Long) ref.getProperty(Constants.SERVICE_ID);
Bundle registeringBundle = ref.getBundle();
Iterator<ServiceKey> keys = cache.keySet().iterator();
while (keys.hasNext()) {
ServiceKey key = keys.next();
if (key.registering == registeringBundle && serviceId.equals(key.serviceId)) {
keys.remove();
break;
}
}
}
}
public void add(final BundleContext ctx, ServiceKey k) {
// try to use the system bundle for our listener, if that fails we fall back to the calling context
BundleContext systemBundle;
Bundle system = ctx.getBundle(0);
if (system != null) {
if (System.getSecurityManager() != null) {
systemBundle = AccessController.doPrivileged((PrivilegedAction<BundleContext>) system::getBundleContext);
} else {
systemBundle = system.getBundleContext();
}
} else {
systemBundle = ctx;
}
systemBundle.addBundleListener(cacheClearoutListener);
systemBundle.addServiceListener(cacheClearoutListener);
}
}
private static final class ServiceKey {
private final Bundle requesting;
private final Bundle registering;
private final Long serviceId;
private final int hash;
public ServiceKey(Bundle owningBundle, Bundle registeringBundle, Long property) {
requesting = owningBundle;
registering = registeringBundle;
serviceId = property;
hash = serviceId.intValue() * 100003 + System.identityHashCode(requesting);
}
public int hashCode() {
return hash;
}
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other instanceof ServiceKey) {
ServiceKey otherKey = (ServiceKey) other;
return (otherKey.requesting == requesting && otherKey.serviceId.equals(serviceId));
}
return false;
}
}
private static class JNDIServiceDamper implements Callable<Object> {
private BundleContext ctx;
private ServicePair pair;
private String interfaceName;
private String filter;
private boolean dynamic;
private int rebindTimeout;
public JNDIServiceDamper(BundleContext context, String i, String f, ServicePair service,
boolean d, int timeout) {
ctx = context;
pair = service;
interfaceName = i;
filter = f;
dynamic = d;
rebindTimeout = timeout;
}
public Object call() throws NamingException {
if (pair == null || pair.ref.getBundle() == null) {
if (dynamic) {
pair = findService(ctx, interfaceName, filter);
if (pair == null && rebindTimeout > 0) {
long startTime = System.currentTimeMillis();
try {
while (pair == null && System.currentTimeMillis() - startTime < rebindTimeout) {
Thread.sleep(100);
pair = findService(ctx, interfaceName, filter);
}
} catch (InterruptedException e) {
}
}
} else {
pair = null;
}
}
if (pair == null) {
throw new ServiceException(interfaceName, ServiceException.UNREGISTERED);
}
return pair.service;
}
}
private static class ServicePair {
private ServiceReference<?> ref;
private Object service;
}
}
| 8,359 |
0 | Create_ds/aries/jndi/jndi-url-itest/src/test/java/org/apache/aries/jndi | Create_ds/aries/jndi/jndi-url-itest/src/test/java/org/apache/aries/jndi/itests/JndiUrlIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.jndi.itests;
import org.apache.aries.itest.AbstractIntegrationTest;
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.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.*;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public class JndiUrlIntegrationTest extends AbstractIntegrationTest {
private static final int CONNECTION_TIMEOUT = 10000;
private static HttpURLConnection makeConnection(String contextPath) throws IOException {
URL url = new URL(contextPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.connect();
return conn;
}
private static String getHTTPResponse(HttpURLConnection conn) throws IOException {
StringBuilder response = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-1"));
try {
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
response.append(s).append("\r\n");
}
} finally {
reader.close();
}
return response.toString();
}
/**
* This test exercises the blueprint:comp/ jndi namespace by driving
* a Servlet which then looks up some blueprint components from its own
* bundle, including a reference which it uses to call a service from a
* second bundle.
*
* @throws Exception
*/
@Test
public void testBlueprintCompNamespaceWorks() throws Exception {
Bundle bBiz = context().getBundleByName("org.apache.aries.jndi.url.itest.biz");
assertNotNull(bBiz);
Bundle bweb = context().getBundleByName("org.apache.aries.jndi.url.itest.web");
assertNotNull(bweb);
context().getBundleByName("org.ops4j.pax.web.pax-web-extender-war").start();
printBundleStatus("Before making web request");
try {
Thread.sleep(5000);
} catch (InterruptedException ix) {
}
System.out.println("In test and trying to get connection....");
String response = getTestServletResponse();
System.out.println("Got response `" + response + "`");
assertEquals("ITest servlet response wrong", "Mark.2.0.three", response);
}
private void printBundleStatus(String msg) {
System.out.println("-----\nprintBundleStatus: " + msg + "\n-----");
for (Bundle b : bundleContext.getBundles()) {
System.out.println(b.getSymbolicName() + " " + "state=" + formatState(b.getState()));
}
System.out.println();
}
private String formatState(int state) {
String result = Integer.toString(state);
switch (state) {
case Bundle.ACTIVE:
result = "Active";
break;
case Bundle.INSTALLED:
result = "Installed";
break;
case Bundle.RESOLVED:
result = "Resolved";
break;
}
return result;
}
private String getTestServletResponse() throws IOException {
HttpURLConnection conn = makeConnection("http://localhost:8080/jndiUrlItest/ITestServlet");
String response = getHTTPResponse(conn).trim();
return response;
}
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(),
// this is how you set the default log level when using pax
// logging (logProfile)
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo))
);
}
@Configuration
public Option[] configuration() {
return CoreOptions.options(
baseOptions(),
// Bundles
mavenBundle("org.eclipse.equinox", "cm").versionAsInProject(),
mavenBundle("org.eclipse.osgi", "services").versionAsInProject(),
mavenBundle("org.apache.geronimo.specs", "geronimo-servlet_2.5_spec").versionAsInProject(),
mavenBundle("org.ops4j.pax.web", "pax-web-extender-war").versionAsInProject(),
mavenBundle("org.ops4j.pax.web", "pax-web-jetty-bundle").versionAsInProject(),
mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.api").versionAsInProject(),
mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.core").versionAsInProject(),
mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy.api").versionAsInProject(),
mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy.impl").versionAsInProject(),
mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(),
mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi").versionAsInProject(),
mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi.url.itest.web").versionAsInProject(),
mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi.url.itest.biz").versionAsInProject(),
mavenBundle("org.ow2.asm", "asm-debug-all").versionAsInProject(),
mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(),
mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),
mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject()
);
// org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=7777"),
// org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartup(),
}
}
| 8,360 |
0 | Create_ds/aries/jndi/jndi-legacy-support/src/main/java/org/apache/aries/jndi/legacy | Create_ds/aries/jndi/jndi-legacy-support/src/main/java/org/apache/aries/jndi/legacy/support/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.jndi.legacy.support;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import javax.naming.spi.InitialContextFactoryBuilder;
public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
context.registerService(InitialContextFactoryBuilder.class.getName(), new LegacyInitialContextFinder(), null);
}
@Override
public void stop(BundleContext context) throws Exception {
}
}
| 8,361 |
0 | Create_ds/aries/jndi/jndi-legacy-support/src/main/java/org/apache/aries/jndi/legacy | Create_ds/aries/jndi/jndi-legacy-support/src/main/java/org/apache/aries/jndi/legacy/support/LegacyInitialContextFinder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jndi.legacy.support;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Hashtable;
/**
* Some OSGi based server runtimes, such as jetty OSGi and virgo rely on the thread context classloader
* to make their JNDI InitialContextFactory's available in OSGi, rather than relying on the OSGi JNDI spec.
* This is a little bizare, but perhaps is just a point in time statement. In any case to support them
* using Aries JNDI we have this ICFB which uses the Thread context classloader. We don't ship it in the
* jndi uber bundle because it is only for these runtimes which haven't caught up with the latest OSGi specs.
* Normally we want to enourage the use of the OSGi spec, but this is a backstop for those wanting to use
* Aries JNDI and one of these runtimes.
*
*/
public class LegacyInitialContextFinder implements InitialContextFactoryBuilder {
public InitialContextFactory createInitialContextFactory(
Hashtable<?, ?> environment) throws NamingException {
String icf = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
if (icf != null) {
ClassLoader cl;
if (System.getSecurityManager() != null) {
cl = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) Thread.currentThread()::getContextClassLoader);
} else {
cl = Thread.currentThread().getContextClassLoader();
}
try {
Class<?> icfClass = Class.forName(icf, false, cl);
if (InitialContextFactory.class.isAssignableFrom(icfClass)) {
return (InitialContextFactory) icfClass.newInstance();
}
} catch (ClassNotFoundException e) {
// If the ICF doesn't exist this is expected. Should return null so the next builder is queried.
} catch (InstantiationException e) {
// If the ICF couldn't be created just ignore and return null.
} catch (IllegalAccessException e) {
// If the default constructor is private, just ignore and return null.
}
}
return null;
}
}
| 8,362 |
0 | Create_ds/aries/sandbox/samples/bank/bank-web/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-web/src/main/java/org/apache/aries/samples/bank/web/ViewAccount.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.web;
import java.io.IOException;
import java.io.Writer;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.aries.samples.bank.api.AccountServicesToOutsideWorld;
/**
* Servlet implementation class ViewAccount
*/
public class ViewAccount extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int accountNumber = Integer.parseInt(request.getParameter("accountNumber"));
Writer writer = response.getWriter();
writer.write("<html><head></head><body>");
AccountServicesToOutsideWorld accAccess;
try {
InitialContext ic = new InitialContext();
accAccess = (AccountServicesToOutsideWorld) ic.lookup("osgi:service/"
+ AccountServicesToOutsideWorld.class.getName());
} catch (NamingException nx) {
throw new ServletException(nx);
}
if (accAccess != null) {
String operation = request.getParameter("operation");
if (operation != null) {
int amount = Integer.parseInt(request.getParameter("amount"));
if (operation.equals("deposit")) {
accAccess.deposit(accountNumber, amount);
} else if (operation.equals("withdraw")) {
accAccess.withdraw(accountNumber, amount);
} else {
System.out.println("Unknown operation " + operation
+ " in ViewAccount");
}
}
String name = accAccess.name(accountNumber);
int balance = accAccess.balance(accountNumber);
writer.write("<br/>Account " + accountNumber + " name `"
+ name + "` balance: " + balance);
// Deposit or withdraw
writer.write("<form action=\"ViewAccount\" method=\"POST\">");
writer.write("<input type=\"hidden\" name=\"accountNumber\" value=\""
+ accountNumber + "\"/>");
writer.write("<select name=\"operation\"><option value=\"deposit\">deposit</option>");
writer.write("<option value=\"withdraw\">withdraw</option></select>");
writer.write("<input name=\"amount\" type=\"text\"/>");
writer.write("<input type=\"submit\" value=\"submit request\" /></form>");
//TODO: transfer
writer.write("<br/>TODO: Form to make a transfer goes here<br/>");
writer.write("<a href=\"index.html\">back to main menu</a>");
} else {
writer.write("<br/>ERROR: Unable to find AccountAccessService");
}
writer.write("</body></html>");
writer.close();
}
}
| 8,363 |
0 | Create_ds/aries/sandbox/samples/bank/bank-web/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-web/src/main/java/org/apache/aries/samples/bank/web/CreateAccount.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.web;
import java.io.IOException;
import java.io.Writer;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.aries.samples.bank.api.AccountServicesToOutsideWorld;
/**
* Servlet implementation class CreateAccount
*/
public class CreateAccount extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
int assets = Integer.parseInt(request.getParameter("assets"));
int liabilities = Integer.parseInt(request.getParameter("liabilities"));
String accountType = request.getParameter("accountType");
Writer writer = response.getWriter();
AccountServicesToOutsideWorld accAccess;
try {
InitialContext ic = new InitialContext();
accAccess = (AccountServicesToOutsideWorld) ic.lookup
("osgi:service/" + AccountServicesToOutsideWorld.class.getName());
} catch (NamingException nx) {
throw new ServletException (nx);
}
int newAccountNumber;
if (accAccess != null) {
if (accountType.equals("Chequing")) {
newAccountNumber = accAccess.openChequingAccount(name, assets, liabilities);
} else {
newAccountNumber = accAccess.openLineOfCreditAccount(name, assets, liabilities);
}
writer.write("<html><head></head><body>");
if (newAccountNumber >= 0) {
writer.write ("Successfully opened <a href=\"ViewAccount?accountNumber=" + newAccountNumber
+ "\">Account number " + newAccountNumber + "</a>");
} else {
writer.write ("New account request denied: computer says no.");
}
} else {
writer.write("<br/>INTERNAL ERROR: Unable to find AccountAccessService");
}
writer.write("<br/><br/><a href=\"index.html\">back to main menu</a></body></html>");
}
}
| 8,364 |
0 | Create_ds/aries/sandbox/samples/bank/bank-creditCheck/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-creditCheck/src/main/java/org/apache/aries/samples/bank/creditCheck/CreditCheckServiceImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.cc;
import org.apache.aries.samples.bank.api.CreditCheckService;
public class CreditCheckServiceImpl implements CreditCheckService {
private static final int MIN = -10000;
private static final int MAX = 10000;
@Override
public double risk(String name, int assets, int liabilities) {
int equity = assets - liabilities;
double risk = 1.0;
if (equity <= MIN)
risk = 1.0;
else if (equity >= MAX)
risk = 0.0;
else
risk = ((double)(MAX-equity)) / (MAX-MIN);
System.out.println("EJB: CreditCheck.risk("+name+","+assets+","+liabilities+") = "+risk);
return risk;
}
}
| 8,365 |
0 | Create_ds/aries/sandbox/samples/bank/bank-lineOfCreditAccount/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-lineOfCreditAccount/src/main/java/org/apache/aries/samples/bank/lineOfCreditAccount/LineOfCreditAccountServiceImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.loc;
import org.apache.aries.samples.bank.api.Constants;
import org.apache.aries.samples.bank.api.LineOfCreditAccountService;
// We could make an Abstract class to base this and ChequingAccountServiceImpl from if we decide
// to keep those two classes around.
public class LineOfCreditAccountServiceImpl implements LineOfCreditAccountService {
class AccountRecord {
String name;
public String getName() {
return name;
}
int balance;
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public AccountRecord (String name) {
this.name = name;
balance = 0;
}
}
private static final int BASE = Constants.LINEOFCREDIT_ACCOUNT_BASE;
private static int nextAccount_ = BASE;
private static AccountRecord[] _accounts = new AccountRecord[10];
@Override
public int open(String name) {
int accountNumber = nextAccount_++;
_accounts[accountNumber-BASE] = new AccountRecord (name);
System.out.println("LineOfCreditAccountServiceImpl.open() = "+accountNumber);
return accountNumber;
}
@Override
public int balance(int accountNumber) {
int balance = _accounts[accountNumber-BASE].getBalance();
System.out.println("LineOfCreditAccountServiceImpl.balance("+accountNumber+") = "+balance);
return balance;
}
@Override
public void deposit(int accountNumber, int funds) {
AccountRecord record = _accounts[accountNumber-BASE];
record.setBalance(record.getBalance() + funds);
System.out.println("LineOfCreditAccountServiceImpl.deposit("+accountNumber+","+funds+")");
}
@Override
public void withdraw(int accountNumber, int funds) {
AccountRecord record = _accounts[accountNumber-BASE];
record.setBalance(record.getBalance() - funds);
System.out.println("LineOfCreditAccountServiceImpl.withdraw("+accountNumber+","+funds+")");
}
@Override
public String name(int accountNumber) {
String name =_accounts[accountNumber-BASE].getName();
System.out.println ("LineOfCreditAccountServiceImpl.getName("+accountNumber+" = " + name);
return name;
}
}
| 8,366 |
0 | Create_ds/aries/sandbox/samples/bank/bank-biz/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-biz/src/main/java/org/apache/aries/samples/bank/biz/AccountServicesToOutsideWorldImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.biz;
import org.apache.aries.samples.bank.api.AccountService;
import org.apache.aries.samples.bank.api.AccountServicesToOutsideWorld;
import org.apache.aries.samples.bank.api.ChequingAccountService;
import org.apache.aries.samples.bank.api.Constants;
import org.apache.aries.samples.bank.api.CreditCheckService;
import org.apache.aries.samples.bank.api.LineOfCreditAccountService;
public class AccountServicesToOutsideWorldImpl implements AccountServicesToOutsideWorld {
private ChequingAccountService _chequingAccountService;
private LineOfCreditAccountService _lineOfCreditAccountService;
private CreditCheckService _creditCheckService;
private double _riskThreshold;
public void setChequingAccountService(ChequingAccountService c) {
_chequingAccountService = c;
}
public void setLineOfCreditAccountService(LineOfCreditAccountService l) {
_lineOfCreditAccountService = l;
}
public void setCreditCheckService(CreditCheckService c) {
_creditCheckService = c;
}
public void setRiskThreshold(double r) {
_riskThreshold = r;
}
private static final int NO_ACCOUNT = -1;
@Override
public int openChequingAccount(String name, int assets, int liabilities) {
int accountNumber = _chequingAccountService.open(name);
System.out.println("AccountAccessServiceImpl.openChequingAccount(" + name + "," + assets + ","
+ liabilities + ") = " + accountNumber);
return accountNumber;
}
@Override
public int openLineOfCreditAccount(String name, int assets, int liabilities) {
System.out.println("AccountAccessServiceImpl.openLineOfCreditAccount(" + name + "," + assets
+ "," + liabilities + ") riskThreshold = " + _riskThreshold);
double risk = _creditCheckService.risk(name, assets, liabilities);
int accountNumber = NO_ACCOUNT;
if (risk < _riskThreshold)
accountNumber = _lineOfCreditAccountService.open(name);
System.out.println("AccountAccessServiceImpl.openLineOfCreditAccount(" + name + "," + assets
+ "," + liabilities + ") = " + accountNumber);
return accountNumber;
}
@Override
public int balance(int accountNumber) {
int balance = accountServiceFor(accountNumber).balance(accountNumber);
System.out.println("AccountAccessServiceImpl.balance(" + accountNumber + ") = " + balance);
return balance;
}
@Override
public void deposit(int accountNumber, int funds) {
accountServiceFor(accountNumber).deposit(accountNumber, funds);
System.out.println("AccountAccessServiceImpl.deposit(" + accountNumber + "," + funds + ")");
}
@Override
public void withdraw(int accountNumber, int funds) {
accountServiceFor(accountNumber).withdraw(accountNumber, funds);
System.out.println("AccountAccessServiceImpl.withdraw(" + accountNumber + "," + funds + ")");
}
@Override
public void transfer(int fromAccountNumber, int toAccountNumber, int funds) {
withdraw(fromAccountNumber, funds);
deposit(toAccountNumber, funds);
System.out.println("AccountAccessServiceImpl.transfer(" + fromAccountNumber + ","
+ toAccountNumber + "," + funds + ")");
}
@Override
public String name(int accountNumber) {
String result = accountServiceFor(accountNumber).name(accountNumber);
System.out.println("AccountServicesToOutsideWorldImpl.name(" + accountNumber + ") = " + result);
return result;
}
private AccountService accountServiceFor(int accountNumber) {
if (accountNumber >= Constants.CHEQUING_ACCOUNT_BASE
&& accountNumber <= Constants.CHEQUING_ACCOUNT_MAX)
return _chequingAccountService;
else if (accountNumber >= Constants.LINEOFCREDIT_ACCOUNT_BASE
&& accountNumber <= Constants.LINEOFCREDIT_ACCOUNT_MAX)
return _lineOfCreditAccountService;
else
return null;
}
}
| 8,367 |
0 | Create_ds/aries/sandbox/samples/bank/bank-chequingAccount/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-chequingAccount/src/main/java/org/apache/aries/samples/bank/chequingAccount/ChequingAccountServiceImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.chq;
import org.apache.aries.samples.bank.api.ChequingAccountService;
import org.apache.aries.samples.bank.api.Constants;
/* This class is to become a Session Bean according to our original design. */
public class ChequingAccountServiceImpl implements ChequingAccountService {
class AccountRecord {
String name;
public String getName() {
return name;
}
int balance;
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public AccountRecord (String name) {
this.name = name;
balance = 0;
}
}
private static final int BASE = Constants.CHEQUING_ACCOUNT_BASE;
private static int nextAccount_ = BASE;
private static AccountRecord[] _accounts = new AccountRecord[10];
@Override
public int open(String name) {
int accountNumber = nextAccount_++;
_accounts[accountNumber-BASE] = new AccountRecord (name);
System.out.println("ChequingAccountServiceImpl.open() = "+accountNumber);
return accountNumber;
}
@Override
public int balance(int accountNumber) {
int balance = _accounts[accountNumber-BASE].getBalance();
System.out.println("ChequingAccountServiceImpl.balance("+accountNumber+") = "+balance);
return balance;
}
@Override
public void deposit(int accountNumber, int funds) {
AccountRecord record = _accounts[accountNumber-BASE];
record.setBalance(record.getBalance() + funds);
System.out.println("ChequingAccountServiceImpl.deposit("+accountNumber+","+funds+")");
}
@Override
public void withdraw(int accountNumber, int funds) {
AccountRecord record = _accounts[accountNumber-BASE];
record.setBalance(record.getBalance() - funds);
System.out.println("ChequingAccountServiceImpl.withdraw("+accountNumber+","+funds+")");
}
@Override
public String name(int accountNumber) {
String name =_accounts[accountNumber-BASE].getName();
System.out.println ("ChequingAccountServiceImpl.getName("+accountNumber+" = " + name);
return name;
}
}
| 8,368 |
0 | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank/api/CreditCheckService.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.api;
public interface CreditCheckService {
public double risk (String name, int assets, int liabilities);
}
| 8,369 |
0 | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank/api/AccountServicesToOutsideWorld.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.api;
/* Front end to WSDL and web clients */
public interface AccountServicesToOutsideWorld
{
int openChequingAccount (String name, int assets, int liabilities);
int openLineOfCreditAccount (String name, int assets, int liabilities);
String name (int accountNumber);
int balance (int accountNumber);
void deposit (int accountNumber, int funds);
void withdraw (int accountNumber, int funds);
void transfer (int fromAccountNumber, int toAccountNumber, int funds);
}
| 8,370 |
0 | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank/api/AccountService.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.api;
public interface AccountService {
int open (String name);
String name(int accountNumber);
int balance (int accountNumber);
void deposit (int accountNumber, int funds);
void withdraw (int accountNumber, int funds);
}
| 8,371 |
0 | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank/api/ChequingAccountService.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.api;
public interface ChequingAccountService extends AccountService {
}
| 8,372 |
0 | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank/api/LineOfCreditAccountService.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.api;
public interface LineOfCreditAccountService extends AccountService {
}
| 8,373 |
0 | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank | Create_ds/aries/sandbox/samples/bank/bank-api/src/main/java/org/apache/aries/samples/bank/api/Constants.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.bank.api;
public final class Constants {
public static final int CHEQUING_ACCOUNT_BASE = 1000;
public static final int CHEQUING_ACCOUNT_MAX = 1999;
public static final int LINEOFCREDIT_ACCOUNT_BASE = 2000;
public static final int LINEOFCREDIT_ACCOUNT_MAX = 2999;
}
| 8,374 |
0 | Create_ds/aries/sandbox/samples/goat/goat-web/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-web/src/main/java/org/apache/aries/samples/goat/web/ServerSideClass.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.web;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.aries.samples.goat.info.ComponentInfoImpl;
import org.apache.aries.samples.goat.info.RelationshipInfoImpl;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.ModelInfoService;
import org.apache.aries.samples.goat.api.RelationshipInfo;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContextFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
public class ServerSideClass {
private String modelInfoServiceHint = "";
private ModelInfoService ModelInfoService = null;
private Map<ModelInfoService, ComponentInfoProvider.ComponentInfoListener> clisteners = new HashMap<ModelInfoService, ComponentInfoProvider.ComponentInfoListener>();
private Map<ModelInfoService, RelationshipInfoProvider.RelationshipInfoListener> rlisteners = new HashMap<ModelInfoService, RelationshipInfoProvider.RelationshipInfoListener>();
private class ComponentInfoListenerImpl implements
ComponentInfoProvider.ComponentInfoListener {
String server;
public ComponentInfoListenerImpl(String server) {
this.server = server;
}
public void updateComponent(ComponentInfo b) {
if (this.server.equals(modelInfoServiceHint)) {
// todo: only issue the add for the new bundle, and affected
// other bundles.
//getInitialComponents(modelInfoServiceHint);
//System.out.println("State is: " + b.getComponentProperties().get("State"));
addFunctionCall("addComponent", b);
}
}
public void removeComponent(ComponentInfo b) {
// todo
}
}
private class RelationshipInfoListenerImpl implements
RelationshipInfoProvider.RelationshipInfoListener {
String server;
public RelationshipInfoListenerImpl(String server) {
this.server = server;
}
public void updateRelationship(RelationshipInfo r) {
if (this.server.equals(modelInfoServiceHint)) {
addFunctionCall("addRelationship", r);
}
}
public void removeRelationship(RelationshipInfo r) {
// todo
}
}
public ServerSideClass() {
System.err.println("SSC Built!");
}
@SuppressWarnings("unused")
private String bundleStateToString(int bundleState) {
switch (bundleState) {
case Bundle.UNINSTALLED:
return "UNINSTALLED";
case Bundle.INSTALLED:
return "INSTALLED";
case Bundle.RESOLVED:
return "RESOLVED";
case Bundle.STARTING:
return "STARTING";
case Bundle.STOPPING:
return "STOPPING";
case Bundle.ACTIVE:
return "ACTIVE";
default:
return "UNKNOWN[" + bundleState + "]";
}
}
/**
* this is invoked by a page onload.. so until it's invoked.. we dont care
* about components
*/
public void getInitialComponents(String dataProvider) {
System.err.println("GET INITIAL BUNDLES ASKED TO USE DATAPROVIDER "
+ dataProvider);
if (dataProvider == null)
throw new IllegalArgumentException(
"Unable to accept 'null' as a dataProvider");
// do we need to update?
if (!this.modelInfoServiceHint.equals(dataProvider)) {
this.modelInfoServiceHint = dataProvider;
if (!(this.ModelInfoService == null)) {
// we already had a provider.. we need to shut down the existing
// components & relationships in the browsers..
addFunctionCall("forgetAboutEverything");
}
ServletContext context = org.directwebremoting.ServerContextFactory
.get().getServletContext();
Object o = context.getAttribute("osgi-bundlecontext");
if (o != null) {
if (o instanceof BundleContext) {
BundleContext b_ctx = (BundleContext) o;
System.err.println("Looking up bcip");
try {
ServiceReference sr[] = b_ctx.getServiceReferences(
ModelInfoService.class.getName(),
"(displayName=" + this.modelInfoServiceHint
+ ")");
if (sr != null) {
System.err.println("Getting bcip");
this.ModelInfoService = (ModelInfoService) b_ctx
.getService(sr[0]);
System.err.println("Got bcip "
+ this.ModelInfoService);
} else {
System.err.println("UNABLE TO FIND BCIP!!");
System.err.println("UNABLE TO FIND BCIP!!");
System.err.println("UNABLE TO FIND BCIP!!");
}
} catch (InvalidSyntaxException ise) {
}
if (this.ModelInfoService != null) {
if (!rlisteners.containsKey(this.ModelInfoService)) {
RelationshipInfoProvider.RelationshipInfoListener rl = new RelationshipInfoListenerImpl(
this.modelInfoServiceHint);
rlisteners.put(this.ModelInfoService, rl);
this.ModelInfoService.getRelationshipInfoProvider()
.registerRelationshipInfoListener(rl);
}
if (!clisteners.containsKey(this.ModelInfoService)) {
ComponentInfoProvider.ComponentInfoListener cl = new ComponentInfoListenerImpl(
this.modelInfoServiceHint);
clisteners.put(this.ModelInfoService, cl);
this.ModelInfoService.getComponentInfoProvider()
.registerComponentInfoListener(cl);
}
}
}
}
}
Collection<ComponentInfo> bis = this.ModelInfoService
.getComponentInfoProvider().getComponents();
System.err.println("Got " + (bis == null ? "null" : bis.size())
+ " components back from the provider ");
if (bis != null) {
for (ComponentInfo b : bis) {
System.err.println("Adding Component .. " + b.getId());
addFunctionCall("addComponent", b);
}
}
Collection<RelationshipInfo> ris = this.ModelInfoService
.getRelationshipInfoProvider().getRelationships();
System.err.println("Got " + (ris == null ? "null" : ris.size())
+ " relationships back from the provider ");
if (ris != null) {
for (RelationshipInfo r : ris) {
System.err.println("Adding relationship type " + r.getType()
+ " called " + r.getName() + " from "
+ r.getProvidedBy().getId());
addFunctionCall("addRelationship", r);
}
}
}
private void addFunctionCall(String name, Object... params) {
final ScriptBuffer script = new ScriptBuffer();
script.appendScript(name).appendScript("(");
for (int i = 0; i < params.length; i++) {
if (i != 0)
script.appendScript(",");
script.appendData(params[i]);
}
script.appendScript(");");
Browser.withAllSessions(new Runnable() {
public void run() {
for (ScriptSession s : Browser.getTargetSessions()) {
s.addScript(script);
}
}
});
}
public String[] getProviders() {
System.err.println("Getting providers...");
ArrayList<String> result = new ArrayList<String>();
ServletContext context = ServerContextFactory.get().getServletContext();
Object o = context.getAttribute("osgi-bundlecontext");
if (o != null) {
if (o instanceof BundleContext) {
BundleContext b_ctx = (BundleContext) o;
try {
System.err.println("Getting providers [2]...");
ServiceReference[] srs = b_ctx.getServiceReferences(
ModelInfoService.class.getName(), null);
System.err.println("Got.. " + srs);
if (srs == null || srs.length == 0) {
System.err.println("NO DATA PROVIDERS");
throw new RuntimeException(
"Unable to find any data providers");
}
System.err.println("Processing srs as loop.");
for (ServiceReference sr : srs) {
System.err.println("Processing srs entry...");
String name = (String.valueOf(sr
.getProperty("displayName")));
result.add(name);
}
System.err.println("Processed srs as loop.");
} catch (InvalidSyntaxException e) {
// wont happen, the exception relates to the filter, (2nd
// arg above), which is constant null.
}
}
}
System.err.println("Returning " + result.size());
String[] arr = new String[result.size()];
arr = result.toArray(arr);
for (String x : arr) {
System.err.println(" - " + x);
}
return arr;
}
}
| 8,375 |
0 | Create_ds/aries/sandbox/samples/goat/goat-bundlecontext-modelprovider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-bundlecontext-modelprovider/src/main/java/org/apache/aries/samples/goat/bundlecontextmodel/BundleContextInfoProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.bundlecontextmodel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.apache.aries.samples.goat.info.ComponentInfoImpl;
import org.apache.aries.samples.goat.info.RelationshipInfoImpl;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.ModelInfoService;
import org.apache.aries.samples.goat.api.RelationshipAspect;
import org.apache.aries.samples.goat.api.RelationshipInfo;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
public class BundleContextInfoProvider implements ModelInfoService, RelationshipInfoProvider, ComponentInfoProvider, BundleListener, ServiceListener {
private Map<String, ComponentInfo>biCache = new HashMap<String,ComponentInfo>();
private Map<String, RelationshipInfo>riCache = new HashMap<String,RelationshipInfo>();
private List<ComponentInfoListener> clisteners=null;
private List<RelationshipInfoListener> rlisteners=null;
private BundleContext ctx=null;
public BundleContextInfoProvider(BundleContext ctx){
System.err.println("BCIP built!");
this.ctx = ctx;
this.clisteners = Collections.synchronizedList(new ArrayList<ComponentInfoListener>());
this.rlisteners = Collections.synchronizedList(new ArrayList<RelationshipInfoListener>());
this.ctx.addBundleListener(this);
this.ctx.addServiceListener(this);
}
public List<ComponentInfo> getComponents() {
System.err.println("BCIP getBundles called");
Bundle[] bundles = this.ctx.getBundles();
List<ComponentInfo> result = new ArrayList<ComponentInfo>();
for(int i=0; i<bundles.length; i++){
System.err.println("BCIP converting "+i);
result.add( getComponentForId( getKeyForBundle(bundles[i])) );
}
System.err.println("BCIP returning data");
return result;
}
public void registerComponentInfoListener(ComponentInfoListener listener) {
clisteners.add(listener);
}
public void registerRelationshipInfoListener(RelationshipInfoListener listener) {
rlisteners.add(listener);
}
private Bundle getBundleForIDKey(BundleContext ctx, String id){
String s =id.substring("/root/".length());
Long l = Long.parseLong(s);
return ctx.getBundle(l.longValue());
}
private String bundleStateToString(int bundleState){
switch(bundleState){
case Bundle.UNINSTALLED : return "UNINSTALLED";
case Bundle.INSTALLED : return "INSTALLED";
case Bundle.RESOLVED : return "RESOLVED";
case Bundle.STARTING : return "STARTING";
case Bundle.STOPPING : return "STOPPING";
case Bundle.ACTIVE : return "ACTIVE";
default : return "UNKNOWN["+bundleState+"]";
}
}
public ComponentInfo getComponentForId(String id) {
if(biCache.containsKey(id)){
return biCache.get(id);
}
Bundle b = getBundleForIDKey(ctx,id);
ComponentInfoImpl bii = new ComponentInfoImpl();
bii.setId(getKeyForBundle(b));
HashSet<Long> allDepSet = new HashSet<Long>();
bii.setComponentProperties(new HashMap<String,String>());
bii.getComponentProperties().put("BundleID", ""+b.getBundleId());
bii.getComponentProperties().put("State", bundleStateToString(b.getState()));
bii.getComponentProperties().put("SymbolicName", b.getSymbolicName());
bii.getComponentProperties().put("Version", ""+b.getVersion());
Enumeration<String> e = b.getHeaders().keys();
while(e.hasMoreElements()){
String key = e.nextElement();
//Ideally we'd add everything here.. but until we add the filtering in the ui
//its easier to just filter here.. for now, all 'extra' properties are removed.
if(! (key.equals("Import-Package") || key.equals("Export-Package")) ){
//bii.getComponentProperties().put(key, String.valueOf(b.getHeaders().get(key)));
}
}
bii.setChildren(new ArrayList<ComponentInfo>());
biCache.put(id, bii);
return bii;
}
public void bundleChanged(BundleEvent arg0) {
String id = getKeyForBundle(arg0.getBundle());
if(biCache.containsKey(id)){
biCache.remove(id);
}
ComponentInfo bi = getComponentForId(getKeyForBundle(arg0.getBundle()));
for(ComponentInfoListener bil : clisteners){
bil.updateComponent(bi);
}
}
private String getKeyForBundle(Bundle b){
return "/root/"+b.getBundleId();
}
@Override
public List<RelationshipInfo> getRelationships() {
ArrayList<RelationshipInfo> r = new ArrayList<RelationshipInfo>();
Bundle bundles[] = ctx.getBundles();
PackageAdmin pa = (PackageAdmin)ctx.getService(ctx.getServiceReference(PackageAdmin.class.getName().toString()));
if(bundles!=null && bundles.length!=0){
for(Bundle b: bundles){
String bkey = getKeyForBundle(b);
ComponentInfo ci = getComponentForId(bkey);
//add all the packages..
//we only add exports, as imports are implied in the reverse
ExportedPackage eps[] = pa.getExportedPackages(b);
if(eps!=null && eps.length!=0){
for(ExportedPackage ep : eps){
RelationshipInfoImpl ri = new RelationshipInfoImpl();
ri.setProvidedBy( ci );
ri.setType("Package");
ri.setName(ep.getName());
ri.setRelationshipAspects(new ArrayList<RelationshipAspect>());
ri.setConsumedBy(new ArrayList<ComponentInfo>());
//TODO: add versioning aspect.
Bundle imps[] = ep.getImportingBundles();
if(imps!=null && imps.length!=0){
for(Bundle imp : imps){
ri.getConsumedBy().add(getComponentForId(getKeyForBundle(imp)));
}
}
r.add(ri);
}
}
//add all the services..
//we only add registered services, as ones in use are handled in the reverse
ServiceReference srs[] = b.getRegisteredServices();
if(srs!=null && srs.length!=0){
for(ServiceReference sr : srs){
RelationshipInfoImpl ri = getRIforSR(sr);
ri.setProvidedBy( ci );
r.add(ri);
}
}
}
}
return r;
}
private RelationshipInfoImpl getRIforSR(ServiceReference sr){
RelationshipInfoImpl ri = new RelationshipInfoImpl();
ri.setType("Service");
String serviceNames="";
String []objectClasses = (String[])sr.getProperty("objectClass");
if(objectClasses!=null){
for(String objectClass : objectClasses){
serviceNames+=","+objectClass;
}
}
if(serviceNames.length()>1){
serviceNames = serviceNames.substring(1);
}
ri.setName(serviceNames);
ri.setRelationshipAspects(new ArrayList<RelationshipAspect>());
//TODO: add service parameters
ri.setConsumedBy(new ArrayList<ComponentInfo>());
Bundle using[] = sr.getUsingBundles();
if(using!=null && using.length!=0){
for(Bundle u : using){
ri.getConsumedBy().add(getComponentForId(getKeyForBundle(u)));
}
}
return ri;
}
@Override
public String getName() {
return "Bundle Context Info Provider 1.0";
}
@Override
public ComponentInfoProvider getComponentInfoProvider() {
return this;
}
@Override
public RelationshipInfoProvider getRelationshipInfoProvider() {
return this;
}
@Override
public void serviceChanged(ServiceEvent arg0) {
if(arg0.getType() == ServiceEvent.REGISTERED || arg0.getType() == ServiceEvent.MODIFIED || arg0.getType() == ServiceEvent.MODIFIED_ENDMATCH){
ServiceReference sr = arg0.getServiceReference();
RelationshipInfoImpl ri = getRIforSR(sr);
ComponentInfo ci = getComponentForId(getKeyForBundle(sr.getBundle()));
ri.setProvidedBy(ci);
for(RelationshipInfoListener ril : rlisteners){
ril.updateRelationship(ri);
}
}else if(arg0.getType() == ServiceEvent.UNREGISTERING){
ServiceReference sr = arg0.getServiceReference();
RelationshipInfoImpl ri = getRIforSR(sr);
ComponentInfo ci = getComponentForId(getKeyForBundle(sr.getBundle()));
ri.setProvidedBy(ci);
for(RelationshipInfoListener ril : rlisteners){
ril.removeRelationship(ri);
}
}
}
}
| 8,376 |
0 | Create_ds/aries/sandbox/samples/goat/goat-info-enhancer/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-info-enhancer/src/main/java/org/apache/aries/samples/goat/enhancer/ServiceInterceptor.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.enhancer;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import org.apache.aries.samples.goat.api.ModelInfoService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
public class ServiceInterceptor implements ServiceListener {
private static final String DISPLAY_NAME = "displayName";
/**
*
*/
public static final String SERVICE_ID = "service.id";
private final BundleContext ctx;
private final Map<String, ServiceRegistration> registrations = new HashMap<String, ServiceRegistration>();
public ServiceInterceptor(BundleContext ctx) {
this.ctx = ctx;
// Check all the existing services
try {
// Handle any existing services
ServiceReference[] references = ctx.getAllServiceReferences(
ModelInfoService.class.getName(), null);
ctx.addServiceListener(this, "(objectclass='"
+ ModelInfoService.class.getName() + "')");
//If we found any service references...
if(references != null && references.length != 0) {
for (ServiceReference reference : references) {
registerServiceEnhancer(reference);
}
}
} catch (InvalidSyntaxException e) {
e.printStackTrace();
}
// We could listen for find events and mask the original services if we
// wanted to
// ServiceRegistration findRegistration =
// ctx.registerService(FindHook.class.getName(),
// new InterceptorFindHook(), null);
}
/*
* (non-Javadoc)
*
* @see
* org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.
* ServiceEvent)
*/
@Override
public void serviceChanged(ServiceEvent event) {
ServiceReference reference = event.getServiceReference();
if (event != null && event.getType() == ServiceEvent.REGISTERED) {
registerServiceEnhancer(reference);
} else if (event != null
&& event.getType() == ServiceEvent.UNREGISTERING) {
// Better unregister our enhancer
Object id = reference.getProperty(SERVICE_ID);
ServiceRegistration registration = registrations.get(id);
if (registration != null) {
registration.unregister();
registrations.remove(id);
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void registerServiceEnhancer(ServiceReference reference) {
Object actualService = ctx.getService(reference);
if (actualService instanceof ModelInfoService) {
ModelInfoService infoService = (ModelInfoService) actualService;
Object serviceId = reference.getProperty(SERVICE_ID);
Object enhancer = new ModelInfoEnhancerService(infoService);
Dictionary properties = new Hashtable();
Object originalDisplayName = reference.getProperty(DISPLAY_NAME);
properties.put(DISPLAY_NAME, originalDisplayName + " [enhanced]");
ServiceRegistration registration = ctx.registerService(
ModelInfoService.class.getName(), enhancer, properties);
registrations.put(serviceId + "", registration);
} else {
System.out.println("Oh dear - unexpected service "
+ actualService.getClass());
}
}
/**
*
*/
public void stop() {
for (ServiceRegistration registration : registrations.values()) {
registration.unregister();
}
}
}
| 8,377 |
0 | Create_ds/aries/sandbox/samples/goat/goat-info-enhancer/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-info-enhancer/src/main/java/org/apache/aries/samples/goat/enhancer/ModelInfoEnhancerService.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.enhancer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.ModelInfoService;
import org.apache.aries.samples.goat.api.RelationshipInfo;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
import org.apache.aries.samples.goat.info.ComponentInfoImpl;
import org.apache.aries.samples.goat.info.RelationshipInfoImpl;
public class ModelInfoEnhancerService implements ModelInfoService,
ComponentInfoProvider, RelationshipInfoProvider,
ComponentInfoProvider.ComponentInfoListener,
RelationshipInfoProvider.RelationshipInfoListener {
private static final String SERVICE_REGISTRATION = "Service registration";
private static final String SERVICE_USAGE = "Service usage";
// TODO where should we expose these shared strings?
private static final String SERVICE = "Service";
private ModelInfoService originalService;
private final Map<String, ComponentInfo> components = new HashMap<String, ComponentInfo>();
private final Map<String, RelationshipInfo> relationships = new HashMap<String, RelationshipInfo>();
private final List<ComponentInfoListener> clisteners;
private final List<RelationshipInfoListener> rlisteners;
public ModelInfoEnhancerService(ModelInfoService infoService) {
clisteners = Collections
.synchronizedList(new ArrayList<ComponentInfoListener>());
rlisteners = Collections
.synchronizedList(new ArrayList<RelationshipInfoListener>());
this.originalService = infoService;
Collection<ComponentInfo> originalComponents = originalService
.getComponentInfoProvider().getComponents();
// We keep all the original components
for (ComponentInfo info : originalComponents) {
components.put(info.getId(), info);
}
// We add a new component for each service
Collection<RelationshipInfo> originalRelationships = originalService
.getRelationshipInfoProvider().getRelationships();
// We keep all the original components
for (RelationshipInfo rel : originalRelationships) {
if (SERVICE.equals(rel.getType())) {
ComponentInfoImpl serviceComponent = new ComponentInfoImpl();
String id = constructServiceComponentId(rel);
serviceComponent.setId(id);
Map<String, String> componentProperties = new HashMap<String, String>();
componentProperties.put("Name", rel.getName());
serviceComponent.setComponentProperties(componentProperties);
components.put(id, serviceComponent);
// Make new relationships;
RelationshipInfoImpl registration = new RelationshipInfoImpl();
registration.setType(SERVICE_REGISTRATION);
registration.setName(rel.getName());
registration.setProvidedBy(rel.getProvidedBy());
registration.setRelationshipAspects(rel
.getRelationshipAspects());
ArrayList<ComponentInfo> arrayList = new ArrayList<ComponentInfo>();
arrayList.add(serviceComponent);
registration.setConsumedBy(arrayList);
relationships.put(constructId(registration), registration);
RelationshipInfoImpl consumption = new RelationshipInfoImpl();
consumption.setType(SERVICE_USAGE);
consumption.setName(rel.getName());
consumption.setProvidedBy(serviceComponent);
consumption.setConsumedBy(rel.getConsumedBy());
consumption
.setRelationshipAspects(rel.getRelationshipAspects());
relationships.put(constructId(consumption), consumption);
} else {
// Pass non-service relationships through
relationships.put(constructId(rel), rel);
}
originalService.getComponentInfoProvider()
.registerComponentInfoListener(this);
originalService.getRelationshipInfoProvider()
.registerRelationshipInfoListener(this);
}
}
@Override
public String getName() {
return "Model Enhancer Service";
}
@Override
public ComponentInfoProvider getComponentInfoProvider() {
return this;
}
@Override
public RelationshipInfoProvider getRelationshipInfoProvider() {
return this;
}
@Override
public Collection<RelationshipInfo> getRelationships() {
return relationships.values();
}
@Override
public Collection<ComponentInfo> getComponents() {
return components.values();
}
@Override
public ComponentInfo getComponentForId(String id) {
return components.get(id);
}
@Override
public void registerRelationshipInfoListener(
RelationshipInfoListener listener) {
rlisteners.add(listener);
}
@Override
public void registerComponentInfoListener(ComponentInfoListener listener) {
clisteners.add(listener);
}
@Override
public void updateRelationship(RelationshipInfo r) {
if (SERVICE.equals(r.getType())) {
updateSyntheticServiceArtefactsAndNotifyListeners(r);
} else {
// Update our copy
relationships.put(constructId(r), r);
// This shouldn't affect us, but pass it on to our listeners
for (RelationshipInfoListener listener : rlisteners) {
listener.updateRelationship(r);
}
}
}
@Override
public void removeRelationship(RelationshipInfo r) {
if (SERVICE.equals(r.getType())) {
removeSyntheticServiceArtefactsAndNotifyListeners(r);
} else {
// We don't want to track this relationship anymore
String id = constructId(r);
RelationshipInfo relationship = relationships.get(id);
relationships.remove(id);
if (relationship != null) {
// This shouldn't affect us, but pass it on to our listeners
for (RelationshipInfoListener listener : rlisteners) {
listener.removeRelationship(relationship);
}
}
}
}
@Override
public void updateComponent(ComponentInfo b) {
// Update our copy
components.put(b.getId(), b);
// This shouldn't affect us, but pass it on to our listeners
for (ComponentInfoListener listener : clisteners) {
listener.updateComponent(b);
}
}
@Override
public void removeComponent(ComponentInfo b) {
// This shouldn't affect us unless it has relationships pointing to it
// Cheerfully assume that gets handled upstream
// We don't want to know about this component anymore
ComponentInfo component = components.remove(b);
if (component != null) {// This shouldn't affect us, but pass it on to
// our listeners
for (ComponentInfoListener listener : clisteners) {
listener.removeComponent(component);
}
}
}
private String constructServiceComponentId(RelationshipInfo rel) {
return "/syntheticenhancedservices/" + rel.getName() + "/"
+ rel.getProvidedBy().getId();
}
private String constructId(RelationshipInfo b) {
return b.getType() + "/" + b.getName() + "/"
+ b.getProvidedBy().getId();
}
private void removeSyntheticServiceArtefactsAndNotifyListeners(
RelationshipInfo r) {
// We need to remove our two relationships and the synthetic
// component
String componentId = constructServiceComponentId(r);
// Do the relationships first
// The registration has type "service registration", and the
// original provider and name
String registrationRelationshipId = SERVICE_REGISTRATION + "/"
+ r.getName() + "/" + r.getProvidedBy().getId();
RelationshipInfo registrationRelationship = relationships
.get(registrationRelationshipId);
// The consumers have type "service usage", and the
// original name, and the new provided by
String usageRelationshipId = SERVICE_USAGE + "/" + r.getName() + "/"
+ componentId;
RelationshipInfo usageRelationship = relationships
.get(usageRelationshipId);
relationships.remove(usageRelationshipId);
relationships.remove(registrationRelationshipId);
// Tell our listeners about the relationships first
for (RelationshipInfoListener listener : rlisteners) {
if (usageRelationship != null) {
listener.removeRelationship(usageRelationship);
}
if (registrationRelationship != null) {
listener.removeRelationship(registrationRelationship);
}
}
ComponentInfo component = components.remove(componentId);
if (component != null) {
// Tell our listeners their service component went away
for (ComponentInfoListener listener : clisteners) {
listener.removeComponent(component);
}
}
}
private void updateSyntheticServiceArtefactsAndNotifyListeners(
RelationshipInfo r) {
// We need to update our two relationships and the synthetic
// component
// Hopefully the thing which changed won't prevent us
// from finding our relationship
String componentId = constructServiceComponentId(r);
// Do the relationships first
// The registration has type "service registration", and the
// original provider and name
String registrationRelationshipId = SERVICE_REGISTRATION + "/"
+ r.getName() + "/" + r.getProvidedBy().getId();
RelationshipInfoImpl registrationRelationship = (RelationshipInfoImpl) relationships
.get(registrationRelationshipId);
registrationRelationship.setName(r.getName());
registrationRelationship.setRelationshipAspects(r
.getRelationshipAspects());
// The consumers have type "service usage", and the
// original name, and the new provided by
String usageRelationshipId = SERVICE_USAGE + "/" + r.getName() + "/"
+ componentId;
RelationshipInfoImpl usageRelationship = (RelationshipInfoImpl) relationships
.get(usageRelationshipId);
// The consumers may have changed, so we update the usage relationship
usageRelationship.setConsumedBy(r.getConsumedBy());
usageRelationship.setName(r.getName());
usageRelationship.setRelationshipAspects(r.getRelationshipAspects());
// Tell our listeners about the relationships first
for (RelationshipInfoListener listener : rlisteners) {
if (usageRelationship != null) {
listener.updateRelationship(usageRelationship);
}
if (registrationRelationship != null) {
listener.updateRelationship(registrationRelationship);
}
}
ComponentInfo component = components.get(componentId);
if (component != null) {
// Tell our listeners their service component was updated
for (ComponentInfoListener listener : clisteners) {
listener.updateComponent(component);
}
}
}
}
| 8,378 |
0 | Create_ds/aries/sandbox/samples/goat/goat-info-enhancer/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-info-enhancer/src/main/java/org/apache/aries/samples/goat/enhancer/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.samples.goat.enhancer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private ServiceInterceptor interceptor;
@Override
public void start(BundleContext ctx) throws Exception {
interceptor = new ServiceInterceptor(ctx);
}
/*
* (non-Javadoc)
*
* @see
* org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext arg0) throws Exception {
interceptor.stop();
}
}
| 8,379 |
0 | Create_ds/aries/sandbox/samples/goat/goat-dummy-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-dummy-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyModelService.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.ModelInfoService;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
public class DummyModelService implements ModelInfoService {
private final static ComponentInfoProvider cip = new DummyInfoProvider();
private final static RelationshipInfoProvider rip = new DummyRelationshipProvider(cip);
@Override
public String getName() {
return "Dummy Model Service";
}
@Override
public ComponentInfoProvider getComponentInfoProvider() {
return cip;
}
@Override
public RelationshipInfoProvider getRelationshipInfoProvider() {
return rip;
}
}
| 8,380 |
0 | Create_ds/aries/sandbox/samples/goat/goat-dummy-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-dummy-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyInfoProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.aries.samples.goat.info.ComponentInfoImpl;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
public class DummyInfoProvider implements ComponentInfoProvider {
ComponentInfoImpl a = new ComponentInfoImpl();
ComponentInfoImpl b = new ComponentInfoImpl();
ComponentInfoImpl c = new ComponentInfoImpl();
public DummyInfoProvider(){
a.setId("/root/"+1);
Map<String,String> props = new HashMap<String,String>();
props.put("SymbolicName", "Uber.Bundle");
props.put("Version", "1.0.0");
props.put("State", "ACTIVE");
props.put("BundleID", "1");
a.setComponentProperties(props);
b.setId("/root/"+2);
props = new HashMap<String,String>();
props.put("SymbolicName", "Fred");
props.put("Version", "1.0.0");
props.put("State", "RESOLVED");
props.put("BundleID", "2");
b.setComponentProperties(props);
c.setId("/root/"+3);
props = new HashMap<String,String>();
props.put("SymbolicName", "Wilma");
props.put("Version", "1.0.0");
props.put("State", "ACTIVE");
props.put("BundleID", "3");
c.setComponentProperties(props);
}
@Override
public List<ComponentInfo> getComponents() {
List<ComponentInfo> result = new ArrayList<ComponentInfo>();
result.add(a);
result.add(b);
result.add(c);
return result;
}
@Override
public ComponentInfo getComponentForId(String id) {
if("/root/1".equals(id)) return a;
if("/root/2".equals(id)) return b;
if("/root/3".equals(id)) return c;
return null;
}
@Override
public void registerComponentInfoListener(ComponentInfoListener listener) {
//no-op
}
}
| 8,381 |
0 | Create_ds/aries/sandbox/samples/goat/goat-dummy-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-dummy-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyRelationshipProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.samples.goat.info.RelationshipInfoImpl;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.RelationshipInfo;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
public class DummyRelationshipProvider implements RelationshipInfoProvider {
ComponentInfoProvider cip = null;
public DummyRelationshipProvider(ComponentInfoProvider cip){
this.cip = cip;
}
@Override
public List<RelationshipInfo> getRelationships() {
ArrayList<RelationshipInfo> ris = new ArrayList<RelationshipInfo>();
ComponentInfo ci1 = cip.getComponentForId("/root/1");
ComponentInfo ci2 = cip.getComponentForId("/root/2");
ComponentInfo ci3 = cip.getComponentForId("/root/3");
RelationshipInfoImpl ri1 = new RelationshipInfoImpl();
RelationshipInfoImpl ri2 = new RelationshipInfoImpl();
RelationshipInfoImpl ri3 = new RelationshipInfoImpl();
RelationshipInfoImpl ri4 = new RelationshipInfoImpl();
RelationshipInfoImpl ri5 = new RelationshipInfoImpl();
RelationshipInfoImpl ri6 = new RelationshipInfoImpl();
ris.add(ri1);
ris.add(ri2);
ris.add(ri3);
ris.add(ri4);
ris.add(ri5);
ris.add(ri6);
ri1.setName("i.am.exported.by.1.and.used.by.2.and.3");
ri1.setProvidedBy(ci1);
ArrayList<ComponentInfo> c = new ArrayList<ComponentInfo>();
c.add(ci2);
c.add(ci3);
ri1.setConsumedBy(c);
ri1.setType("Package");
ri2.setName("i.am.exported.by.1.and.used.by.3");
ri2.setProvidedBy(ci1);
c = new ArrayList<ComponentInfo>();
c.add(ci3);
ri2.setConsumedBy(c);
ri2.setType("Package");
ri3.setName("i.am.exported.by.2.and.used.by.3");
ri3.setProvidedBy(ci2);
c = new ArrayList<ComponentInfo>();
c.add(ci3);
ri3.setConsumedBy(c);
ri3.setType("Package");
ri4.setName("i.am.exported.by.3.and.used.by.2");
ri4.setProvidedBy(ci3);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri4.setConsumedBy(c);
ri4.setType("Package");
ri5.setName("i.am.a.funky.service.from.3.used.by.2");
ri5.setProvidedBy(ci3);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri5.setConsumedBy(c);
ri5.setType("Service");
ri6.setName("i.am.a.funky.service.from.1.used.by.2");
ri6.setProvidedBy(ci1);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri6.setConsumedBy(c);
ri6.setType("Service");
return ris;
}
@Override
public void registerRelationshipInfoListener(RelationshipInfoListener listener) {
// TODO Auto-generated method stub
}
}
| 8,382 |
0 | Create_ds/aries/sandbox/samples/goat/goat-dummy2-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-dummy2-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyInfoProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.aries.samples.goat.info.ComponentInfoImpl;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
public class DummyInfoProvider implements ComponentInfoProvider {
ComponentInfoImpl a = new ComponentInfoImpl();
ComponentInfoImpl b = new ComponentInfoImpl();
ComponentInfoImpl c = new ComponentInfoImpl();
public DummyInfoProvider(){
a.setId("/root/"+1);
Map<String,String> props = new HashMap<String,String>();
props.put("SymbolicName", "Mickey.Bundle");
props.put("Version", "1.0.0");
props.put("State", "RESOLVED");
props.put("BundleID", "1");
a.setComponentProperties(props);
b.setId("/root/"+2);
props = new HashMap<String,String>();
props.put("SymbolicName", "Mouse");
props.put("Version", "1.0.0");
props.put("State", "ACTIVE");
props.put("BundleID", "2");
b.setComponentProperties(props);
c.setId("/root/"+3);
props = new HashMap<String,String>();
props.put("SymbolicName", "Barney");
props.put("Version", "1.0.0");
props.put("State", "ACTIVE");
props.put("BundleID", "3");
c.setComponentProperties(props);
}
@Override
public List<ComponentInfo> getComponents() {
List<ComponentInfo> result = new ArrayList<ComponentInfo>();
result.add(a);
result.add(b);
result.add(c);
return result;
}
@Override
public ComponentInfo getComponentForId(String id) {
if("/root/1".equals(id)) return a;
if("/root/2".equals(id)) return b;
if("/root/3".equals(id)) return c;
return null;
}
@Override
public void registerComponentInfoListener(ComponentInfoListener listener) {
//no-op
}
}
| 8,383 |
0 | Create_ds/aries/sandbox/samples/goat/goat-dummy2-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-dummy2-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyRelationshipProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy2;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.samples.goat.info.RelationshipInfoImpl;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.RelationshipInfo;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
public class DummyRelationshipProvider implements RelationshipInfoProvider {
ComponentInfoProvider cip = null;
public DummyRelationshipProvider(ComponentInfoProvider cip){
this.cip = cip;
}
@Override
public List<RelationshipInfo> getRelationships() {
ArrayList<RelationshipInfo> ris = new ArrayList<RelationshipInfo>();
ComponentInfo ci1 = cip.getComponentForId("/root/1");
ComponentInfo ci2 = cip.getComponentForId("/root/2");
ComponentInfo ci3 = cip.getComponentForId("/root/3");
RelationshipInfoImpl ri1 = new RelationshipInfoImpl();
RelationshipInfoImpl ri2 = new RelationshipInfoImpl();
RelationshipInfoImpl ri3 = new RelationshipInfoImpl();
RelationshipInfoImpl ri4 = new RelationshipInfoImpl();
RelationshipInfoImpl ri5 = new RelationshipInfoImpl();
RelationshipInfoImpl ri6 = new RelationshipInfoImpl();
ris.add(ri1);
ris.add(ri2);
ris.add(ri3);
ris.add(ri4);
ris.add(ri5);
ris.add(ri6);
ri1.setName("i.am.exported.by.1.and.used.by.2.and.3");
ri1.setProvidedBy(ci1);
ArrayList<ComponentInfo> c = new ArrayList<ComponentInfo>();
c.add(ci2);
c.add(ci3);
ri1.setConsumedBy(c);
ri1.setType("Package");
ri2.setName("i.am.exported.by.1.and.used.by.3");
ri2.setProvidedBy(ci1);
c = new ArrayList<ComponentInfo>();
c.add(ci3);
ri2.setConsumedBy(c);
ri2.setType("Package");
ri3.setName("i.am.exported.by.2.and.used.by.3");
ri3.setProvidedBy(ci2);
c = new ArrayList<ComponentInfo>();
c.add(ci3);
ri3.setConsumedBy(c);
ri3.setType("Package");
ri4.setName("i.am.exported.by.3.and.used.by.2");
ri4.setProvidedBy(ci3);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri4.setConsumedBy(c);
ri4.setType("Package");
ri5.setName("i.am.a.funky.service.from.3.used.by.2");
ri5.setProvidedBy(ci3);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri5.setConsumedBy(c);
ri5.setType("Service");
ri6.setName("i.am.a.funky.service.from.1.used.by.2");
ri6.setProvidedBy(ci1);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri6.setConsumedBy(c);
ri6.setType("Service");
return ris;
}
@Override
public void registerRelationshipInfoListener(RelationshipInfoListener listener) {
// TODO Auto-generated method stub
}
}
| 8,384 |
0 | Create_ds/aries/sandbox/samples/goat/goat-dummy2-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-dummy2-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyModelService2.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy2;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.ModelInfoService;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
public class DummyModelService2 implements ModelInfoService {
private final static ComponentInfoProvider cip = new DummyInfoProvider();
private final static RelationshipInfoProvider rip = new DummyRelationshipProvider(cip);
@Override
public String getName() {
return "Dummy Model Service";
}
@Override
public ComponentInfoProvider getComponentInfoProvider() {
return cip;
}
@Override
public RelationshipInfoProvider getRelationshipInfoProvider() {
return rip;
}
}
| 8,385 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/info/RelationshipInfoImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.info;
import java.util.List;
import org.apache.aries.samples.goat.api.RelationshipInfo;
import org.apache.aries.samples.goat.api.RelationshipAspect;
import org.apache.aries.samples.goat.api.ComponentInfo;;
public class RelationshipInfoImpl implements RelationshipInfo {
List<ComponentInfo> consumedBy;
List<RelationshipAspect> relationshipAspects;
String name;
ComponentInfo providedBy;
String type;
public List<ComponentInfo> getConsumedBy() {
return consumedBy;
}
public void setConsumedBy(List<ComponentInfo> consumedBy) {
this.consumedBy = consumedBy;
}
public List<RelationshipAspect> getRelationshipAspects() {
return relationshipAspects;
}
public void setRelationshipAspects(List<RelationshipAspect> relationshipAspects) {
this.relationshipAspects = relationshipAspects;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ComponentInfo getProvidedBy() {
return providedBy;
}
public void setProvidedBy(ComponentInfo providedBy) {
this.providedBy = providedBy;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 8,386 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/info/ComponentInfoImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.info;
import java.util.List;
import java.util.Map;
import org.apache.aries.samples.goat.api.ComponentInfo;
public class ComponentInfoImpl implements ComponentInfo {
List<ComponentInfo> children;
Map<String,String> componentProperties;
String id;
public List<ComponentInfo> getChildren() {
return children;
}
public void setChildren(List<ComponentInfo> children) {
this.children = children;
}
public Map<String, String> getComponentProperties() {
return componentProperties;
}
public void setComponentProperties(Map<String, String> componentProperties) {
this.componentProperties = componentProperties;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| 8,387 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/api/ComponentInfoProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.api;
import java.util.Collection;
/**
* Provides information about components within a model.
*
* Good usage practice would be to subscribe a listener .. and THEN call
* getComponents.. (doing it the other way round risks leaving a window during
* which a change could occur, and you not be informed). (doing it this way
* round, at worst, you'll see an update before you handle getComponents, and
* since an update can be an add, you'll just process it twice)
*
*/
public interface ComponentInfoProvider {
/**
* Callback interface implemented by users of the ComponentInfoProvider
* interface, allowing notification of changes, or deletions to components
* they have been informed about.
*/
static interface ComponentInfoListener {
// called to add, or update a component.
public void updateComponent(ComponentInfo b);
public void removeComponent(ComponentInfo b);
};
/**
* Gets the current set of 'top level' components in this model.
*
* Any nested components are only obtainable via the 'getChildren' method on
* ComponentInfo.
*
* @return
*/
Collection<ComponentInfo> getComponents();
/**
* Gets a component for an id previously returned via getComponents, or
* updateComponent
*
* @param id
* @return component, or null if component id is either unknown, or deleted.
*/
ComponentInfo getComponentForId(String id);
/**
* Add a listener to this Info Provider, to be informed of
* changes/deletions.
*
* @param listener
*/
public void registerComponentInfoListener(ComponentInfoListener listener);
// TODO: unregisterComponentInfoListener ;-)
}
| 8,388 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/api/ModelInfoService.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.api;
/**
* The top level service interface published to the service registry
*
* A model is something with components, with relationships between them.
*/
public interface ModelInfoService {
String getName();
ComponentInfoProvider getComponentInfoProvider();
RelationshipInfoProvider getRelationshipInfoProvider();
}
| 8,389 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/api/ComponentInfo.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.api;
import java.util.List;
import java.util.Map;
public interface ComponentInfo {
String getId();
/**
* always needed, id's must be unique globally, or within their containing component info.
* (impl notes.. (for bundles)
* Id's will probably NOT be bundle id's... we need the id to be fixed between framework restarts,
* to enable things like storing coords for onscreen renderings of components
* Id's will probably end up being path based, /component.id/component.id etc .. for sanities sake.
* Component properties are information that forms part of a component, keys will vary depending on
* what the component represents. The GUI will handle rendering based on key names.
*/
Map<String,String> getComponentProperties();
/**
* children are only supported in concept currently.. no gui work done yet for them..
* List of any contained components for this component.
*/
List<ComponentInfo> getChildren();
}
| 8,390 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/api/ParameterizedRelationshipAspect.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.api;
import java.util.List;
public interface ParameterizedRelationshipAspect extends RelationshipAspect{
static class Parameter{
String key;
String value;
};
List<Parameter> getProvidedParameters(); //any parameters specified by the supplier of the dependency.
List<Parameter> getConsumedParameters(); //any parameters specified by the consumer of the dependency.
}
| 8,391 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/api/RelationshipAspect.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.api;
public interface RelationshipAspect {
public String getType();
}
| 8,392 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/api/RelationshipInfoProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.api;
import java.util.Collection;
public interface RelationshipInfoProvider {
static interface RelationshipInfoListener {
public void updateRelationship(RelationshipInfo b);
public void removeRelationship(RelationshipInfo b);
};
Collection<RelationshipInfo> getRelationships();
public void registerRelationshipInfoListener(
RelationshipInfoListener listener);
}
| 8,393 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/api/RelationshipInfo.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.api;
import java.util.List;
//This represents a single dependency between two components
public interface RelationshipInfo {
//relationships are unique by type&name combined.
String getType(); //String describing the type of this dependency.
String getName(); //name of this dependency.
//the provider/consumer side of this relationship.
ComponentInfo getProvidedBy();
//consumers can of course, be empty. (thats empty.. NOT null)
List<ComponentInfo> getConsumedBy();
//relationship aspects are not fully integrated yet.. avoid until stable ;-)
List<RelationshipAspect> getRelationshipAspects();
}
| 8,394 |
0 | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/goat/goat-api/src/main/java/org/apache/aries/samples/goat/api/VersionedRelationshipAspect.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.api;
public interface VersionedRelationshipAspect extends RelationshipAspect {
String getProvidedVersion(); //this will be an exact version.
String getConsumedVersion(); //this will be either a range, or an exact version.
//provided version will either match, or be in the range.
}
| 8,395 |
0 | Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy2-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy2-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyInfoProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.aries.samples.goat.info.ComponentInfoImpl;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
public class DummyInfoProvider implements ComponentInfoProvider {
ComponentInfoImpl a = new ComponentInfoImpl();
ComponentInfoImpl b = new ComponentInfoImpl();
ComponentInfoImpl c = new ComponentInfoImpl();
public DummyInfoProvider(){
a.setId("/root/"+1);
Map<String,String> props = new HashMap<String,String>();
props.put("SymbolicName", "Mickey.Bundle");
props.put("Version", "1.0.0");
props.put("State", "RESOLVED");
props.put("BundleID", "1");
a.setComponentProperties(props);
b.setId("/root/"+2);
props = new HashMap<String,String>();
props.put("SymbolicName", "Mouse");
props.put("Version", "1.0.0");
props.put("State", "ACTIVE");
props.put("BundleID", "2");
b.setComponentProperties(props);
c.setId("/root/"+3);
props = new HashMap<String,String>();
props.put("SymbolicName", "Barney");
props.put("Version", "1.0.0");
props.put("State", "ACTIVE");
props.put("BundleID", "3");
c.setComponentProperties(props);
}
@Override
public List<ComponentInfo> getComponents() {
List<ComponentInfo> result = new ArrayList<ComponentInfo>();
result.add(a);
result.add(b);
result.add(c);
return result;
}
@Override
public ComponentInfo getComponentForId(String id) {
if("/root/1".equals(id)) return a;
if("/root/2".equals(id)) return b;
if("/root/3".equals(id)) return c;
return null;
}
@Override
public void registerComponentInfoListener(ComponentInfoListener listener) {
//no-op
}
}
| 8,396 |
0 | Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy2-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy2-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyRelationshipProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy2;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.samples.goat.info.RelationshipInfoImpl;
import org.apache.aries.samples.goat.api.ComponentInfo;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.RelationshipInfo;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
public class DummyRelationshipProvider implements RelationshipInfoProvider {
ComponentInfoProvider cip = null;
public DummyRelationshipProvider(ComponentInfoProvider cip){
this.cip = cip;
}
@Override
public List<RelationshipInfo> getRelationships() {
ArrayList<RelationshipInfo> ris = new ArrayList<RelationshipInfo>();
ComponentInfo ci1 = cip.getComponentForId("/root/1");
ComponentInfo ci2 = cip.getComponentForId("/root/2");
ComponentInfo ci3 = cip.getComponentForId("/root/3");
RelationshipInfoImpl ri1 = new RelationshipInfoImpl();
RelationshipInfoImpl ri2 = new RelationshipInfoImpl();
RelationshipInfoImpl ri3 = new RelationshipInfoImpl();
RelationshipInfoImpl ri4 = new RelationshipInfoImpl();
RelationshipInfoImpl ri5 = new RelationshipInfoImpl();
RelationshipInfoImpl ri6 = new RelationshipInfoImpl();
ris.add(ri1);
ris.add(ri2);
ris.add(ri3);
ris.add(ri4);
ris.add(ri5);
ris.add(ri6);
ri1.setName("i.am.exported.by.1.and.used.by.2.and.3");
ri1.setProvidedBy(ci1);
ArrayList<ComponentInfo> c = new ArrayList<ComponentInfo>();
c.add(ci2);
c.add(ci3);
ri1.setConsumedBy(c);
ri1.setType("Package");
ri2.setName("i.am.exported.by.1.and.used.by.3");
ri2.setProvidedBy(ci1);
c = new ArrayList<ComponentInfo>();
c.add(ci3);
ri2.setConsumedBy(c);
ri2.setType("Package");
ri3.setName("i.am.exported.by.2.and.used.by.3");
ri3.setProvidedBy(ci2);
c = new ArrayList<ComponentInfo>();
c.add(ci3);
ri3.setConsumedBy(c);
ri3.setType("Package");
ri4.setName("i.am.exported.by.3.and.used.by.2");
ri4.setProvidedBy(ci3);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri4.setConsumedBy(c);
ri4.setType("Package");
ri5.setName("i.am.a.funky.service.from.3.used.by.2");
ri5.setProvidedBy(ci3);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri5.setConsumedBy(c);
ri5.setType("Service");
ri6.setName("i.am.a.funky.service.from.1.used.by.2");
ri6.setProvidedBy(ci1);
c = new ArrayList<ComponentInfo>();
c.add(ci2);
ri6.setConsumedBy(c);
ri6.setType("Service");
return ris;
}
@Override
public void registerRelationshipInfoListener(RelationshipInfoListener listener) {
// TODO Auto-generated method stub
}
}
| 8,397 |
0 | Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy2-provider/src/main/java/org/apache/aries/samples/goat | Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy2-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyModelService2.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.samples.goat.dummy2;
import org.apache.aries.samples.goat.api.ComponentInfoProvider;
import org.apache.aries.samples.goat.api.ModelInfoService;
import org.apache.aries.samples.goat.api.RelationshipInfoProvider;
public class DummyModelService2 implements ModelInfoService {
private final static ComponentInfoProvider cip = new DummyInfoProvider();
private final static RelationshipInfoProvider rip = new DummyRelationshipProvider(cip);
@Override
public String getName() {
return "Dummy Model Service";
}
@Override
public ComponentInfoProvider getComponentInfoProvider() {
return cip;
}
@Override
public RelationshipInfoProvider getRelationshipInfoProvider() {
return rip;
}
}
| 8,398 |
0 | Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-cli/src/main/java/org/apache/cxf/dosgi/samples/greeter | Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-cli/src/main/java/org/apache/cxf/dosgi/samples/greeter/client/GreeterDialog.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.dosgi.samples.greeter.client;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class GreeterDialog extends JDialog {
private static final long serialVersionUID = 1L;
Object selection;
public GreeterDialog() {
super((Frame) null, "Invoke Remote Greeter Service", true);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
setContentPane(panel);
final JRadioButton rb1 = new JRadioButton("invoke: Map<GreetingPhrase, String> greetMe(String name);");
rb1.setSelected(true);
rb1.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(rb1);
final JPanel simplePanel = new JPanel(new GridBagLayout());
simplePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
GridBagConstraints c1 = new GridBagConstraints();
rb1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
enablePanel(simplePanel, rb1.isSelected());
}
});
JLabel lb1 = new JLabel("Name: ");
c1.weightx = 0.0;
c1.gridx = 0;
c1.gridy = 0;
c1.insets = new Insets(0, 25, 0, 0);
c1.anchor = GridBagConstraints.LINE_START;
simplePanel.add(lb1, c1);
final JTextField tf1 = new JTextField(20);
c1.weightx = 0.2;
c1.gridx = 1;
c1.gridy = 0;
c1.insets = new Insets(0, 10, 0, 0);
c1.anchor = GridBagConstraints.LINE_START;
simplePanel.add(tf1, c1);
panel.add(simplePanel);
panel.add(new JLabel(" ")); // add a spacer
final JRadioButton rb2 = new JRadioButton("invoke: GreetingPhrase [] greetMe(GreeterData data) throws GreeterException;");
rb2.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(rb2);
final JPanel complexPanel = new JPanel(new GridBagLayout());
complexPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
GridBagConstraints c2 = new GridBagConstraints();
rb2.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
enablePanel(complexPanel, rb2.isSelected());
}
});
JLabel lb2 = new JLabel("Name: ");
c2.weightx = 0.0;
c2.gridx = 0;
c2.gridy = 0;
c2.insets = new Insets(0, 25, 0, 0);
c2.anchor = GridBagConstraints.LINE_START;
complexPanel.add(lb2, c2);
final JTextField tf2 = new JTextField(20);
c2.weightx = 0.2;
c2.gridx = 1;
c2.gridy = 0;
c2.insets = new Insets(0, 10, 0, 0);
c2.anchor = GridBagConstraints.LINE_START;
complexPanel.add(tf2, c2);
JLabel lb3 = new JLabel("Age: ");
c2.weightx = 0.0;
c2.gridx = 0;
c2.gridy = 1;
c2.insets = new Insets(0, 25, 0, 0);
c2.anchor = GridBagConstraints.LINE_START;
complexPanel.add(lb3, c2);
final JTextField tf3 = new JTextField(7);
c2.weightx = 0.2;
c2.gridx = 1;
c2.gridy = 1;
c2.insets = new Insets(0, 10, 0, 0);
c2.anchor = GridBagConstraints.LINE_START;
complexPanel.add(tf3, c2);
final JCheckBox cb1 = new JCheckBox("Throw Exception");
c2.weightx = 0.0;
c2.gridx = 0;
c2.gridy = 2;
c2.gridwidth = 2;
c2.insets = new Insets(0, 22, 0, 0);
c2.anchor = GridBagConstraints.LINE_START;
complexPanel.add(cb1, c2);
panel.add(complexPanel);
enablePanel(complexPanel, false);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttons.setAlignmentX(Component.LEFT_ALIGNMENT);
JButton b1 = new JButton("Invoke");
buttons.add(b1);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rb1.isSelected()) {
selection = tf1.getText();
} else {
selection = new GreeterDataImpl(tf2.getText(), new Integer(tf3.getText()), cb1.isSelected());
}
setVisible(false);
}
});
panel.add(buttons);
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
pack();
setLocationRelativeTo(null); // centers frame on screen
}
public Object getSelection() {
return selection;
}
private static void enablePanel(JPanel panel, boolean b) {
for (Component c : panel.getComponents()) {
c.setEnabled(b);
}
}
public static void main(String ... args) {
GreeterDialog gd = new GreeterDialog();
gd.setVisible(true);
System.exit(0);
}
}
| 8,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.