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/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassChildOfAbstract.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import java.util.concurrent.Callable;
public class ProxyTestClassChildOfAbstract extends ProxyTestClassAbstract implements Callable<String>{
@Override
public String getMessage() {
return "Working";
}
public String call() throws Exception {
return "Callable Works too!";
}
}
| 7,800 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassStaticInitOfChildParent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassStaticInitOfChildParent
{
private static final ProxyTestClassStaticInitOfChildParent child = new ProxyTestClassStaticInitOfChild();
public static void doStuff() {
//Do silly stuff;
child.toString();
}
public ProxyTestClassStaticInitOfChildParent(String s){
}
}
| 7,801 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestInterface.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import java.util.concurrent.Callable;
public interface ProxyTestInterface extends Callable<Object> {
public static final String FIELD = "A Field";
public int doSuff();
}
| 7,802 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassGenericSuper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassGenericSuper<T>
{
T something = null;
public void setSomething(T something)
{
this.something = something;
}
public T getSomething()
{
return something;
}
}
| 7,803 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassSuperWithNoDefaultOrProtectedAccess.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassSuperWithNoDefaultOrProtectedAccess
{
static {
System.out.println("The time is: " + System.currentTimeMillis());
}
public void bMethod()
{
aPrivateMethod();
}
public void bProMethod()
{
}
public void bDefMethod()
{
}
private void aPrivateMethod()
{
}
public Object getTargetObject() {
return null;
}
@SuppressWarnings("unused")
private void doTarget() {
Object o = getTargetObject();
if(this != o)
((ProxyTestClassSuperWithNoDefaultOrProtectedAccess)o).doTarget();
}
}
| 7,804 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassFinal.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public final class ProxyTestClassFinal
{
void someMethod()
{
}
}
| 7,805 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassCovariant.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassCovariant
{
//this method is here to make sure we don't break on covariant override
public ProxyTestClassCovariant getCovariant()
{
return this;
}
}
| 7,806 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassSerializableInterface.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
@SuppressWarnings("serial")
public class ProxyTestClassSerializableInterface implements
ProxyTestSerializableInterface {
public int value;
/**
* We deserialize using this static method to ensure that the right classloader
* is used when deserializing our object, it will always be the classloader that
* loaded this class, which might be the JUnit one, or our weaving one.
*
* @param bytes
* @param value
* @throws Exception
*/
public static void checkDeserialization(byte[] bytes, int value) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
ProxyTestClassSerializableInterface out = (ProxyTestClassSerializableInterface) ois.readObject();
assertEquals(value, out.value);
}
}
| 7,807 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/AbstractProxyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import 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 static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import org.apache.aries.blueprint.proxy.ProxyTestClassInnerClasses.ProxyTestClassInner;
import org.apache.aries.blueprint.proxy.ProxyTestClassInnerClasses.ProxyTestClassStaticInner;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.impl.SingleInstanceDispatcher;
import org.junit.Test;
import org.osgi.framework.wiring.BundleWiring;
public abstract class AbstractProxyTest {
protected static class TestListener implements InvocationListener {
boolean preInvoke = false;
boolean postInvoke = false;
boolean postInvokeExceptionalReturn = false;
private Method m;
private Object token;
private Throwable e;
public Object preInvoke(Object proxy, Method m, Object[] args)
throws Throwable {
preInvoke = true;
token = new Object();
this.m = m;
return token;
}
public void postInvoke(Object token, Object proxy, Method m,
Object returnValue) throws Throwable {
postInvoke = this.token == token && this.m == m;
}
public void postInvokeExceptionalReturn(Object token, Object proxy,
Method m, Throwable exception) throws Throwable {
postInvokeExceptionalReturn = this.token == token && this.m == m;
e = exception;
}
public void clear() {
preInvoke = false;
postInvoke = false;
postInvokeExceptionalReturn = false;
token = null;
m = null;
e = null;
}
public Method getLastMethod() {
return m;
}
public Throwable getLastThrowable() {
return e;
}
}
protected abstract Object getProxyInstance(Class<?> proxyClass);
protected abstract Object getProxyInstance(Class<?> proxyClass, InvocationListener listener);
protected abstract Class<?> getProxyClass(Class<?> clazz);
protected abstract Object setDelegate(Object proxy, Callable<Object> dispatcher);
protected Class<?> getTestClass() {
return ProxyTestClassGeneral.class;
}
protected Method getDeclaredMethod(Class<?> testClass, String name,
Class<?>... classes) throws Exception {
return getProxyClass(testClass).getDeclaredMethod(name, classes);
}
/**
* This test uses the ProxySubclassGenerator to generate and load a subclass
* of the specified getTestClass().
*
* Once the subclass is generated we check that it wasn't null. We check
* that the InvocationHandler constructor doesn't return a null object
* either
*
* Test method for
* {@link org.apache.aries.proxy.impl.ProxySubclassGenerator#generateAndLoadSubclass()}
* .
*/
@Test
public void testGenerateAndLoadProxy() throws Exception
{
assertNotNull("Generated proxy subclass was null", getProxyClass(getTestClass()));
assertNotNull("Generated proxy subclass instance was null", getProxyInstance(getProxyClass(getTestClass())));
}
/**
* Test a basic method invocation on the proxy subclass
*/
@Test
public void testMethodInvocation() throws Exception {
Method m = getDeclaredMethod(getTestClass(), "testMethod", String.class,
int.class, Object.class);
String x = "x";
String returned = (String) m.invoke(getProxyInstance(getProxyClass(getTestClass())), x, 1, new Object());
assertEquals("Object returned from invocation was not correct.", x, returned);
}
/**
* Test different argument types on a method invocation
*/
@Test
public void testMethodArgs() throws Exception
{
Method m = getDeclaredMethod(getTestClass(), "testArgs", double.class,
short.class, long.class, char.class, byte.class, boolean.class);
Character xc = Character.valueOf('x');
String x = xc.toString();
String returned = (String) m.invoke(getProxyInstance(getProxyClass(getTestClass())), Double.MAX_VALUE, Short.MIN_VALUE, Long.MAX_VALUE, xc
.charValue(), Byte.MIN_VALUE, false);
assertEquals("Object returned from invocation was not correct.", x, returned);
}
/**
* Test a method that returns void
*/
@Test
public void testReturnVoid() throws Exception
{
Method m = getDeclaredMethod(getTestClass(), "testReturnVoid");
//for these weaving tests we are loading the woven test classes on a different classloader
//to this class so we need to set the method accessible
m.setAccessible(true);
m.invoke(getProxyInstance(getProxyClass(getTestClass())));
}
/**
* Test a method that returns an int
*/
@Test
public void testReturnInt() throws Exception
{
Method m = getDeclaredMethod(getTestClass(), "testReturnInt");
//for these weaving tests we are loading the woven test classes on a different classloader
//to this class so we need to set the method accessible
m.setAccessible(true);
Integer returned = (Integer) m.invoke(getProxyInstance(getProxyClass(getTestClass())));
assertEquals("Expected object was not returned from invocation", Integer.valueOf(17), returned);
}
/**
* Test a method that returns an Integer
*/
@Test
public void testReturnInteger() throws Exception
{
Method m = getDeclaredMethod(getTestClass(), "testReturnInteger");
Integer returned = (Integer) m.invoke(getProxyInstance(getProxyClass(getTestClass())));
assertEquals("Expected object was not returned from invocation", Integer.valueOf(1), returned);
}
/**
* Test a public method declared higher up the superclass hierarchy
*/
@Test
public void testPublicHierarchyMethod() throws Exception
{
Method m = null;
try {
m = getDeclaredMethod(getTestClass(), "bMethod");
} catch (NoSuchMethodException nsme) {
m = getProxyClass(getTestClass()).getSuperclass().getDeclaredMethod("bMethod");
}
m.invoke(getProxyInstance(getProxyClass(getTestClass())));
}
/**
* Test a protected method declared higher up the superclass hierarchy
*/
@Test
public void testProtectedHierarchyMethod() throws Exception
{
Method m = null;
try {
m = getDeclaredMethod(getTestClass(), "bProMethod");
} catch (NoSuchMethodException nsme) {
m = getProxyClass(getTestClass()).getSuperclass().getDeclaredMethod("bProMethod");
}
//for these weaving tests we are loading the woven test classes on a different classloader
//to this class so we need to set the method accessible
m.setAccessible(true);
m.invoke(getProxyInstance(getProxyClass(getTestClass())));
}
/**
* Test a default method declared higher up the superclass hierarchy
*/
@Test
public void testDefaultHierarchyMethod() throws Exception
{
Method m = null;
try {
m = getDeclaredMethod(getTestClass(), "bDefMethod");
} catch (NoSuchMethodException nsme) {
m = getProxyClass(getTestClass()).getSuperclass().getDeclaredMethod("bDefMethod", new Class[] {});
}
//for these weaving tests we are loading the woven test classes on a different classloader
//to this class so we need to set the method accessible
m.setAccessible(true);
m.invoke(getProxyInstance(getProxyClass(getTestClass())));
}
/**
* Test a covariant override method
*/
@Test
public void testCovariant() throws Exception
{
Class<?> proxy = getProxyClass(ProxyTestClassCovariantOverride.class);
Method m = getDeclaredMethod(ProxyTestClassCovariantOverride.class, "getCovariant");
Object returned = m.invoke(getProxyInstance(proxy));
assertTrue("Object was of wrong type: " + returned.getClass().getSimpleName(),
proxy.isInstance(returned));
}
/**
* Test a method with generics
*/
@Test
public void testGenerics() throws Exception
{
Class<?> proxy = getProxyClass(ProxyTestClassGeneric.class);
Object o = getProxyInstance(proxy);
Method m = getDeclaredMethod(ProxyTestClassGeneric.class, "setSomething", String.class);
m.invoke(o, "aString");
if(getClass() == WovenProxyGeneratorTest.class)
m = getDeclaredMethod(ProxyTestClassGeneric.class.getSuperclass(), "getSomething");
else
m = getDeclaredMethod(ProxyTestClassGeneric.class, "getSomething");
Object returned = m.invoke(o);
assertTrue("Object was of wrong type", String.class.isInstance(returned));
assertEquals("String had wrong value", "aString", returned);
}
/**
* Test that we don't generate classes twice
*/
@Test
public void testRetrieveClass() throws Exception
{
Class<?> retrieved = getProxyClass(getTestClass());
assertNotNull("The new class was null", retrieved);
assertEquals("The same class was not returned", retrieved, getProxyClass(getTestClass()));
}
@Test
public void testEquals() throws Exception {
Object p1 = getProxyInstance(getProxyClass(getTestClass()));
Object p2 = getProxyInstance(getProxyClass(getTestClass()));
assertFalse("Should not be equal", p1.equals(p2));
Object p3 = getP3();
p1 = setDelegate(p1, new SingleInstanceDispatcher(p3));
p2 = setDelegate(p2, new SingleInstanceDispatcher(p3));
assertTrue("Should be equal", p1.equals(p2));
Object p4 = getProxyInstance(getProxyClass(getTestClass()));
Object p5 = getProxyInstance(getProxyClass(getTestClass()));
p4 = setDelegate(p4, new SingleInstanceDispatcher(p1));
p5 = setDelegate(p5, new SingleInstanceDispatcher(p2));
assertTrue("Should be equal", p4.equals(p5));
}
protected abstract Object getP3() throws Exception;
@Test
public void testInterception() throws Throwable {
TestListener tl = new TestListener();
Object obj = getProxyInstance(getProxyClass(getTestClass()), tl);
assertCalled(tl, false, false, false);
Method m = getDeclaredMethod(getTestClass(), "testReturnInteger", new Class[] {});
m.invoke(obj);
assertCalled(tl, true, true, false);
tl.clear();
assertCalled(tl, false, false, false);
m = getDeclaredMethod(getTestClass(), "testException", new Class[] {});
try {
m.invoke(obj);
fail("Should throw an exception");
} catch (InvocationTargetException re) {
if(!!!re.getTargetException().getClass().equals(RuntimeException.class))
throw re.getTargetException();
assertCalled(tl, true, false, true);
}
tl.clear();
assertCalled(tl, false, false, false);
m = getDeclaredMethod(getTestClass(), "testInternallyCaughtException", new Class[] {});
try {
m.invoke(obj);
} finally {
assertCalled(tl, true, true, false);
}
}
protected void assertCalled(TestListener listener, boolean pre, boolean post, boolean ex) {
assertEquals(pre, listener.preInvoke);
assertEquals(post, listener.postInvoke);
assertEquals(ex, listener.postInvokeExceptionalReturn);
}
@Test
public void testStaticInner() throws Exception {
assertNotNull(getProxyInstance(getProxyClass(ProxyTestClassStaticInner.class)));
}
@Test
public void testInner() throws Exception {
//An inner class has no no-args (the parent gets added as an arg) so we can't
//get an instance
assertNotNull(getProxyClass(ProxyTestClassInner.class));
}
/**
* Test an abstract class
*/
@Test
public void testAbstractClass() throws Exception
{
Object ptca = getProxyInstance(getProxyClass(ProxyTestClassAbstract.class));
ptca = setDelegate(ptca, new Callable<Object>() {
public Object call() throws Exception {
//We have to use a proxy instance here because we need it to be a subclass
//of the one from the weaving loader in the weaving test...
return getProxyInstance(ProxyTestClassChildOfAbstract.class);
}
});
Method m = ptca.getClass().getDeclaredMethod("getMessage");
assertEquals("Working", m.invoke(ptca));
}
public static BundleWiring getWiring(ClassLoader loader) throws Exception {
BundleWiring wiring = mock(BundleWiring.class);
when(wiring.getClassLoader()).thenReturn(loader);
return wiring;
}
}
| 7,808 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassUnweavableChild.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassUnweavableChild extends ProxyTestClassUnweavableSuper{
public ProxyTestClassUnweavableChild() {
super(1);
}
}
| 7,809 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/WovenProxyPlusSubclassGeneratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.SingleInstanceDispatcher;
import org.apache.aries.proxy.impl.gen.ProxySubclassGenerator;
import org.apache.aries.proxy.impl.interfaces.InterfaceProxyGenerator;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.junit.BeforeClass;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
/**
* This class uses the {@link ProxySubclassGenerator} to test
*/
@SuppressWarnings("unchecked")
public class WovenProxyPlusSubclassGeneratorTest extends WovenProxyGeneratorTest
{
private static final Class<?> FINAL_METHOD_CLASS = ProxyTestClassFinalMethod.class;
private static final Class<?> FINAL_CLASS = ProxyTestClassFinal.class;
private Callable<Object> testCallable = null;
private static Bundle testBundle;
@BeforeClass
public static void createTestBundle() throws Exception {
testBundle = mock(Bundle.class);
BundleWiring wiring = AbstractProxyTest.getWiring(weavingLoader);
when(testBundle.adapt(BundleWiring.class))
.thenReturn(wiring);
}
//Avoid running four weaving tests that don't apply to us
public void testUnweavableSuperWithNoNoargsAllTheWay() {}
public void testUnweavableSuperWithFinalMethod() {}
public void testUnweavableSuperWithDefaultMethodInWrongPackage() {}
public void testInnerWithNoParentNoArgs() {}
@Test(expected=NoSuchFieldException.class)
public void testGeneratedSVUIDisSynthetic() throws Exception {
super.testGeneratedSVUIDisSynthetic();
}
//
// /**
// * Test that the methods found declared on the generated proxy subclass are
// * the ones that we expect.
// */
// @Test
// public void testExpectedMethods() throws Exception
// {
// Class<?> superclass = getTestClass();
//
// do {
// Method[] declaredMethods = superclass.getDeclaredMethods();
// List<Method> listOfDeclaredMethods = new ArrayList<Method>();
// for (Method m : declaredMethods) {
//
// if(m.getName().equals("clone") || m.getName().equals("finalize"))
// continue;
//
// int i = m.getModifiers();
// if (Modifier.isPrivate(i) || Modifier.isFinal(i)) {
// // private or final don't get added
// } else if (!(Modifier.isPublic(i) || Modifier.isPrivate(i) || Modifier.isProtected(i))) {
// // the method is default visibility, check the package
// if (m.getDeclaringClass().getPackage().equals(getTestClass().getPackage())) {
// // default vis with same package gets added
// listOfDeclaredMethods.add(m);
// }
// } else {
// listOfDeclaredMethods.add(m);
// }
// }
//
// declaredMethods = listOfDeclaredMethods.toArray(new Method[] {});
// ProxySubclassMethodHashSet<String> foundMethods = new ProxySubclassMethodHashSet<String>(
// declaredMethods.length);
// foundMethods.addMethodArray(declaredMethods);
// // as we are using a set we shouldn't get duplicates
// expectedMethods.addAll(foundMethods);
// superclass = superclass.getSuperclass();
// } while (superclass != null);
//
//
//
// Method[] subclassMethods = getProxyClass(getTestClass()).getDeclaredMethods();
// List<Method> listOfDeclaredMethods = new ArrayList<Method>();
// for (Method m : subclassMethods) {
// if(m.getName().startsWith(WovenProxy.class.getName().replace('.', '_')))
// continue;
//
// listOfDeclaredMethods.add(m);
// }
// subclassMethods = listOfDeclaredMethods.toArray(new Method[] {});
//
// ProxySubclassMethodHashSet<String> generatedMethods = new ProxySubclassMethodHashSet<String>(
// subclassMethods.length);
// generatedMethods.addMethodArray(subclassMethods);
//
// // check that all the methods we have generated were expected
// for (String gen : generatedMethods) {
// assertTrue("Unexpected method: " + gen, expectedMethods.contains(gen));
// }
// // check that all the expected methods were generated
// for (String exp : expectedMethods) {
// assertTrue("Method was not generated: " + exp, generatedMethods.contains(exp));
// }
// // check the sets were the same
// assertEquals("Sets were not the same", expectedMethods, generatedMethods);
//
// }
//
/**
* Test a covariant override method
*/
@Test
public void testCovariant() throws Exception
{
Class<?> proxy = getProxyClass(ProxyTestClassCovariantOverride.class);
Method m = getDeclaredMethod(ProxyTestClassCovariantOverride.class, "getCovariant", new Class[] {});
Object returned = m.invoke(getProxyInstance(proxy));
assertTrue("Object was of wrong type: " + returned.getClass().getSimpleName(),
proxy.getSuperclass().isInstance(returned));
}
/**
* Test a method marked final
*/
@Test
public void testFinalMethod() throws Exception
{
try {
InterfaceProxyGenerator.getProxyInstance(null, FINAL_METHOD_CLASS, Collections.EMPTY_SET,
new Callable<Object>() {
public Object call() throws Exception {
return null;
}} , null).getClass();
} catch (RuntimeException re) {
FinalModifierException e = (FinalModifierException) re.getCause();
assertFalse("Should have found final method not final class", e.isFinalClass());
}
}
/**
* Test a class marked final
*/
@Test
public void testFinalClass() throws Exception
{
try {
InterfaceProxyGenerator.getProxyInstance(null, FINAL_CLASS, Collections.EMPTY_SET,
new Callable<Object>() {
public Object call() throws Exception {
return null;
}} , null).getClass();
} catch (FinalModifierException e) {
assertTrue("Should have found final class", e.isFinalClass());
}
}
@Test
public void testAddingInterfacesToClass() throws Exception {
Object proxy = InterfaceProxyGenerator.getProxyInstance(testBundle, super.getProxyClass(getTestClass()), Arrays.asList(Map.class, Iterable.class), new Callable<Object>() {
int calls = 0;
private Map<String, String> map = new HashMap<String, String>();
{
map.put("key", "value");
}
public Object call() throws Exception {
switch(++calls) {
case 1 :
return WovenProxyPlusSubclassGeneratorTest.super.getProxyInstance(weavingLoader.loadClass(getTestClass().getName()));
case 2 :
return map;
default :
return map.values();
}
}
}, null);
Method m = weavingLoader.loadClass(ProxyTestClassGeneral.class.getName()).getDeclaredMethod("testReturnInt");
m.setAccessible(true);
assertEquals(17, m.invoke(proxy));
assertEquals("value", ((Map<String, String>)proxy).put("key", "value2"));
Iterator<?> it = ((Iterable<?>)proxy).iterator();
assertEquals("value2", it.next());
assertFalse(it.hasNext());
}
@Override
protected Method getDeclaredMethod(Class<?> testClass, String name,
Class<?>... classes) {
Class<?> proxy = getProxyClass(testClass);
while(proxy != null) {
try {
return proxy.getDeclaredMethod(name, classes);
} catch (Exception e) {
proxy = proxy.getSuperclass();
}
}
return null;
}
@Override
protected Object getProxyInstance(Class<?> proxyClass) {
if(proxyClass == ProxyTestClassChildOfAbstract.class) {
return super.getProxyInstance(super.getProxyClass(proxyClass));
}
try {
Constructor<?> con = proxyClass.getDeclaredConstructor(Callable.class, InvocationListener.class);
con.setAccessible(true);
return con.newInstance((testCallable == null) ? new SingleInstanceDispatcher(super.getProxyInstance(proxyClass.getSuperclass())) : testCallable, null);
} catch (Exception e) {
return null;
}
}
@Override
protected Class<?> getProxyClass(Class<?> clazz) {
try {
return InterfaceProxyGenerator.getProxyInstance(testBundle, super.getProxyClass(clazz), Collections.EMPTY_SET,
new Callable<Object>() {
public Object call() throws Exception {
return null;
}} , null).getClass();
} catch (UnableToProxyException e) {
return null;
} catch (RuntimeException re) {
if(re.getCause() instanceof UnableToProxyException)
return null;
else
throw re;
}
}
@Override
protected Object getProxyInstance(Class<?> proxyClass,
InvocationListener listener) {
WovenProxy proxy = (WovenProxy) getProxyInstance(proxyClass);
proxy = proxy.org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance(
new SingleInstanceDispatcher(proxy), listener);
return proxy;
}
} | 7,810 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassSuper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassSuper
{
static {
System.out.println("The time is: " + System.currentTimeMillis());
}
public void bMethod()
{
aPrivateMethod();
}
protected void bProMethod()
{
}
void bDefMethod()
{
}
private void aPrivateMethod()
{
}
public Object getTargetObject() {
return null;
}
@SuppressWarnings("unused")
private void doTarget() {
Object o = getTargetObject();
if(this != o)
((ProxyTestClassSuper)o).doTarget();
}
}
| 7,811 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestSerializableInterface.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
import java.io.Serializable;
public interface ProxyTestSerializableInterface extends Serializable {
}
| 7,812 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassUnweavableChildWithFinalMethodParent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassUnweavableChildWithFinalMethodParent extends ProxyTestClassUnweavableSuperWithFinalMethod{
public ProxyTestClassUnweavableChildWithFinalMethodParent() {
super(1);
}
}
| 7,813 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/ProxyTestClassUnweavableSuper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy;
public class ProxyTestClassUnweavableSuper extends ProxyTestClassUnweavableGrandParent {
public ProxyTestClassUnweavableSuper(int i) {
super(i);
}
String doStuff2() {
return "Hello!";
}
}
| 7,814 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex/AriesTransactionManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy.complex;
import org.apache.aries.blueprint.proxy.complex.manager.MonitorableTransactionManager;
import org.apache.aries.blueprint.proxy.complex.manager.RecoverableTransactionManager;
import org.apache.aries.blueprint.proxy.complex.manager.XAWork;
import org.apache.aries.blueprint.proxy.complex.manager.XidImporter;
import javax.resource.spi.XATerminator;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
public interface AriesTransactionManager extends
TransactionManager, UserTransaction,
TransactionSynchronizationRegistry, XidImporter,
MonitorableTransactionManager, RecoverableTransactionManager,
XATerminator, XAWork {
}
| 7,815 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex/manager/MonitorableTransactionManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy.complex.manager;
import java.util.EventListener;
public interface MonitorableTransactionManager extends EventListener {
}
| 7,816 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex/manager/XidImporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy.complex.manager;
public interface XidImporter {
}
| 7,817 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex/manager/RecoverableTransactionManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy.complex.manager;
import javax.transaction.TransactionManager;
public interface RecoverableTransactionManager extends TransactionManager {
}
| 7,818 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/complex/manager/XAWork.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy.complex.manager;
public interface XAWork {
}
| 7,819 |
0 | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy | Create_ds/aries/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/pkg/ProxyTestClassUnweavableSuperWithDefaultMethodWrongPackageParent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.proxy.pkg;
import org.apache.aries.blueprint.proxy.ProxyTestClassUnweavableGrandParent;
public class ProxyTestClassUnweavableSuperWithDefaultMethodWrongPackageParent
extends ProxyTestClassUnweavableGrandParent{
public ProxyTestClassUnweavableSuperWithDefaultMethodWrongPackageParent() {
super(1);
}
String doStuff2() {
return "Hello!";
}
}
| 7,820 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/AbstractProxyManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import static java.lang.String.format;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
public abstract class AbstractProxyManager implements ProxyManager
{
public final Object createDelegatingProxy(Bundle clientBundle, Collection<Class<?>> classes,
Callable<Object> dispatcher, Object template)
throws UnableToProxyException
{
return createDelegatingInterceptingProxy(clientBundle, classes, dispatcher, template, null);
}
public Object createInterceptingProxy(Bundle clientBundle,
Collection<Class<?>> classes, Object delegate, InvocationListener listener)
throws UnableToProxyException {
if (delegate instanceof WovenProxy) {
WovenProxy proxy = ((WovenProxy) delegate).
org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance(
new SingleInstanceDispatcher(delegate), listener);
return proxy;
} else {
return createDelegatingInterceptingProxy(clientBundle, classes,
new SingleInstanceDispatcher(delegate), delegate, listener);
}
}
public final Object createDelegatingInterceptingProxy(Bundle clientBundle, Collection<Class<?>> classes,
Callable<Object> dispatcher, Object template, InvocationListener listener)
throws UnableToProxyException
{
if(dispatcher == null)
throw new NullPointerException("You must specify a dipatcher");
if (template instanceof WovenProxy) {
WovenProxy proxy = ((WovenProxy) template).
org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance(
dispatcher, listener);
return proxy;
}
Object proxyObject = duplicateProxy(classes, dispatcher, template, listener);
if (proxyObject == null) {
proxyObject = createNewProxy(clientBundle, classes, dispatcher, listener);
}
return proxyObject;
}
public final Callable<Object> unwrap(Object proxy)
{
Callable<Object> target = null;
if(proxy instanceof WovenProxy) {
//Woven proxies are a bit different, they can be proxies without
//having a dispatcher, so we fake one up if we need to
WovenProxy wp = (WovenProxy) proxy;
if(wp.org_apache_aries_proxy_weaving_WovenProxy_isProxyInstance()) {
target = wp.org_apache_aries_proxy_weaving_WovenProxy_unwrap();
if(target == null) {
target = new SingleInstanceDispatcher(proxy);
}
}
} else {
InvocationHandler ih = getInvocationHandler(proxy);
if (ih instanceof ProxyHandler) {
target = ((ProxyHandler)ih).getTarget();
}
}
return target;
}
public final boolean isProxy(Object proxy)
{
return (proxy != null &&
((proxy instanceof WovenProxy && ((WovenProxy)proxy).org_apache_aries_proxy_weaving_WovenProxy_isProxyInstance()) ||
getInvocationHandler(proxy) instanceof ProxyHandler));
}
protected abstract Object createNewProxy(Bundle clientBundle, Collection<Class<?>> classes,
Callable<Object> dispatcher, InvocationListener listener) throws UnableToProxyException;
protected abstract InvocationHandler getInvocationHandler(Object proxy);
protected abstract boolean isProxyClass(Class<?> clazz);
protected synchronized ClassLoader getClassLoader(final Bundle clientBundle, Collection<Class<?>> classes)
{
if (clientBundle != null && clientBundle.getState() == Bundle.UNINSTALLED) {
throw new IllegalStateException(format("The bundle %s at version %s with id %d has been uninstalled.",
clientBundle.getSymbolicName(), clientBundle.getVersion(), clientBundle.getBundleId()));
}
ClassLoader cl = null;
if (classes.size() == 1) cl = classes.iterator().next().getClassLoader();
if (cl == null) {
cl = getWiringClassloader(clientBundle);
}
return cl;
}
private ClassLoader getWiringClassloader(final Bundle bundle) {
BundleWiring wiring = bundle != null ? bundle.adapt(BundleWiring.class) : null;
return wiring != null ? wiring.getClassLoader() : null;
}
private Object duplicateProxy(Collection<Class<?>> classes, Callable<Object> dispatcher,
Object template, InvocationListener listener)
{
Object proxyObject = null;
Class<?> classToProxy = null;
if (template != null) {
if(isProxyClass(template.getClass()))
classToProxy = template.getClass();
} else if (classes.size() == 1) {
classToProxy = classes.iterator().next();
if(!!!isProxyClass(classToProxy))
classToProxy = null;
}
if (classToProxy != null) {
try {
/*
* the class is already a proxy, we should just invoke
* the constructor to get a new instance of the proxy
* with a new Collaborator using the specified delegate
*/
if(WovenProxy.class.isAssignableFrom(classToProxy)) {
Constructor<?> c = classToProxy.getDeclaredConstructor(Callable.class,
InvocationListener.class);
c.setAccessible(true);
proxyObject = c.newInstance(dispatcher, listener);
} else {
proxyObject = classToProxy.getConstructor(InvocationHandler.class).
newInstance(new ProxyHandler(this, dispatcher, listener));
}
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
} catch (InstantiationException e) {
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
} catch (IllegalAccessException e) {
}
}
return proxyObject;
}
} | 7,821 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/SingleInstanceDispatcher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import java.util.concurrent.Callable;
/**
* Dispatch to a single fixed instance
*/
public final class SingleInstanceDispatcher implements Callable<Object> {
private final Object delegate;
public SingleInstanceDispatcher(Object delegate) {
this.delegate = delegate;
}
public final Object call() throws Exception {
return delegate;
}
}
| 7,822 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/DefaultWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import java.lang.reflect.Method;
import org.apache.aries.proxy.InvocationListener;
public class DefaultWrapper implements InvocationListener {
public Object preInvoke(Object proxy, Method m, Object[] args)
throws Throwable {
return null;
}
public void postInvoke(Object token, Object proxy, Method m, Object returnValue)
throws Throwable {
}
public void postInvokeExceptionalReturn(Object token, Object proxy, Method m,
Throwable exception) throws Throwable {
}
}
| 7,823 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/ProxyHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.InvocationListener;
public final class ProxyHandler implements InvocationHandler {
private final Callable<Object> target;
private final InvocationHandler core;
private final AbstractProxyManager proxyManager;
public ProxyHandler(AbstractProxyManager abstractProxyManager, Callable<Object> dispatcher, InvocationListener listener)
{
target = dispatcher;
proxyManager = abstractProxyManager;
final InvocationListener nonNullListener;
if (listener == null) {
nonNullListener = new DefaultWrapper();
} else {
nonNullListener = listener;
}
core = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
Object result = null;
Object token = null;
boolean inInvoke = false;
try {
token = nonNullListener.preInvoke(proxy, method, args);
inInvoke = true;
result = nonNullListener.aroundInvoke(token, proxy, target, method, args);
inInvoke = false;
nonNullListener.postInvoke(token, proxy, method, result);
} catch (Throwable e) {
// whether the the exception is an error is an application decision
// if we catch an exception we decide carefully which one to
// throw onwards
Throwable exceptionToRethrow = null;
// if the exception came from a precall or postcall
// we will rethrow it
if (!inInvoke) {
exceptionToRethrow = e;
}
// if the exception didn't come from precall or postcall then it
// came from invoke
// we will rethrow this exception if it is not a runtime
// exception, but we must unwrap InvocationTargetExceptions
else {
if (e instanceof InvocationTargetException) {
e = ((InvocationTargetException) e).getTargetException();
}
if (!(e instanceof RuntimeException)) {
exceptionToRethrow = e;
}
}
try {
nonNullListener.postInvokeExceptionalReturn(token, proxy, method, e);
} catch (Exception f) {
// we caught an exception from
// postInvokeExceptionalReturn
// if we haven't already chosen an exception to rethrow then
// we will throw this exception
if (exceptionToRethrow == null) {
exceptionToRethrow = f;
}
}
// if we made it this far without choosing an exception we
// should throw e
if (exceptionToRethrow == null) {
exceptionToRethrow = e;
}
throw exceptionToRethrow;
}
return result;
}
};
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
// Unwrap calls for equals
if (method.getName().equals("equals")
&& method.getParameterTypes().length == 1 &&
method.getParameterTypes()[0] == Object.class) {
Object targetObject = args[0];
if (proxyManager.isProxy(targetObject)) {
args[0] = proxyManager.unwrap(targetObject).call();
}
} else if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) {
// special case finalize, don't route through to delegate because that will get its own call
return null;
}
return core.invoke(proxy, method, args);
}
public Callable<Object> getTarget()
{
return target;
}
} | 7,824 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/JdkProxyManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.proxy.UnableToProxyException;
import org.osgi.framework.Bundle;
public final class JdkProxyManager extends AbstractProxyManager implements ProxyManager
{
public Object createNewProxy(Bundle clientBundle, Collection<Class<?>> classes,
Callable<Object> dispatcher, InvocationListener listener) throws UnableToProxyException
{
return Proxy.newProxyInstance(getClassLoader(clientBundle, classes), getInterfaces(classes), new ProxyHandler(this, dispatcher, listener));
}
private static final Class<?>[] getInterfaces(Collection<Class<?>> classes) throws UnableToProxyException
{
for (Class<?> clazz : classes) {
if (!!!clazz.isInterface()) {
throw new UnableToProxyException(clazz, String.format("The class %s is not an interface and therefore a proxy cannot be generated.", clazz.getName()));
}
}
return (Class[]) classes.toArray(new Class[classes.size()]);
}
@Override
protected boolean isProxyClass(Class<?> clazz)
{
return Proxy.isProxyClass(clazz);
}
@Override
protected InvocationHandler getInvocationHandler(Object proxy)
{
Class<?> clazz = proxy.getClass();
if (isProxyClass(clazz)) {
return Proxy.getInvocationHandler(proxy);
}
return null;
}
} | 7,825 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/AsmProxyManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.gen.ProxySubclassGenerator;
import org.apache.aries.proxy.impl.interfaces.InterfaceProxyGenerator;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.osgi.framework.Bundle;
public final class AsmProxyManager extends AbstractProxyManager implements ProxyManager
{
static final ClassLoader bootClassLoader = new ClassLoader(Object.class.getClassLoader()) { /* boot class loader */};
public Object createNewProxy(Bundle clientBundle, Collection<Class<?>> classes,
Callable<Object> dispatcher, InvocationListener listener) throws UnableToProxyException
{
Object proxyObject = null;
// if we just have interfaces and no classes we default to using
// the interface proxy because we can't dynamically
// subclass more than one interface
// unless we have a class
// that implements all of them
// loop through the classes checking if they are java interfaces
// if we find any class that isn't an interface we need to use
// the subclass proxy
Set<Class<?>> notInterfaces = new HashSet<Class<?>>();
Set<Class<?>> interfaces = new HashSet<Class<?>>();
for (Class<?> clazz : classes) {
if (!!!clazz.isInterface()) {
notInterfaces.add(clazz);
} else {
interfaces.add(clazz);
}
}
// if we just have no classes we default to using
// the interface proxy because we can't dynamically
// subclass more than one interface
// unless we have a class
// that implements all of them
if (notInterfaces.isEmpty()) {
proxyObject = InterfaceProxyGenerator.getProxyInstance(clientBundle, null, interfaces, dispatcher, listener);
} else {
// if we need to use the subclass proxy then we need to find
// the most specific class
Class<?> classToProxy = getLowestSubclass(notInterfaces);
if(WovenProxy.class.isAssignableFrom(classToProxy)) {
if(isConcrete(classToProxy) && implementsAll(classToProxy, interfaces)) {
try {
Constructor<?> c = classToProxy.getDeclaredConstructor(Callable.class,
InvocationListener.class);
c.setAccessible(true);
proxyObject = c.newInstance(dispatcher, listener);
} catch (Exception e) {
//We will have to subclass this one, but we should always have a constructor
//to use
//TODO log that performance would be improved by using a non-null template
}
} else {
//We need to generate a class that implements the interfaces (if any) and
//has the classToProxy as a superclass
if((classToProxy.getModifiers() & Modifier.FINAL) != 0) {
throw new UnableToProxyException(classToProxy, "The class " + classToProxy
+ " does not implement all of the interfaces " + interfaces +
" and is final. This means that we cannot create a proxy for both the class and all of the requested interfaces.");
}
proxyObject = InterfaceProxyGenerator.getProxyInstance(clientBundle,
classToProxy, interfaces, dispatcher, listener);
}
}
if(proxyObject == null){
// ARIES-1216 : in some cases, some class can not be visible from the root class classloader.
// If that's the case, we need to build a custom classloader that has visibility on all those classes
// If we could generate a proper constructor this would not be necessary, but since we have to rely
// on the generated serialization constructor to bypass the JVM verifier, we don't have much choice
ClassLoader classLoader = classToProxy.getClassLoader();
if (classLoader == null) {
classLoader = bootClassLoader;
}
boolean allVisible = true;
for (Class<?> clazz : classes) {
try {
if (classLoader.loadClass(clazz.getName()) != clazz) {
throw new UnableToProxyException(classToProxy, "The requested class " + clazz + " is different from the one seen by by " + classToProxy);
}
} catch (ClassNotFoundException e) {
allVisible = false;
break;
}
}
if (!allVisible) {
List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
for (Class<?> clazz : classes) {
ClassLoader cl = clazz.getClassLoader();
if (cl != null && !classLoaders.contains(cl)) {
classLoaders.add(cl);
}
}
classLoader = new MultiClassLoader(classLoaders);
}
proxyObject = ProxySubclassGenerator.newProxySubclassInstance(classToProxy, classLoader, new ProxyHandler(this, dispatcher, listener));
}
}
return proxyObject;
}
private static class MultiClassLoader extends ClassLoader {
private final List<ClassLoader> parents;
private MultiClassLoader(List<ClassLoader> parents) {
this.parents = parents;
}
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
for (ClassLoader cl : parents) {
try {
return cl.loadClass(name);
} catch (ClassNotFoundException e) {
// Ignore
}
}
try {
// use bootClassLoader as last fallback
return bootClassLoader.loadClass(name);
} catch (ClassNotFoundException e) {
// Ignore
}
throw new ClassNotFoundException(name);
}
@Override
public URL getResource(String name) {
for (ClassLoader cl : parents) {
URL url = cl.getResource(name);
if (url != null) {
return url;
}
}
return null;
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
final List<Enumeration<URL>> tmp = new ArrayList<Enumeration<URL>>();
for (ClassLoader cl : parents) {
tmp.add(cl.getResources(name));
}
return new Enumeration<URL>() {
int index = 0;
@Override
public boolean hasMoreElements() {
return next();
}
@Override
public URL nextElement() {
if (!next()) {
throw new NoSuchElementException();
}
return tmp.get(index).nextElement();
}
private boolean next() {
while (index < tmp.size()) {
if (tmp.get(index) != null && tmp.get(index).hasMoreElements()) {
return true;
}
index++;
}
return false;
}
};
}
}
private Class<?> getLowestSubclass(Set<Class<?>> notInterfaces) throws
UnableToProxyException {
Iterator<Class<?>> it = notInterfaces.iterator();
Class<?> classToProxy = it.next();
while(it.hasNext()) {
Class<?> potential = it.next();
if(classToProxy.isAssignableFrom(potential)) {
//potential can be widened to classToProxy, and is therefore
//a lower subclass
classToProxy = potential;
} else if (!!!potential.isAssignableFrom(classToProxy)){
//classToProxy is not a subclass of potential - This is
//an error, we can't be part of two hierarchies at once!
throw new UnableToProxyException(classToProxy, "The requested classes "
+ classToProxy + " and " + potential + " are not in the same type hierarchy");
}
}
return classToProxy;
}
private boolean isConcrete(Class<?> classToProxy) {
return (classToProxy.getModifiers() & Modifier.ABSTRACT) == 0;
}
private boolean implementsAll(Class<?> classToProxy, Set<Class<?>> interfaces) {
//If we can't widen to one of the interfaces then we need to do some more work
for(Class<?> iface : interfaces) {
if(!!!iface.isAssignableFrom(classToProxy))
return false;
}
return true;
}
@Override
protected boolean isProxyClass(Class<?> clazz)
{
return WovenProxy.class.isAssignableFrom(clazz) || ProxySubclassGenerator.isProxySubclass(clazz) || Proxy.isProxyClass(clazz);
}
@Override
protected InvocationHandler getInvocationHandler(Object proxy)
{
Class<?> type = proxy.getClass();
InvocationHandler ih = null;
if (ProxySubclassGenerator.isProxySubclass(type)) {
ih = ProxySubclassGenerator.getInvocationHandler(proxy);
} else if (Proxy.isProxyClass(type)) {
ih = Proxy.getInvocationHandler(proxy);
}
return ih;
}
} | 7,826 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/SystemModuleClassLoader.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class SystemModuleClassLoader extends ClassLoader {
private static java.lang.reflect.Method method_Class_getModule;
private static java.lang.reflect.Method method_Module_getResourceAsStream ;
static {
try {
method_Class_getModule = Class.class.getMethod("getModule");
method_Module_getResourceAsStream = method_Class_getModule.getReturnType()
.getMethod("getResourceAsStream", String.class);
} catch (NoSuchMethodException e) {
//this isn't java9 with jigsaw
}
}
public SystemModuleClassLoader(ClassLoader parentLoader) {
super(parentLoader);
}
public SystemModuleClassLoader() {
super();
}
@Override
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
if (url == null) {
// try java9 module resource loader
if (method_Class_getModule == null || method_Module_getResourceAsStream == null) {
return null; // not Java 9 JIGSAW
}
try {
String className = name.replace('/', '.');
int lastDot = className.lastIndexOf('.');
className = className.substring(0, lastDot);
final Class<?> clazz = Class.forName(className, false, this);
final Object module = method_Class_getModule.invoke(clazz);
return (InputStream)method_Module_getResourceAsStream
.invoke(module, name);
} catch (Exception e) {
return null; // not found
}
} else {
try {
return url.openStream();
} catch (IOException e) {
return null;
}
}
}
}
| 7,827 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/ProxyManagerActivator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import org.apache.aries.proxy.ProxyManager;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class ProxyManagerActivator implements BundleActivator
{
private static final boolean ASM_PROXY_SUPPORTED;
private AbstractProxyManager managerService;
@SuppressWarnings("rawtypes")
private ServiceRegistration registration;
static
{
boolean classProxy = false;
try {
// Try load load a asm class (to make sure it's actually available
// then create the asm factory
Class.forName("org.objectweb.asm.ClassVisitor", false, ProxyManagerActivator.class.getClassLoader());
classProxy = true;
} catch (Throwable t) {
}
ASM_PROXY_SUPPORTED = classProxy;
}
public void start(BundleContext context)
{
if (ASM_PROXY_SUPPORTED) {
managerService = new AsmProxyManager();
try {
//if ASM is available then we should also try weaving
Class<?> cls = Class.forName("org.apache.aries.proxy.impl.weaving.ProxyWeavingHook",
true, ProxyManagerActivator.class.getClassLoader());
cls.getConstructor(BundleContext.class).newInstance(context);
} catch (Throwable t) {
//We don't care about this, we just won't have registered the hook
}
} else {
managerService = new JdkProxyManager();
}
registration = context.registerService(ProxyManager.class.getName(), managerService, null);
}
public void stop(BundleContext context)
{
registration.unregister();
}
} | 7,828 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/ProxyUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl;
import java.math.BigDecimal;
import org.objectweb.asm.Opcodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProxyUtils
{
private static Logger LOGGER = LoggerFactory.getLogger(ProxyUtils.class);
public static final int JAVA_CLASS_VERSION = new BigDecimal(System.getProperty("java.class.version")).intValue();
private static int weavingJavaVersion = -1; // initialise an invalid number
/**
* Get the java version to be woven at.
* @return
*/
public static int getWeavingJavaVersion() {
if (weavingJavaVersion == -1 ) {
//In order to avoid an inconsistent stack error the version of the woven byte code needs to match
//the level of byte codes in the original class
switch(JAVA_CLASS_VERSION) {
case Opcodes.V21:
LOGGER.debug("Weaving to Java 21");
weavingJavaVersion = Opcodes.V21;
break;
case Opcodes.V20:
LOGGER.debug("Weaving to Java 20");
weavingJavaVersion = Opcodes.V20;
break;
case Opcodes.V19:
LOGGER.debug("Weaving to Java 19");
weavingJavaVersion = Opcodes.V19;
break;
case Opcodes.V18:
LOGGER.debug("Weaving to Java 18");
weavingJavaVersion = Opcodes.V18;
break;
case Opcodes.V17:
LOGGER.debug("Weaving to Java 17");
weavingJavaVersion = Opcodes.V17;
break;
case Opcodes.V16:
LOGGER.debug("Weaving to Java 16");
weavingJavaVersion = Opcodes.V16;
break;
case Opcodes.V15:
LOGGER.debug("Weaving to Java 15");
weavingJavaVersion = Opcodes.V15;
break;
case Opcodes.V14:
LOGGER.debug("Weaving to Java 14");
weavingJavaVersion = Opcodes.V14;
break;
case Opcodes.V13:
LOGGER.debug("Weaving to Java 13");
weavingJavaVersion = Opcodes.V13;
break;
case Opcodes.V12:
LOGGER.debug("Weaving to Java 12");
weavingJavaVersion = Opcodes.V12;
break;
case Opcodes.V11:
LOGGER.debug("Weaving to Java 11");
weavingJavaVersion = Opcodes.V11;
break;
case Opcodes.V10:
LOGGER.debug("Weaving to Java 10");
weavingJavaVersion = Opcodes.V10;
break;
case Opcodes.V9:
LOGGER.debug("Weaving to Java 9");
weavingJavaVersion = Opcodes.V9;
break;
case Opcodes.V1_8:
LOGGER.debug("Weaving to Java 8");
weavingJavaVersion = Opcodes.V1_8;
break;
case Opcodes.V1_7:
LOGGER.debug("Weaving to Java 7");
weavingJavaVersion = Opcodes.V1_7;
break;
case Opcodes.V1_6:
LOGGER.debug("Weaving to Java 6");
weavingJavaVersion = Opcodes.V1_6;
break;
case Opcodes.V1_5:
LOGGER.debug("Weaving to Java 5");
weavingJavaVersion = Opcodes.V1_5;
break;
default:
//aries should work with Java 5 or above - also will highlight when a higher level (and unsupported) level of Java is released
throw new IllegalArgumentException("Invalid Java version " + JAVA_CLASS_VERSION);
}
}
return weavingJavaVersion;
}
}
| 7,829 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/weaving/ProxyWeavingHook.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.weaving;
import static java.lang.String.format;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.apache.aries.proxy.weavinghook.ProxyWeavingController;
import org.apache.aries.proxy.weavinghook.WeavingHelper;
import org.objectweb.asm.ClassReader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.hooks.weaving.WeavingException;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class ProxyWeavingHook implements WeavingHook, WeavingHelper {
public static final String WEAVING_ENABLED_CLASSES = "org.apache.aries.proxy.weaving.enabled";
public static final String WEAVING_DISABLED_CLASSES = "org.apache.aries.proxy.weaving.disabled";
public static final String WEAVING_ENABLED_CLASSES_DEFAULT = "*";
public static final String WEAVING_DISABLED_CLASSES_DEFAULT = "org.objectweb.asm.*,org.slf4j.*,org.apache.log4j.*,javax.*,ch.qos.logback.*";
private static final Logger LOGGER = LoggerFactory.getLogger(ProxyWeavingHook.class);
/** An import of the WovenProxy package */
private static final String IMPORT_A = "org.apache.aries.proxy.weaving";
/**
* An import for the InvocationListener class that we will need.
* This should automatically wire to the right thing because of the uses clause
* on the impl.weaving package
*/
private static final String IMPORT_B = "org.apache.aries.proxy";
private final List<Pattern> enabled;
private final List<Pattern> disabled;
@SuppressWarnings("rawtypes")
private final ServiceTracker controllers;
@SuppressWarnings({
"unchecked", "rawtypes"
})
public ProxyWeavingHook(BundleContext context) {
String enabledProp = context != null ? context.getProperty(WEAVING_ENABLED_CLASSES) : null;
enabled = parseMatchers(enabledProp, WEAVING_ENABLED_CLASSES_DEFAULT);
disabled = parseMatchers(context != null ? context.getProperty(WEAVING_DISABLED_CLASSES) : null, WEAVING_DISABLED_CLASSES_DEFAULT);
controllers = new ServiceTracker(context, ProxyWeavingController.class.getName(), null);
controllers.open();
if (!"none".equals(enabledProp)) {
Dictionary<String,String> props = new Hashtable<String,String>();
// SubsystemResource.java also uses this constant.
// While it could be turned into a static final constant, note that this
// is also a non-standard workaround in the absence of a solution in the spec.
// See the associated OSGi spec bug.
props.put("osgi.woven.packages", "org.apache.aries.proxy.weaving,org.apache.aries.proxy");
context.registerService("org.osgi.framework.hooks.weaving.WeavingHook", this, props);
}
}
public final void weave(WovenClass wovenClass) {
BundleWiring bw = wovenClass.getBundleWiring();
if (bw != null) {
Bundle b = bw.getBundle();
if(b.getBundleId() == 0 ||
b.getSymbolicName().startsWith("org.apache.aries.proxy") ||
b.getSymbolicName().startsWith("org.apache.aries.util")) {
return;
}
}
if (!isEnabled(wovenClass.getClassName()) || isDisabled(wovenClass.getClassName())) {
return;
}
if (shouldWeave(wovenClass)) {
byte[] bytes = null;
try {
bytes = WovenProxyGenerator.getWovenProxy(wovenClass.getBytes(),
wovenClass.getBundleWiring().getClassLoader());
} catch (Exception e) {
if(e instanceof RuntimeException &&
e.getCause() instanceof UnableToProxyException){
//This is a weaving failure that should be logged, but the class
//can still be loaded
LOGGER.trace(String.format("The class %s cannot be woven, it may not be possible for the runtime to proxy this class.",
wovenClass.getClassName()), e);
} else {
throw weavingException(wovenClass, e);
}
}
if(bytes != null && bytes.length != 0) {
wovenClass.setBytes(bytes);
List<String> imports = wovenClass.getDynamicImports();
imports.add(IMPORT_A);
imports.add(IMPORT_B);
}
}
}
private List<Pattern> parseMatchers(String matchers, String def) {
String[] strings = (matchers != null ? matchers : def).split(",");
List<Pattern> patterns = new ArrayList<Pattern>();
for (String str : strings) {
str = str.trim();
if (str.length() != 0) {
str = str.replaceAll("\\.", "\\\\.");
str = str.replaceAll("\\*", ".*");
Pattern p = Pattern.compile(str);
patterns.add(p);
}
}
return patterns;
}
boolean isEnabled(String className) {
return matches(enabled, className);
}
boolean isDisabled(String className) {
return matches(disabled, className);
}
private boolean matches(List<Pattern> patterns, String className) {
for (Pattern p : patterns) {
if (p.matcher(className).matches()) {
return true;
}
}
return false;
}
public boolean isWoven(Class<?> clazz)
{
return WovenProxy.class.isAssignableFrom(clazz);
}
public boolean isSuperClassWoven(WovenClass wovenClass)
{
ClassReader cReader = new ClassReader(wovenClass.getBytes());
try {
Class<?> superClass = Class.forName(cReader.getSuperName().replace('/', '.'), false,
wovenClass.getBundleWiring().getClassLoader());
return WovenProxy.class.isAssignableFrom(superClass);
} catch (ClassNotFoundException e) {
throw weavingException(wovenClass, e);
}
}
private boolean shouldWeave(WovenClass wovenClass)
{
// assume we weave
boolean result = true;
Object[] cs = controllers.getServices();
// if we have at least 1 weaving controller
if (cs != null && cs.length > 0) {
// first of all set to false.
result = false;
for (Object obj : cs) {
ProxyWeavingController c = (ProxyWeavingController) obj;
if (c.shouldWeave(wovenClass, this)) {
// exit as soon as we get told to weave, otherwise keep going.
return true;
}
}
}
return result;
}
private WeavingException weavingException(WovenClass wovenClass, Exception e) {
String msg = format("There was a serious error trying to weave the class %s. See the associated exception for more information.",
wovenClass.getClassName());
// This is a failure that should stop the class loading!
LOGGER.error(msg, e);
return new WeavingException(msg, e);
}
} | 7,830 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/weaving/WovenProxyGenerator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.weaving;
import static org.objectweb.asm.Opcodes.ACC_ANNOTATION;
import static org.objectweb.asm.Opcodes.ACC_ENUM;
import static org.objectweb.asm.Opcodes.ACC_INTERFACE;
import org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter;
import org.apache.aries.proxy.impl.common.OSGiFriendlyClassVisitor;
import org.apache.aries.proxy.impl.common.OSGiFriendlyClassWriter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
/**
* This class is used to weave the bytes of a class into a proxyable class
*/
public final class WovenProxyGenerator
{
public static final byte[] getWovenProxy(byte[] original, ClassLoader loader){
ClassReader cReader = new ClassReader(original);
//Don't weave interfaces, enums or annotations
if((cReader.getAccess() & (ACC_INTERFACE | ACC_ANNOTATION | ACC_ENUM)) != 0)
return null;
//If we are Java 1.6 + compiled then we need to compute stack frames, otherwise
//maxs are fine (and faster)
int computeVal = AbstractWovenProxyAdapter.IS_AT_LEAST_JAVA_6 ?
ClassWriter.COMPUTE_FRAMES : ClassWriter.COMPUTE_MAXS;
ClassWriter cWriter = new OSGiFriendlyClassWriter(cReader, computeVal, loader);
ClassVisitor cv = new OSGiFriendlyClassVisitor(cWriter, computeVal );
//Wrap our outer layer to add the original SerialVersionUID if it was previously being defaulted
ClassVisitor weavingAdapter = new SyntheticSerialVerUIDAdder(
new WovenProxyAdapter(cv, cReader.getClassName(), loader));
// If we are Java 1.6 + then we need to skip frames as they will be recomputed
cReader.accept(weavingAdapter, AbstractWovenProxyAdapter.IS_AT_LEAST_JAVA_6 ? ClassReader.SKIP_FRAMES : 0);
return cWriter.toByteArray();
}
} | 7,831 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/weaving/SyntheticSerialVerUIDAdder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.weaving;
import java.lang.reflect.Modifier;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.SerialVersionUIDAdder;
import static org.objectweb.asm.Opcodes.ASM9;
class SyntheticSerialVerUIDAdder extends SerialVersionUIDAdder {
private WovenProxyAdapter wpa;
//copied from superclass, they are now private
/**
* Flag that indicates if we need to compute SVUID.
*/
private boolean computeSVUID;
/**
* Set to true if the class already has SVUID.
*/
private boolean hasSVUID;
public SyntheticSerialVerUIDAdder(WovenProxyAdapter cv) {
super(ASM9, cv);
wpa = cv;
}
// The following visit and visitField methods are workaround since ASM4 does not supply the javadoced method isHasSVUID() by mistake.
// When the method isHasSVUId() or similar methods available, we can remove the following two methods.
@Override
public void visit(
final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces) {
computeSVUID = (access & Opcodes.ACC_INTERFACE) == 0;
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public FieldVisitor visitField(
final int access,
final String name,
final String desc,
final String signature,
final Object value) {
if (computeSVUID) {
if ("serialVersionUID".equals(name) && Modifier.isFinal(access) && Modifier.isStatic(access) && Type.LONG_TYPE.equals(Type.getType(desc))) {
// since the class already has SVUID, we won't be computing it.
computeSVUID = false;
hasSVUID = true;
}
}
return super.visitField(access, name, desc, signature, value);
}
@Override
public void visitEnd() {
wpa.setSVUIDGenerated(!!!hasSVUID);
super.visitEnd();
}
}
| 7,832 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/weaving/WovenProxyAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.weaving;
import org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter;
import org.apache.aries.proxy.impl.common.WovenProxyConcreteMethodAdapter;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
/**
* Used to weave classes processed by the {@link ProxyWeavingHook}
*/
final class WovenProxyAdapter extends AbstractWovenProxyAdapter {
private boolean sVUIDGenerated = false;
public WovenProxyAdapter(ClassVisitor writer, String className,
ClassLoader loader) {
super(writer, className, loader);
}
/**
* Get the weaving visitor used to weave instance methods, or just copy abstract ones
*/
protected final MethodVisitor getWeavingMethodVisitor(int access, String name,
String desc, String signature, String[] exceptions, Method currentMethod,
String methodStaticFieldName, Type currentMethodDeclaringType,
boolean currentMethodDeclaringTypeIsInterface) {
MethodVisitor methodVisitorToReturn;
if((access & ACC_ABSTRACT) == 0) {
methodVisitorToReturn = new WovenProxyConcreteMethodAdapter(cv.visitMethod(
access, name, desc, signature, exceptions), access, name, desc,
exceptions, methodStaticFieldName, currentMethod, typeBeingWoven,
currentMethodDeclaringType, currentMethodDeclaringTypeIsInterface);
} else {
methodVisitorToReturn = cv.visitMethod(access, name, desc, signature, exceptions);
}
return methodVisitorToReturn;
}
@Override
public FieldVisitor visitField(int access, String name, String arg2,
String arg3, Object arg4) {
//If this sVUID is generated then make it synthetic
if(sVUIDGenerated && "serialVersionUID".equals(name)) {
//If we aren't a serializable class then don't add a generated sVUID
if(!!!isSerializable) {
return null;
}
access |= ACC_SYNTHETIC;
}
return super.visitField(access, name, arg2, arg3, arg4);
}
public void setSVUIDGenerated(boolean b) {
sVUIDGenerated = b;
}
} | 7,833 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/ProxySubclassHierarchyAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.gen;
import java.util.Collection;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Although we implement ClassVisitor we are only interested in the methods of
* the superclasses in the hierarchy. For this reason although visitMethod is
* implemented the other methods of ClassVisitor are currently no-op.
*
*
*/
public class ProxySubclassHierarchyAdapter extends ClassVisitor implements Opcodes
{
private ProxySubclassAdapter adapter = null;
private Collection<String> methodsToImplement = null;
private static Logger LOGGER = LoggerFactory.getLogger(ProxySubclassHierarchyAdapter.class);
ProxySubclassHierarchyAdapter(ProxySubclassAdapter adapter, Collection<String> methodsToImplement)
{
super(Opcodes.ASM9);
LOGGER.debug(Constants.LOG_ENTRY, "ProxySubclassHeirarchyAdapter", new Object[] {
this, adapter, methodsToImplement });
this.methodsToImplement = methodsToImplement;
this.adapter = adapter;
LOGGER.debug(Constants.LOG_EXIT, "ProxySubclassHeirarchyAdapter", this);
}
public MethodVisitor visitMethod(int access, String name, String desc, String signature,
String[] exceptions)
{
LOGGER.debug(Constants.LOG_ENTRY, "visitMethod", new Object[] { access, name, desc,
signature, exceptions });
// if the method we find in the superclass is one that is available on
// the class
// we are dynamically subclassing then we need to implement an
// invocation for it
String argDesc = ProxySubclassMethodHashSet.typeArrayToStringArgDescriptor(Type
.getArgumentTypes(desc));
if (methodsToImplement.contains(name + argDesc)) {
// create the method in bytecode
adapter.visitMethod(access, name, desc, signature, exceptions);
}
LOGGER.debug(Constants.LOG_EXIT, "visitMethod");
// always return null because we don't want to copy any method code
return null;
}
public void visit(int arg0, int arg1, String arg2, String arg3, String arg4, String[] arg5)
{
// no-op
}
public AnnotationVisitor visitAnnotation(String arg0, boolean arg1)
{
// don't process any annotations at this stage
return null;
}
public void visitAttribute(Attribute arg0)
{
// no-op
}
public void visitEnd()
{
// no-op
}
public FieldVisitor visitField(int arg0, String arg1, String arg2, String arg3, Object arg4)
{
// don't process fields
return null;
}
public void visitInnerClass(String arg0, String arg1, String arg2, int arg3)
{
// no-op
}
public void visitOuterClass(String arg0, String arg1, String arg2)
{
// no-op
}
public void visitSource(String arg0, String arg1)
{
// no-op
}
}
| 7,834 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/UnableToLoadProxyException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.gen;
import org.apache.aries.proxy.UnableToProxyException;
public class UnableToLoadProxyException extends UnableToProxyException
{
/**
*
*/
private static final long serialVersionUID = 506487573157016476L;
public UnableToLoadProxyException(String className, Exception e)
{
super(className, e);
}
}
| 7,835 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/ProxySubclassMethodHashSet.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.gen;
import java.util.HashSet;
import org.objectweb.asm.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProxySubclassMethodHashSet<E> extends HashSet<String>
{
private static final long serialVersionUID = 7674408912532811084L;
private static Logger LOGGER = LoggerFactory.getLogger(ProxySubclassMethodHashSet.class);
public ProxySubclassMethodHashSet(int i)
{
super(i);
}
public void addMethodArray(java.lang.reflect.Method[] arrayOfEntries)
{
LOGGER.debug(Constants.LOG_ENTRY, "addMethodArray", new Object[] { arrayOfEntries });
for (java.lang.reflect.Method entry : arrayOfEntries) {
String methodName = entry.getName();
LOGGER.debug("Method name: {}", methodName);
Type[] methodArgTypes = Type.getArgumentTypes(entry);
String argDescriptor = typeArrayToStringArgDescriptor(methodArgTypes);
LOGGER.debug("Descriptor: {}", argDescriptor);
boolean added = super.add(methodName + argDescriptor);
LOGGER.debug("Added: {}", added);
}
LOGGER.debug(Constants.LOG_EXIT, "addMethodArray");
}
static String typeArrayToStringArgDescriptor(Type[] argTypes)
{
StringBuilder descriptor = new StringBuilder();
for (Type t : argTypes) {
descriptor.append(t.toString());
}
return descriptor.toString();
}
}
| 7,836 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/ProxySubclassGenerator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.gen;
import static java.lang.reflect.Modifier.isFinal;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.UnableToProxyException;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.reflect.ReflectionFactory;
@SuppressWarnings("restriction")
public class ProxySubclassGenerator
{
private final static Logger LOGGER = LoggerFactory.getLogger(ProxySubclassGenerator.class);
// This map holds references to the names of classes created by this Class
// It is a weak map (so when a ClassLoader is garbage collected we remove
// the map of
// Class names to sub-Class names)
private static final Map<ClassLoader, ConcurrentMap<String, String>> proxyClassesByClassLoader;
private static final ClassLoader defaultClassLoader = new ClassLoader() {};
static {
// Ensure that this is a synchronized map as we may use it from multiple
// threads concurrently
//
proxyClassesByClassLoader = Collections
.synchronizedMap(new WeakHashMap<ClassLoader, ConcurrentMap<String, String>>());
}
private static final char FINAL_MODIFIER = '!';
private static final char UNABLE_TO_PROXY = '#';
public static Class<?> getProxySubclass(Class<?> aClass) throws UnableToProxyException
{
return getProxySubclass(aClass, aClass.getClassLoader());
}
public static Class<?> getProxySubclass(Class<?> aClass, ClassLoader loader) throws UnableToProxyException
{
LOGGER.debug(Constants.LOG_ENTRY, "getProxySubclass", new Object[] { aClass });
// in the special case where the loader is null we use a default classloader
// this is for subclassing java.* or javax.* packages, so that one will do
if (loader == null) loader = defaultClassLoader;
ConcurrentMap<String, String> proxyMap;
synchronized (loader) {
proxyMap = proxyClassesByClassLoader.get(loader);
if (proxyMap == null) {
proxyMap = new ConcurrentHashMap<String, String>();
proxyClassesByClassLoader.put(loader, proxyMap);
}
}
// check the map to see if we have already generated a subclass for this
// class
// if we have return the mapped class object
// if we haven't generate the subclass and return it
Class<?> classToReturn = null;
synchronized (aClass) {
String key = aClass.getName();
String className = proxyMap.get(key);
if (className != null) {
LOGGER.debug("Found proxy subclass with key {} and name {}.", key, className);
if (className.charAt(0) == FINAL_MODIFIER) {
String[] exceptionParts = className.substring(1).split(":");
if (exceptionParts.length == 1) {
throw new FinalModifierException(aClass);
} else {
throw new FinalModifierException(aClass, exceptionParts[1]);
}
} else if (className.charAt(0) == UNABLE_TO_PROXY) {
throw new UnableToProxyException(aClass);
}
try {
classToReturn = loader.loadClass(className);
} catch (ClassNotFoundException cnfe) {
LOGGER.debug(Constants.LOG_EXCEPTION, cnfe);
throw new UnableToLoadProxyException(className, cnfe);
}
} else {
LOGGER.debug("Need to generate subclass. Using key {}.", key);
try {
scanForFinalModifiers(aClass);
classToReturn = generateAndLoadSubclass(aClass, loader);
if (classToReturn != null) {
proxyMap.put(key, classToReturn.getName());
} else {
proxyMap.put(key, UNABLE_TO_PROXY + aClass.getName());
throw new UnableToProxyException(aClass);
}
} catch (FinalModifierException e) {
if (e.isFinalClass()) {
proxyMap.put(key, FINAL_MODIFIER + e.getClassName());
throw e;
} else {
proxyMap.put(key, FINAL_MODIFIER + e.getClassName() + ':' + e.getFinalMethods());
throw e;
}
}
}
}
LOGGER.debug(Constants.LOG_EXIT, "getProxySubclass", classToReturn);
return classToReturn;
}
public static Object newProxySubclassInstance(Class<?> classToProxy, InvocationHandler ih)
throws UnableToProxyException
{
return newProxySubclassInstance(classToProxy, classToProxy.getClassLoader(), ih);
}
public static Object newProxySubclassInstance(Class<?> classToProxy, ClassLoader loader, InvocationHandler ih)
throws UnableToProxyException
{
LOGGER.debug(Constants.LOG_ENTRY, "newProxySubclassInstance", new Object[] {
classToProxy, loader, ih });
Object proxySubclassInstance = null;
try {
Class<?> generatedProxySubclass = getProxySubclass(classToProxy, loader);
LOGGER.debug("Getting the proxy subclass constructor");
// Because the newer JVMs throw a VerifyError if a class attempts to in a constructor other than their superclasses constructor,
// and because we can't know what objects/values we need to pass into the class being proxied constructor,
// we instantiate the proxy class using the ReflectionFactory.newConstructorForSerialization() method which allows us to instantiate the
// proxy class without calling the proxy class' constructor. It is in fact using the java.lang.Object constructor so is in effect
// doing what we were doing before.
ReflectionFactory factory = ReflectionFactory.getReflectionFactory();
Constructor<?> constr = Object.class.getConstructor();
Constructor<?> subclassConstructor = factory.newConstructorForSerialization(generatedProxySubclass, constr);
proxySubclassInstance = subclassConstructor.newInstance();
Method setIHMethod = proxySubclassInstance.getClass().getMethod("setInvocationHandler", InvocationHandler.class);
setIHMethod.invoke(proxySubclassInstance, ih);
LOGGER.debug("Invoked proxy subclass constructor");
} catch (NoSuchMethodException nsme) {
LOGGER.debug(Constants.LOG_EXCEPTION, nsme);
throw new ProxyClassInstantiationException(classToProxy, nsme);
} catch (InvocationTargetException ite) {
LOGGER.debug(Constants.LOG_EXCEPTION, ite);
throw new ProxyClassInstantiationException(classToProxy, ite);
} catch (InstantiationException ie) {
LOGGER.debug(Constants.LOG_EXCEPTION, ie);
throw new ProxyClassInstantiationException(classToProxy, ie);
} catch (IllegalAccessException iae) {
LOGGER.debug(Constants.LOG_EXCEPTION, iae);
throw new ProxyClassInstantiationException(classToProxy, iae);
} catch (VerifyError ve) {
LOGGER.info(String.format("The no-argument constructor of class %s is private and therefore it may not be possible to generate a valid proxy.",
classToProxy));
LOGGER.debug(Constants.LOG_EXCEPTION, ve);
throw new ProxyClassInstantiationException(classToProxy, ve);
}
LOGGER.debug(Constants.LOG_EXIT, "newProxySubclassInstance", proxySubclassInstance);
return proxySubclassInstance;
}
private static Class<?> generateAndLoadSubclass(Class<?> aClass, ClassLoader loader)
throws UnableToProxyException
{
LOGGER.debug(Constants.LOG_ENTRY, "generateAndLoadSubclass", new Object[] { aClass,
loader });
// set the newClassName
String newClassName = "$" + aClass.getSimpleName() + aClass.hashCode();
String packageName = aClass.getPackage().getName();
if (packageName.startsWith("java.") || packageName.startsWith("javax.")) {
packageName = "org.apache.aries.blueprint.proxy." + packageName;
}
String fullNewClassName = (packageName + "." + newClassName).replaceAll("\\.", "/");
LOGGER.debug("New class name: {}", newClassName);
LOGGER.debug("Full new class name: {}", fullNewClassName);
Class<?> clazz = null;
try {
ClassReader cReader = new ClassReader(loader.getResourceAsStream(aClass.getName().replaceAll(
"\\.", "/")
+ ".class"));
ClassWriter cWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassVisitor dynamicSubclassAdapter = new ProxySubclassAdapter(cWriter, fullNewClassName,
loader);
byte[] byteClassData = processClass(cReader, cWriter, dynamicSubclassAdapter);
clazz = loadClassFromBytes(loader, getBinaryName(fullNewClassName), byteClassData, aClass
.getName());
} catch (IOException ioe) {
LOGGER.debug(Constants.LOG_EXCEPTION, ioe);
throw new ProxyClassBytecodeGenerationException(aClass.getName(), ioe);
} catch (TypeNotPresentException tnpe) {
LOGGER.debug(Constants.LOG_EXCEPTION, tnpe);
throw new ProxyClassBytecodeGenerationException(tnpe.typeName(), tnpe.getCause());
}
LOGGER.debug(Constants.LOG_EXIT, "generateAndLoadSubclass", clazz);
return clazz;
}
private static byte[] processClass(ClassReader cReader, ClassWriter cWriter, ClassVisitor cVisitor)
{
LOGGER.debug(Constants.LOG_ENTRY, "processClass", new Object[] { cReader, cWriter,
cVisitor });
cReader.accept(cVisitor, ClassReader.SKIP_DEBUG);
byte[] byteClassData = cWriter.toByteArray();
LOGGER.debug(Constants.LOG_EXIT, "processClass", byteClassData);
return byteClassData;
}
private static String getBinaryName(String name)
{
LOGGER.debug(Constants.LOG_ENTRY, "getBinaryName", name);
String binaryName = name.replaceAll("/", "\\.");
LOGGER.debug(Constants.LOG_EXIT, "getBinaryName", binaryName);
return binaryName;
}
private static Class<?> loadClassFromBytes(ClassLoader loader, String name, byte[] classData,
String classToProxyName) throws UnableToProxyException
{
LOGGER.debug(Constants.LOG_ENTRY, "loadClassFromBytes", new Object[] { loader, name,
classData });
Class<?> clazz = null;
try {
Method defineClassMethod = Class.forName("java.lang.ClassLoader").getDeclaredMethod(
"defineClass", String.class, byte[].class, int.class, int.class, ProtectionDomain.class);
defineClassMethod.setAccessible(true);
// define the class in the same classloader where aClass is loaded,
// but use the protection domain of our code
clazz = (Class<?>) defineClassMethod.invoke(loader, name, classData, 0, classData.length,
ProxySubclassGenerator.class.getProtectionDomain());
defineClassMethod.setAccessible(false);
} catch (ClassNotFoundException cnfe) {
LOGGER.debug(Constants.LOG_EXCEPTION, cnfe);
throw new ProxyClassDefinitionException(classToProxyName, cnfe);
} catch (NoSuchMethodException nsme) {
LOGGER.debug(Constants.LOG_EXCEPTION, nsme);
throw new ProxyClassDefinitionException(classToProxyName, nsme);
} catch (InvocationTargetException ite) {
LOGGER.debug(Constants.LOG_EXCEPTION, ite);
throw new ProxyClassDefinitionException(classToProxyName, ite);
} catch (IllegalAccessException iae) {
LOGGER.debug(Constants.LOG_EXCEPTION, iae);
throw new ProxyClassDefinitionException(classToProxyName, iae);
}
LOGGER.debug(Constants.LOG_EXIT, "loadClassFromBytes", clazz);
return clazz;
}
public static boolean isProxySubclass(Class<?> aClass)
{
LOGGER.debug(Constants.LOG_ENTRY, "isProxySubclass", new Object[] { aClass });
// We will always have a proxy map for the class loader of any proxy
// class, so if
// this is null we know to return false
Map<String, String> proxies = proxyClassesByClassLoader.get(aClass.getClassLoader());
boolean isProxySubclass = (proxies != null && proxies.containsValue(aClass.getName()));
LOGGER.debug(Constants.LOG_EXIT, "isProxySubclass", isProxySubclass);
return isProxySubclass;
}
private static void scanForFinalModifiers(Class<?> clazz) throws FinalModifierException
{
LOGGER.debug(Constants.LOG_ENTRY, "scanForFinalModifiers", new Object[] { clazz });
if (isFinal(clazz.getModifiers())) {
throw new FinalModifierException(clazz);
}
List<String> finalMethods = new ArrayList<String>();
// we don't want to check for final methods on java.* or javax.* Class
// also, clazz can never be null here (we will always hit
// java.lang.Object first)
while (!clazz.getName().startsWith("java.") && !clazz.getName().startsWith("javax.")) {
for (Method m : clazz.getDeclaredMethods()) {
//Static finals are ok, because we won't be overriding them :)
if (isFinal(m.getModifiers()) && !Modifier.isStatic(m.getModifiers())) {
finalMethods.add(m.toGenericString());
}
}
clazz = clazz.getSuperclass();
}
if (!finalMethods.isEmpty()) {
String methodList = finalMethods.toString();
methodList = methodList.substring(1, methodList.length() - 1);
throw new FinalModifierException(clazz, methodList);
}
LOGGER.debug(Constants.LOG_EXIT, "scanForFinalModifiers");
}
public static InvocationHandler getInvocationHandler(Object o)
{
LOGGER.debug(Constants.LOG_ENTRY, "getInvoationHandler", new Object[] { o });
InvocationHandler ih = null;
if (isProxySubclass(o.getClass())) {
// we have to catch exceptions here, but we just log them
// the reason for this is that it should be impossible to get these
// exceptions
// since the Object we are dealing with is a class we generated on
// the fly
try {
ih = (InvocationHandler) o.getClass().getDeclaredMethod("getInvocationHandler",
new Class[] {}).invoke(o, new Object[] {});
} catch (IllegalArgumentException e) {
LOGGER.debug(Constants.LOG_EXCEPTION, e);
} catch (SecurityException e) {
LOGGER.debug(Constants.LOG_EXCEPTION, e);
} catch (IllegalAccessException e) {
LOGGER.debug(Constants.LOG_EXCEPTION, e);
} catch (InvocationTargetException e) {
LOGGER.debug(Constants.LOG_EXCEPTION, e);
} catch (NoSuchMethodException e) {
LOGGER.debug(Constants.LOG_EXCEPTION, e);
}
}
LOGGER.debug(Constants.LOG_EXIT, "getInvoationHandler", ih);
return ih;
}
}
| 7,837 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/ProxyClassInstantiationException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.gen;
import org.apache.aries.proxy.UnableToProxyException;
public class ProxyClassInstantiationException extends UnableToProxyException
{
/**
*
*/
private static final long serialVersionUID = -2303296601108980838L;
public ProxyClassInstantiationException(Class<?> clazz, Throwable e)
{
super(clazz, e);
}
}
| 7,838 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/ProxyClassDefinitionException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.gen;
import org.apache.aries.proxy.UnableToProxyException;
public class ProxyClassDefinitionException extends UnableToProxyException
{
/**
*
*/
private static final long serialVersionUID = 604215734831044743L;
public ProxyClassDefinitionException(String className, Exception e)
{
super(className, e);
}
}
| 7,839 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/ProxyClassBytecodeGenerationException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.gen;
import org.apache.aries.proxy.UnableToProxyException;
public class ProxyClassBytecodeGenerationException extends UnableToProxyException
{
/**
*
*/
private static final long serialVersionUID = -8015178382210046784L;
public ProxyClassBytecodeGenerationException(String string, Throwable throwable)
{
super(string, throwable);
}
}
| 7,840 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/ProxySubclassAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.gen;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import org.apache.aries.proxy.impl.ProxyUtils;
import org.apache.aries.proxy.impl.SystemModuleClassLoader;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProxySubclassAdapter extends ClassVisitor implements Opcodes
{
private static final Type STRING_TYPE = Type.getType(String.class);
private static final Type CLASS_TYPE = Type.getType(Class.class);
private static final Type CLASSLOADER_TYPE = Type.getType(ClassLoader.class);
private static final Type OBJECT_TYPE = Type.getType(Object.class);
private static final Type METHOD_TYPE = Type.getType(java.lang.reflect.Method.class);
private static final Type IH_TYPE = Type.getType(InvocationHandler.class);
private static final Type[] NO_ARGS = new Type[] {};
private static final String IH_FIELD = "ih";
private static Logger LOGGER = LoggerFactory.getLogger(ProxySubclassAdapter.class);
private String newClassName = null;
private String superclassBinaryName = null;
private Class<?> superclassClass = null;
private ClassLoader loader = null;
private Type newClassType = null;
private GeneratorAdapter staticAdapter = null;
private String currentlyAnalysedClassName = null;
private Class<?> currentlyAnalysedClass = null;
private String currentClassFieldName = null;
public ProxySubclassAdapter(ClassVisitor writer, String newClassName, ClassLoader loader)
{
// call the superclass constructor
super(Opcodes.ASM9, writer);
// the writer is now the cv in the superclass of ClassAdapter
LOGGER.debug(Constants.LOG_ENTRY, "ProxySubclassAdapter", new Object[] { this, writer,
newClassName });
// set the newClassName field
this.newClassName = newClassName;
// set the newClassType descriptor
newClassType = Type.getType("L" + newClassName + ";");
// set the classloader
this.loader = loader;
LOGGER.debug(Constants.LOG_EXIT, "ProxySubclassAdapter", this);
}
/*
* This method visits the class to generate the new subclass.
*
* The following things happen here: 1. The class is renamed to a dynamic
* name 2. The existing class name is changed to be the superclass name so
* that the generated class extends the original class. 3. A private field
* is added to store an invocation handler 4. A constructor is added that
* takes an invocation handler as an argument 5. The constructor method
* instantiates an instance of the superclass 6. The constructor method sets
* the invocation handler so the invoke method can be called from all the
* subsequently rewritten methods 7. Add a getInvocationHandler() method 8.
* store a static Class object of the superclass so we can reflectively find
* methods later
*/
public void visit(int version, int access, String name, String signature, String superName,
String[] interfaces)
{
LOGGER.debug(Constants.LOG_ENTRY, "visit", new Object[] { version, access, name,
signature, superName, interfaces });
// store the superclass binary name
this.superclassBinaryName = name.replaceAll("/", "\\.");
try {
this.superclassClass = Class.forName(superclassBinaryName, false, loader);
} catch (ClassNotFoundException cnfe) {
throw new TypeNotPresentException(superclassBinaryName, cnfe);
}
// keep the same access and signature as the superclass (unless it's abstract)
// remove all the superclass interfaces because they will be inherited
// from the superclass anyway
if((access & ACC_ABSTRACT) != 0) {
//If the super was abstract the subclass should not be!
access &= ~ACC_ABSTRACT;
}
cv.visit(ProxyUtils.getWeavingJavaVersion(), access, newClassName, signature, name, null);
// add a private field for the invocation handler
// this isn't static in case we have multiple instances of the same
// proxy
cv.visitField(ACC_PRIVATE, IH_FIELD, Type.getDescriptor(InvocationHandler.class), null, null);
// create a static adapter for generating a static initialiser method in
// the generated subclass
staticAdapter = new GeneratorAdapter(ACC_STATIC,
new Method("<clinit>", Type.VOID_TYPE, NO_ARGS), null, null, cv);
// add a zero args constructor method
Method m = new Method("<init>", Type.VOID_TYPE, NO_ARGS);
GeneratorAdapter methodAdapter = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cv);
// loadthis
methodAdapter.loadThis();
// List the constructors in the superclass.
Constructor<?>[] constructors = superclassClass.getDeclaredConstructors();
// Check that we've got at least one constructor, and get the 1st one in the list.
if (constructors.length > 0) {
// We now need to construct the proxy class as though it is going to invoke the superclasses constructor.
// We do this because we can no longer call the java.lang.Object() zero arg constructor as the JVM now throws a VerifyError.
// So what we do is build up the calling of the superclasses constructor using nulls and default values. This means that the
// class bytes can be verified by the JVM, and then in the ProxySubclassGenerator, we load the class without invoking the
// constructor.
Method constructor = Method.getMethod(constructors[0]);
Type[] argTypes = constructor.getArgumentTypes();
if (argTypes.length == 0) {
methodAdapter.invokeConstructor(Type.getType(superclassClass), new Method("<init>", Type.VOID_TYPE, NO_ARGS));
} else {
for (Type type : argTypes) {
switch (type.getSort())
{
case Type.ARRAY:
// We need to process any array or multidimentional arrays.
String elementDesc = type.getElementType().getDescriptor();
String typeDesc = type.getDescriptor();
// Iterate over the number of arrays and load 0 for each one. Keep a count of the number of
// arrays as we will need to run different code fo multi dimentional arrays.
int index = 0;
while (! elementDesc.equals(typeDesc)) {
typeDesc = typeDesc.substring(1);
methodAdapter.visitInsn(Opcodes.ICONST_0);
index++;
}
// If we're just a single array, then call the newArray method, otherwise use the MultiANewArray instruction.
if (index == 1) {
methodAdapter.newArray(type.getElementType());
} else {
methodAdapter.visitMultiANewArrayInsn(type.getDescriptor(), index);
}
break;
case Type.BOOLEAN:
methodAdapter.push(true);
break;
case Type.BYTE:
methodAdapter.push(Type.VOID_TYPE);
break;
case Type.CHAR:
methodAdapter.push(Type.VOID_TYPE);
break;
case Type.DOUBLE:
methodAdapter.push(0.0);
break;
case Type.FLOAT:
methodAdapter.push(0.0f);
break;
case Type.INT:
methodAdapter.push(0);
break;
case Type.LONG:
methodAdapter.push(0l);
break;
case Type.SHORT:
methodAdapter.push(0);
break;
default:
case Type.OBJECT:
methodAdapter.visitInsn(Opcodes.ACONST_NULL);
break;
}
}
methodAdapter.invokeConstructor(Type.getType(superclassClass), new Method("<init>", Type.VOID_TYPE, argTypes));
}
}
methodAdapter.returnValue();
methodAdapter.endMethod();
// add a method for getting the invocation handler
Method setter = new Method("setInvocationHandler", Type.VOID_TYPE, new Type[] { IH_TYPE });
m = new Method("getInvocationHandler", IH_TYPE, NO_ARGS);
methodAdapter = new GeneratorAdapter(ACC_PUBLIC | ACC_FINAL, m, null, null, cv);
// load this to get the field
methodAdapter.loadThis();
// get the ih field and return
methodAdapter.getField(newClassType, IH_FIELD, IH_TYPE);
methodAdapter.returnValue();
methodAdapter.endMethod();
// add a method for setting the invocation handler
methodAdapter = new GeneratorAdapter(ACC_PUBLIC | ACC_FINAL, setter, null, null, cv);
// load this to put the field
methodAdapter.loadThis();
// load the method arguments (i.e. the invocation handler) to the stack
methodAdapter.loadArgs();
// set the ih field using the method argument
methodAdapter.putField(newClassType, IH_FIELD, IH_TYPE);
methodAdapter.returnValue();
methodAdapter.endMethod();
// loop through the class hierarchy to get any needed methods off the
// supertypes
// start by finding the methods declared on the class of interest (the
// superclass of our dynamic subclass)
java.lang.reflect.Method[] observedMethods = superclassClass.getDeclaredMethods();
// add the methods to a set of observedMethods
ProxySubclassMethodHashSet<String> setOfObservedMethods = new ProxySubclassMethodHashSet<String>(
observedMethods.length);
setOfObservedMethods.addMethodArray(observedMethods);
// get the next superclass in the hierarchy
Class<?> nextSuperClass = superclassClass.getSuperclass();
while (nextSuperClass != null) {
// set the fields for the current class
setCurrentAnalysisClassFields(nextSuperClass);
// add a static field and static initializer code to the generated
// subclass
// for each of the superclasses in the hierarchy
addClassStaticField(currentlyAnalysedClassName);
LOGGER.debug("Class currently being analysed: {} {}", currentlyAnalysedClassName,
currentlyAnalysedClass);
// now find the methods declared on the current class and add them
// to a set of foundMethods
java.lang.reflect.Method[] foundMethods = currentlyAnalysedClass.getDeclaredMethods();
ProxySubclassMethodHashSet<String> setOfFoundMethods = new ProxySubclassMethodHashSet<String>(
foundMethods.length);
setOfFoundMethods.addMethodArray(foundMethods);
// remove from the set of foundMethods any methods we saw on a
// subclass
// because we want to use the lowest level declaration of a method
setOfFoundMethods.removeAll(setOfObservedMethods);
try {
// read the current class and use a
// ProxySubclassHierarchyAdapter
// to process only methods on that class that are in the list
ClassLoader loader = currentlyAnalysedClass.getClassLoader();
if (loader == null) {
loader = this.loader;
}
InputStream is = loader.getResourceAsStream(currentlyAnalysedClass
.getName().replaceAll("\\.", "/")
+ ".class");
if (is == null) {
//use SystemModuleClassLoader as fallback
ClassLoader classLoader = new SystemModuleClassLoader();
is = classLoader.getResourceAsStream(currentlyAnalysedClass
.getName().replaceAll("\\.", "/")
+ ".class");
}
ClassReader cr = new ClassReader(is);
ClassVisitor hierarchyAdapter = new ProxySubclassHierarchyAdapter(this, setOfFoundMethods);
cr.accept(hierarchyAdapter, ClassReader.SKIP_DEBUG);
} catch (IOException e) {
throw new TypeNotPresentException(currentlyAnalysedClassName, e);
}
// now add the foundMethods to the overall list of observed methods
setOfObservedMethods.addAll(setOfFoundMethods);
// get the next class up in the hierarchy and go again
nextSuperClass = currentlyAnalysedClass.getSuperclass();
}
// we've finished looking at the superclass hierarchy
// set the fields for the immediate superclass of our dynamic subclass
setCurrentAnalysisClassFields(superclassClass);
// add the class static field
addClassStaticField(currentlyAnalysedClassName);
// we do the lowest class last because we are already visiting the class
// when in this adapter code
// now we are ready to visit all the methods on the lowest class
// which will happen by the ASM ClassVisitor implemented in this adapter
LOGGER.debug(Constants.LOG_EXIT, "visit");
}
public void visitSource(String source, String debug)
{
LOGGER.debug(Constants.LOG_ENTRY, "visitSource", new Object[] { source, debug });
// set the source to null since the class is generated on the fly and
// not compiled
cv.visitSource(null, null);
LOGGER.debug(Constants.LOG_EXIT, "visitSource");
}
public void visitEnd()
{
LOGGER.debug(Constants.LOG_ENTRY, "visitEnd");
// this method is called when we reach the end of the class
// so it is time to make sure the static initialiser method is closed
staticAdapter.returnValue();
staticAdapter.endMethod();
// now delegate to the cv
cv.visitEnd();
LOGGER.debug(Constants.LOG_EXIT, "visitEnd");
}
/*
* This method is called on each method of the superclass (and all parent
* classes up to Object) Each of these methods is visited in turn and the
* code here generates the byte code for the InvocationHandler to call the
* methods on the superclass.
*/
public MethodVisitor visitMethod(int access, String name, String desc, String signature,
String[] exceptions)
{
LOGGER.debug(Constants.LOG_ENTRY, "visitMethod", new Object[] { access, name, desc,
signature, exceptions });
/*
* Check the method access and handle the method types we don't want to
* copy: final methods (issue warnings if these are not methods from
* java.* classes) static methods (initialiser and others) private
* methods, constructors (for now we don't copy any constructors)
* everything else we process to proxy. Abstract methods should be made
* non-abstract so that they can be proxied.
*/
if((access & ACC_ABSTRACT) != 0) {
//If the method is abstract then it should not be in the concrete subclass!
access &= ~ACC_ABSTRACT;
}
LOGGER.debug("Method name: {} with descriptor: {}", name, desc);
MethodVisitor methodVisitorToReturn = null;
if (name.equals("<init>")) {
// we may need to do something extra with constructors later
// e.g. include bytecode for calling super with the same args
// since we currently rely on the super having a zero args
// constructor
// we need to issue an error if we don't find one
// for now we return null to ignore them
methodVisitorToReturn = null;
} else if (name.equals("<clinit>")) {
// don't copy static initialisers from the superclass into the new
// subclass
methodVisitorToReturn = null;
} else if ((access & ACC_FINAL) != 0) {
// since we check for final methods in the ProxySubclassGenerator we
// should never get here
methodVisitorToReturn = null;
} else if ((access & ACC_SYNTHETIC) != 0) {
// synthetic methods are generated by the compiler for covariance
// etc
// we shouldn't copy them or we will have duplicate methods
methodVisitorToReturn = null;
} else if ((access & ACC_PRIVATE) != 0) {
// don't copy private methods from the superclass
methodVisitorToReturn = null;
} else if ((access & ACC_STATIC) != 0) {
// don't copy static methods
methodVisitorToReturn = null;
} else if (!(((access & ACC_PUBLIC) != 0) || ((access & ACC_PROTECTED) != 0) || ((access & ACC_PRIVATE) != 0))) {
// the default (package) modifier value is 0, so by using & with any
// of the other
// modifier values and getting a result of zero means that we have
// default accessibility
// check the package in which the method is declared against the
// package
// where the generated subclass will be
// if they are the same process the method otherwise ignore it
if (currentlyAnalysedClass.getPackage().equals(superclassClass.getPackage())) {
processMethod(access, name, desc, signature, exceptions);
methodVisitorToReturn = null;
} else {
methodVisitorToReturn = null;
}
} else {
processMethod(access, name, desc, signature, exceptions);
// return null because we don't want the original method code from
// the superclass
methodVisitorToReturn = null;
}
LOGGER.debug(Constants.LOG_EXIT, "visitMethod", methodVisitorToReturn);
return methodVisitorToReturn;
}
private void processMethod(int access, String name, String desc, String signature,
String[] exceptions)
{
LOGGER.debug(Constants.LOG_ENTRY, "processMethod", new Object[] { access, name, desc,
signature, exceptions });
LOGGER.debug("Processing method: {} with descriptor {}", name, desc);
// identify the target method parameters and return type
Method currentTransformMethod = new Method(name, desc);
Type[] targetMethodParameters = currentTransformMethod.getArgumentTypes();
Type returnType = currentTransformMethod.getReturnType();
// we create a static field for each method we encounter with a name
// like method_parm1_parm2...
StringBuilder methodStaticFieldNameBuilder = new StringBuilder(name);
// for each a parameter get the name and add it to the field removing
// the dots first
for (Type t : targetMethodParameters) {
methodStaticFieldNameBuilder.append("_");
methodStaticFieldNameBuilder.append(t.getClassName().replaceAll("\\[\\]", "Array")
.replaceAll("\\.", ""));
}
String methodStaticFieldName = methodStaticFieldNameBuilder.toString();
// add a private static field for the method
cv.visitField(ACC_PRIVATE | ACC_STATIC, methodStaticFieldName, METHOD_TYPE.getDescriptor(),
null, null);
// visit the method using the class writer, delegated through the method
// visitor and generator
// modify the method access so that any native methods aren't
// described as native
// since they won't be native in proxy form
// also stop methods being marked synchronized on the proxy as they will
// be sync
// on the real object
int newAccess = access & (~ACC_NATIVE) & (~ACC_SYNCHRONIZED);
MethodVisitor mv = cv.visitMethod(newAccess, name, desc, signature, exceptions);
// use a GeneratorAdapter to build the invoke call directly in byte code
GeneratorAdapter methodAdapter = new GeneratorAdapter(mv, newAccess, name, desc);
/*
* Stage 1 creates the bytecode for adding the reflected method of the
* superclass to a static field in the subclass: private static Method
* methodName_parm1_parm2... = null; static{ methodName_parm1_parm2... =
* superClass.getDeclaredMethod(methodName,new Class[]{method args}; }
*
* Stage 2 is to call the ih.invoke(this,methodName_parm1_parm2,args) in
* the new subclass methods Stage 3 is to cast the return value to the
* correct type
*/
/*
* Stage 1 use superClass.getMethod(methodName,new Class[]{method args}
* from the Class object on the stack
*/
// load the static superclass Class onto the stack
staticAdapter.getStatic(newClassType, currentClassFieldName, CLASS_TYPE);
// push the method name string arg onto the stack
staticAdapter.push(name);
// create an array of the method parm class[] arg
staticAdapter.push(targetMethodParameters.length);
staticAdapter.newArray(CLASS_TYPE);
int index = 0;
for (Type t : targetMethodParameters) {
staticAdapter.dup();
staticAdapter.push(index);
switch (t.getSort())
{
case Type.BOOLEAN:
staticAdapter.getStatic(Type.getType(java.lang.Boolean.class), "TYPE", CLASS_TYPE);
break;
case Type.BYTE:
staticAdapter.getStatic(Type.getType(java.lang.Byte.class), "TYPE", CLASS_TYPE);
break;
case Type.CHAR:
staticAdapter.getStatic(Type.getType(java.lang.Character.class), "TYPE", CLASS_TYPE);
break;
case Type.DOUBLE:
staticAdapter.getStatic(Type.getType(java.lang.Double.class), "TYPE", CLASS_TYPE);
break;
case Type.FLOAT:
staticAdapter.getStatic(Type.getType(java.lang.Float.class), "TYPE", CLASS_TYPE);
break;
case Type.INT:
staticAdapter.getStatic(Type.getType(java.lang.Integer.class), "TYPE", CLASS_TYPE);
break;
case Type.LONG:
staticAdapter.getStatic(Type.getType(java.lang.Long.class), "TYPE", CLASS_TYPE);
break;
case Type.SHORT:
staticAdapter.getStatic(Type.getType(java.lang.Short.class), "TYPE", CLASS_TYPE);
break;
default:
case Type.OBJECT:
staticAdapter.push(t);
break;
}
staticAdapter.arrayStore(CLASS_TYPE);
index++;
}
// invoke the getMethod
staticAdapter.invokeVirtual(CLASS_TYPE, new Method("getDeclaredMethod", METHOD_TYPE,
new Type[] { STRING_TYPE, Type.getType(java.lang.Class[].class) }));
// store the reflected method in the static field
staticAdapter.putStatic(newClassType, methodStaticFieldName, METHOD_TYPE);
/*
* Stage 2 call the ih.invoke(this,supermethod,parms)
*/
// load this to get the ih field
methodAdapter.loadThis();
// load the invocation handler from the field (the location of the
// InvocationHandler.invoke)
methodAdapter.getField(newClassType, IH_FIELD, IH_TYPE);
// loadThis (the first arg of the InvocationHandler.invoke)
methodAdapter.loadThis();
// load the method to invoke (the second arg of the
// InvocationHandler.invoke)
methodAdapter.getStatic(newClassType, methodStaticFieldName, METHOD_TYPE);
// load all the method arguments onto the stack as an object array (the
// third arg of the InvocationHandler.invoke)
methodAdapter.loadArgArray();
// generate the invoke method
Method invocationHandlerInvokeMethod = new Method("invoke", OBJECT_TYPE, new Type[] {
OBJECT_TYPE, METHOD_TYPE, Type.getType(java.lang.Object[].class) });
// call the invoke method of the invocation handler
methodAdapter.invokeInterface(IH_TYPE, invocationHandlerInvokeMethod);
/*
* Stage 3 the returned object is now on the top of the stack We need to
* check the type and cast as necessary
*/
switch (returnType.getSort())
{
case Type.BOOLEAN:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Boolean.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.BOOLEAN_TYPE);
break;
case Type.BYTE:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Byte.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.BYTE_TYPE);
break;
case Type.CHAR:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Character.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.CHAR_TYPE);
break;
case Type.DOUBLE:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Double.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.DOUBLE_TYPE);
break;
case Type.FLOAT:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Float.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.FLOAT_TYPE);
break;
case Type.INT:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Integer.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.INT_TYPE);
break;
case Type.LONG:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Long.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.LONG_TYPE);
break;
case Type.SHORT:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Short.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.SHORT_TYPE);
break;
case Type.VOID:
try {
methodAdapter.cast(OBJECT_TYPE, Type.getType(Void.class));
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
methodAdapter.unbox(Type.VOID_TYPE);
break;
default:
case Type.OBJECT:
// in this case check the cast and cast the object to the return
// type
methodAdapter.checkCast(returnType);
try {
methodAdapter.cast(OBJECT_TYPE, returnType);
} catch (IllegalArgumentException ex) {
LOGGER.debug("Ignore cast exception caused by ASM 6.1 and try further", ex);
}
break;
}
// return the (appropriately cast) result of the invocation from the
// stack
methodAdapter.returnValue();
// end the method
methodAdapter.endMethod();
LOGGER.debug(Constants.LOG_EXIT, "processMethod");
}
private void addClassStaticField(String classBinaryName)
{
LOGGER.debug(Constants.LOG_ENTRY, "addClassStaticField",
new Object[] { classBinaryName });
currentClassFieldName = classBinaryName.replaceAll("\\.", "_");
/*
* use Class.forName on the superclass so we can reflectively find
* methods later
*
* produces bytecode for retrieving the superclass and storing in a
* private static field: private static Class superClass = null; static{
* superClass = Class.forName(superclass, true, TYPE_BEING_PROXIED.class.getClassLoader()); }
*/
// add a private static field for the superclass Class
cv.visitField(ACC_PRIVATE | ACC_STATIC, currentClassFieldName, CLASS_TYPE.getDescriptor(),
null, null);
// push the String arg for the Class.forName onto the stack
staticAdapter.push(classBinaryName);
//push the boolean arg for the Class.forName onto the stack
staticAdapter.push(true);
//get the classloader
staticAdapter.push(newClassType);
staticAdapter.invokeVirtual(CLASS_TYPE, new Method("getClassLoader", CLASSLOADER_TYPE, NO_ARGS));
// invoke the Class forName putting the Class on the stack
staticAdapter.invokeStatic(CLASS_TYPE, new Method("forName", CLASS_TYPE,
new Type[] { STRING_TYPE, Type.BOOLEAN_TYPE, CLASSLOADER_TYPE }));
// put the Class in the static field
staticAdapter.putStatic(newClassType, currentClassFieldName, CLASS_TYPE);
LOGGER.debug(Constants.LOG_ENTRY, "addClassStaticField");
}
private void setCurrentAnalysisClassFields(Class<?> aClass)
{
LOGGER.debug(Constants.LOG_ENTRY, "setCurrentAnalysisClassFields",
new Object[] { aClass });
currentlyAnalysedClassName = aClass.getName();
currentlyAnalysedClass = aClass;
LOGGER.debug(Constants.LOG_EXIT, "setCurrentAnalysisClassFields");
}
// we don't want to copy fields from the class into the proxy
public FieldVisitor visitField(int access, String name, String desc, String signature,
Object value)
{
return null;
}
// for now we don't do any processing in these methods
public AnnotationVisitor visitAnnotation(String desc, boolean visible)
{
return null;
}
public void visitAttribute(Attribute attr)
{
// no-op
}
public void visitInnerClass(String name, String outerName, String innerName, int access)
{
// no-op
}
public void visitOuterClass(String owner, String name, String desc)
{
// no-op
}
}
| 7,841 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/gen/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.proxy.impl.gen;
public interface Constants
{
final static String LOG_ENTRY = "Method entry: {}, args {}";
final static String LOG_EXIT = "Method exit: {}, returning {}";
final static String LOG_EXCEPTION = "Caught exception";
}
| 7,842 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/WovenProxyAbstractMethodAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.OBJECT_TYPE;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
/**
* Used to create a delegating method implementation for methods with no body
*/
public final class WovenProxyAbstractMethodAdapter extends AbstractWovenProxyMethodAdapter {
public WovenProxyAbstractMethodAdapter(MethodVisitor mv, int access, String name,
String desc, String methodStaticFieldName, Method currentTransformMethod,
Type typeBeingWoven, Type methodDeclaringType, boolean isMethodDeclaringTypeInterface, boolean isDefaultMethod) {
super(mv, access, name, desc, methodStaticFieldName, currentTransformMethod,
typeBeingWoven, methodDeclaringType, isMethodDeclaringTypeInterface, isDefaultMethod);
}
/**
* We write dispatch code here because we have no real method body
*/
@Override
public final void visitCode()
{
//Notify our parent that the method code is starting. This must happen first
mv.visitCode();
//unwrap for equals if we need to
if(currentTransformMethod.getName().equals("equals") &&
currentTransformMethod.getArgumentTypes().length == 1 &&
currentTransformMethod.getArgumentTypes()[0].equals(OBJECT_TYPE)) {
unwrapEqualsArgument();
}
//No null-check needed
//Write the dispatcher code in here
writeDispatcher();
}
@Override
public final void visitMaxs(int stack, int locals) {
mv.visitMaxs(stack, locals);
}
/**
* We don't get the code and maxs calls for interfaces, so we add them here
*/
@Override
public final void visitEnd() {
visitCode();
visitMaxs(0, 0);
mv.visitEnd();
}
}
| 7,843 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/AbstractWovenProxyAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import static java.lang.String.format;
import static org.apache.aries.proxy.impl.ProxyUtils.JAVA_CLASS_VERSION;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.SystemModuleClassLoader;
import org.apache.aries.proxy.impl.gen.Constants;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.AdviceAdapter;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This abstract superclass is responsible for providing proxy extensions to
* classes being written. Classes processed by this adapter will implement
* {@link WovenProxy}, and have a static initialiser that populates
* {@link java.lang.reflect.Method} fields for use with the
* {@link InvocationListener}. Known subclasses are WovenProxyAdapter,
* used to weave classes being loaded by the framework, and InterfaceCombiningClassAdapter
* which is used to dynamically create objects that implement multiple interfaces
*/
public abstract class AbstractWovenProxyAdapter extends ClassVisitor implements Opcodes {
private static final Logger LOGGER = LoggerFactory
.getLogger(AbstractWovenProxyAdapter.class);
/** Access modifier for a public generated method */
private static final int PUBLIC_GENERATED_METHOD_ACCESS = ACC_PUBLIC | ACC_FINAL
| ACC_SYNTHETIC;
/** The internal name for Throwable */
static final String THROWABLE_INAME = Type.getInternalName(Throwable.class);
/**
* A static UUID for adding to our method names.
* This must not change over time, otherwise uninstalling
* and reinstalling the proxy component with a separate
* API bundle will cause BIG trouble (NoSuchFieldError)
* with subclasses that get woven by the "new" hook
*/
private static final String UU_ID = "04df3c80_2877_4f6c_99e2_5a25e11d5535";
/** A constant for No Args methods */
static final Type[] NO_ARGS = new Type[0];
/** The annotation types we should add to generated methods and fields */
private static final String[] annotationTypeDescriptors = new String[] { "Ljavax/persistence/Transient;" };
/** the name of the field used to store the {@link InvocationListener} */
protected static final String LISTENER_FIELD = "org_apache_aries_proxy_InvocationListener_"
+ UU_ID;
/** the name of the field used to store the dispatcher */
public static final String DISPATCHER_FIELD = "woven_proxy_dispatcher_" + UU_ID;
/* Useful ASM types */
/** The ASM type for the {@link InvocationListener} */
static final Type LISTENER_TYPE = Type.getType(InvocationListener.class);
/** The ASM type for the dispatcher */
public static final Type DISPATCHER_TYPE = Type.getType(Callable.class);
private static final Type CLASS_TYPE = Type.getType(Class.class);
private static final Type CLASS_ARRAY_TYPE = Type.getType(Class[].class);
private static final Type STRING_TYPE = Type.getType(String.class);
public static final Type OBJECT_TYPE = Type.getType(Object.class);
static final Type METHOD_TYPE = Type.getType(java.lang.reflect.Method.class);
/** The {@link Type} of the {@link WovenProxy} interface */
static final Type WOVEN_PROXY_IFACE_TYPE = Type.getType(WovenProxy.class);
private static final Type NPE_TYPE = Type.getType(NullPointerException.class);
private static final Type[] DISPATCHER_LISTENER_METHOD_ARGS = new Type[] {
DISPATCHER_TYPE, LISTENER_TYPE };
private static final Method ARGS_CONSTRUCTOR = new Method("<init>", Type.VOID_TYPE,
DISPATCHER_LISTENER_METHOD_ARGS);
private static final Method NO_ARGS_CONSTRUCTOR = new Method("<init>", Type.VOID_TYPE,
NO_ARGS);
private static final Method NPE_CONSTRUCTOR = new Method("<init>", Type.VOID_TYPE,
new Type[] {STRING_TYPE});
// other new methods we will need
static final Method getInovcationTargetMethod = new Method(
"getInvocationTarget" + UU_ID, OBJECT_TYPE, NO_ARGS);
static final Method listenerPreInvokeMethod = new Method("getListener"
+ UU_ID, OBJECT_TYPE, new Type[] { OBJECT_TYPE,
Type.getType(java.lang.reflect.Method.class),
Type.getType(Object[].class) });
/* Instance fields */
/** The type of this class */
protected final Type typeBeingWoven;
/** The type of this class's super */
private Type superType;
/** The {@link ClassLoader} loading this class */
private final ClassLoader loader;
/**
* A flag to indicate that we need to weave WovenProxy methods into this class
*/
private boolean implementWovenProxy = false;
/**
* A list of un-woven superclasses between this object and {@link Object},
* only populated for classes which will directly implement {@link WovenProxy}.
* This list is then used to override any methods that would otherwise be missed
* by the weaving process.
*/
protected final List<Class<?>> nonObjectSupers = new ArrayList<Class<?>>();
/**
* Methods we have transformed and need to create static fields for.
* Stored as field name to {@link TypeMethod} so we know which Class to reflect
* them off
*/
protected final Map<String, TypeMethod> transformedMethods = new HashMap<String, TypeMethod>();
/**
* A set of {@link Method} objects identifying the methods that are in this
* class. This is used to prevent us duplicating methods copied from
* {@link AbstractWovenProxyAdapter#nonObjectSupers} that are already overridden in
* this class.
*/
private final Set<Method> knownMethods = new HashSet<Method>();
/**
* If our super does not have a no-args constructor then we need to be clever
* when writing our own constructor.
*/
private boolean superHasNoArgsConstructor = false;
/**
* If we have a no-args constructor then we can delegate there rather than
* to a super no-args
*/
private boolean hasNoArgsConstructor = false;
/**
* If we have a no-args constructor then we can delegate there rather than
* to a super no-args
*/
protected boolean isSerializable = false;
/**
* The default static initialization method where we will write the proxy init
* code. If there is an existing <clinit> then we will change this and write a
* static_init_UUID instead (see the overriden
* {@link #visitMethod(int, String, String, String, String[])}
* for where this swap happens). See also {@link #writeStaticInitMethod()} for
* where the method is actually written.
*/
private Method staticInitMethod = new Method("<clinit>", Type.VOID_TYPE, NO_ARGS);
/**
* The default access flags for the staticInitMethod. If we find an existing
* <clinit> then we will write a static_init_UUID method and add the ACC_PRIVATE_FLAG.
* See the overriden {@link #visitMethod(int, String, String, String, String[])}
* for where this flag is added. See also {@link #writeStaticInitMethod()} for
* where the method is actually written.
*/
private int staticInitMethodFlags = ACC_SYNTHETIC | ACC_PRIVATE | ACC_STATIC;
protected Type currentMethodDeclaringType;
protected boolean currentMethodDeclaringTypeIsInterface;
public static final boolean IS_AT_LEAST_JAVA_6 = JAVA_CLASS_VERSION >= Opcodes.V1_6;
/**
* Create a new adapter for the supplied class
*
* @param writer
* The ClassWriter to delegate to
* @param className
* The name of this class
* @param loader
* The ClassLoader loading this class
*/
public AbstractWovenProxyAdapter(ClassVisitor writer, String className,
ClassLoader loader) {
super(Opcodes.ASM9, writer);
typeBeingWoven = Type.getType("L" + className.replace('.', '/') + ";");
//By default we expect to see methods from a concrete class
currentMethodDeclaringType = typeBeingWoven;
currentMethodDeclaringTypeIsInterface = false;
this.loader = loader;
}
public final void visit(int version, int access, String name, String signature,
String superName, String[] interfaces) {
LOGGER.debug(Constants.LOG_ENTRY, "visit", new Object[] { version, access,
name, signature, superName, interfaces });
// always update to the most recent version of the JVM
version = JAVA_CLASS_VERSION;
superType = Type.getType("L" + superName + ";");
try {
// we only want to implement WovenProxy once in the hierarchy.
// It's best to do this as high up as possible so we check the
// super. By loading it we may end up weaving it, but that's a good thing!
Class<?> superClass = Class.forName(superName.replace('/', '.'), false,
loader);
isSerializable = Serializable.class.isAssignableFrom(superClass) ||
Arrays.asList(interfaces).contains(Type.getInternalName(Serializable.class)) ||
checkInterfacesForSerializability(interfaces);
if (!!!WovenProxy.class.isAssignableFrom(superClass)) {
// We have found a type we need to add WovenProxy information to
implementWovenProxy = true;
if(superClass != Object.class) {
//If our superclass isn't Object, it means we didn't weave all the way
//to the top of the hierarchy. This means we need to override all the
//methods defined on our parent so that they can be intercepted!
nonObjectSupers.add(superClass);
Class<?> nextSuper = superClass.getSuperclass();
while(nextSuper != Object.class) {
nonObjectSupers.add(nextSuper);
nextSuper = nextSuper.getSuperclass();
}
//Don't use reflection - it can be dangerous
superHasNoArgsConstructor = superHasNoArgsConstructor(superName, name);
} else {
superHasNoArgsConstructor = true;
}
// re-work the interfaces list to include WovenProxy
String[] interfacesPlusWovenProxy = new String[interfaces.length + 1];
System.arraycopy(interfaces, 0, interfacesPlusWovenProxy, 0, interfaces.length);
interfacesPlusWovenProxy[interfaces.length] = WOVEN_PROXY_IFACE_TYPE.getInternalName();
// Write the class header including WovenProxy.
cv.visit(version, access, name, signature, superName, interfacesPlusWovenProxy);
} else {
// Already has a woven proxy parent, but we still need to write the
// header!
cv.visit(version, access, name, signature, superName, interfaces);
}
} catch (ClassNotFoundException e) {
// If this happens we're about to hit bigger trouble on verify, so we
// should stop weaving and fail. Make sure we don't cause the hook to
// throw an error though.
UnableToProxyException u = new UnableToProxyException(name, e);
cannotLoadSuperClassException(superName, u);
}
}
private void cannotLoadSuperClassException(String superName, UnableToProxyException u) {
String msg = format("Unable to load the super type %s for class %s.",
superName.replace('/', '.'), typeBeingWoven.getClassName());
throw new RuntimeException(msg, u);
}
/**
* This method allows us to determine whether a superclass has a
* non-private no-args constructor without causing it to initialize.
* This avoids a potential ClassCircularityError on Mac VMs if the
* initialization references the subclass being woven. Odd, but seen
* in the wild!
*/
private final boolean superHasNoArgsConstructor(String superName, String name) {
ConstructorFinder cf = new ConstructorFinder();
try {
InputStream is = loader.getResourceAsStream(superName +".class");
if(is == null)
throw new IOException();
new ClassReader(is).accept(cf, ClassReader.SKIP_FRAMES + ClassReader.SKIP_DEBUG + ClassReader.SKIP_CODE);
} catch (IOException ioe) {
UnableToProxyException u = new UnableToProxyException(name, ioe);
cannotLoadSuperClassException(superName, u);
}
return cf.hasNoArgsConstructor();
}
private boolean checkInterfacesForSerializability(String[] interfaces) throws ClassNotFoundException {
for(String iface : interfaces)
{
if(Serializable.class.isAssignableFrom(Class.forName(
iface.replace('/', '.'), false, loader)))
return true;
}
return false;
}
/**
* This method is called on each method implemented on this object (but not
* for superclass methods) Each of these methods is visited in turn and the
* code here generates the byte code for the calls to the InovcationListener
* around the existing method
*/
public final MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
LOGGER.debug(Constants.LOG_ENTRY, "visitMethod", new Object[] { access,
name, desc, signature, exceptions });
Method currentMethod = new Method(name, desc);
getKnownMethods().add(currentMethod);
MethodVisitor methodVisitorToReturn = null;
// Only weave "real" instance methods. Not constructors, initializers or
// compiler generated ones.
if ((access & (ACC_STATIC | ACC_PRIVATE | ACC_SYNTHETIC
| ACC_NATIVE | ACC_BRIDGE)) == 0 && !!!name.equals("<init>") &&
!!!name.equals("<clinit>")) {
// found a method we should weave
//Create a field name and store it for later
String methodStaticFieldName = "methodField" + getSanitizedUUIDString();
transformedMethods.put(methodStaticFieldName, new TypeMethod(
currentMethodDeclaringType, currentMethod));
// Surround the MethodVisitor with our weaver so we can manipulate the code
methodVisitorToReturn = getWeavingMethodVisitor(access, name, desc,
signature, exceptions, currentMethod, methodStaticFieldName,
currentMethodDeclaringType, currentMethodDeclaringTypeIsInterface);
} else if (name.equals("<clinit>")){
//there is an existing clinit method, change the fields we use
//to write our init code to static_init_UUID instead
staticInitMethod = new Method("static_init_" + UU_ID, Type.VOID_TYPE, NO_ARGS);
staticInitMethodFlags = staticInitMethodFlags | ACC_FINAL;
methodVisitorToReturn = new AdviceAdapter(Opcodes.ASM9, cv.visitMethod(access, name, desc, signature,
exceptions), access, name, desc){
@Override
protected void onMethodEnter()
{
//add into the <clinit> a call to our synthetic static_init_UUID
invokeStatic(typeBeingWoven, staticInitMethod);
super.onMethodEnter();
}
};
} else {
if(currentMethod.getArgumentTypes().length == 0 && name.equals("<init>"))
hasNoArgsConstructor = true;
//This isn't a method we want to weave, so just get the default visitor
methodVisitorToReturn = cv.visitMethod(access, name, desc, signature,
exceptions);
}
LOGGER.debug(Constants.LOG_EXIT, "visitMethod", methodVisitorToReturn);
return methodVisitorToReturn;
}
/**
* Our class may claim to implement WovenProxy, but doesn't have any
* implementations! We should fix this.
*/
public void visitEnd() {
LOGGER.debug(Constants.LOG_ENTRY, "visitEnd");
for(Class<?> c : nonObjectSupers) {
setCurrentMethodDeclaringType(Type.getType(c), false);
try {
readClass(c, new MethodCopyingClassAdapter(this, loader, c, typeBeingWoven,
getKnownMethods(), transformedMethods));
} catch (IOException e) {
String msg = format("Unexpected error processing %s when weaving %s.",
c.getName(), typeBeingWoven.getClassName());
throw new RuntimeException(msg, e);
}
}
// If we need to implement woven proxy in this class then write the methods
if (implementWovenProxy) {
writeFinalWovenProxyMethods();
}
// this method is called when we reach the end of the class
// so it is time to make sure the static initialiser method is written
writeStaticInitMethod();
// Make sure we add the instance specific WovenProxy method to our class,
// and give ourselves a constructor to use
writeCreateNewProxyInstanceAndConstructor();
// now delegate to the cv
cv.visitEnd();
LOGGER.debug(Constants.LOG_EXIT, "visitEnd");
}
public Set<Method> getKnownMethods() {
return knownMethods;
}
/**
* Get the {@link MethodVisitor} that will weave a given method
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
* @param currentMethod
* @param methodStaticFieldName
* @return
*/
protected abstract MethodVisitor getWeavingMethodVisitor(int access, String name,
String desc, String signature, String[] exceptions, Method currentMethod,
String methodStaticFieldName, Type currentMethodDeclaringType,
boolean currentMethodDeclaringTypeIsInterface);
/**
* Write the methods we need for wovenProxies on the highest supertype
*/
private final void writeFinalWovenProxyMethods() {
// add private fields for the Callable<Object> dispatcher
// and InvocationListener. These aren't static because we can have
// multiple instances of the same proxy class. These should not be
// serialized, or used in JPA or any other thing we can think of,
// so we annotate them as necessary
generateField(DISPATCHER_FIELD, Type.getDescriptor(Callable.class));
generateField(LISTENER_FIELD, Type.getDescriptor(InvocationListener.class));
// a general methodAdapter field that we will use to with GeneratorAdapters
// to create the methods required to implement WovenProxy
GeneratorAdapter methodAdapter;
// add a method for unwrapping the dispatcher
methodAdapter = getMethodGenerator(PUBLIC_GENERATED_METHOD_ACCESS, new Method(
"org_apache_aries_proxy_weaving_WovenProxy_unwrap", DISPATCHER_TYPE,
NO_ARGS));
// /////////////////////////////////////////////////////
// Implement the method
// load this to get the field
methodAdapter.loadThis();
// get the dispatcher field and return
methodAdapter.getField(typeBeingWoven, DISPATCHER_FIELD, DISPATCHER_TYPE);
methodAdapter.returnValue();
methodAdapter.endMethod();
// /////////////////////////////////////////////////////
// add a method for checking if the dispatcher is set
methodAdapter = getMethodGenerator(PUBLIC_GENERATED_METHOD_ACCESS, new Method(
"org_apache_aries_proxy_weaving_WovenProxy_isProxyInstance",
Type.BOOLEAN_TYPE, NO_ARGS));
// /////////////////////////////////////////////////////
// Implement the method
// load this to get the field
methodAdapter.loadThis();
// make a label for return true
Label returnTrueLabel = methodAdapter.newLabel();
// get the dispatcher field for the stack
methodAdapter.getField(typeBeingWoven, DISPATCHER_FIELD, DISPATCHER_TYPE);
// check if the dispatcher was non-null and goto return true if it was
methodAdapter.ifNonNull(returnTrueLabel);
methodAdapter.loadThis();
// get the listener field for the stack
methodAdapter.getField(typeBeingWoven, LISTENER_FIELD, LISTENER_TYPE);
// check if the listener field was non-null and goto return true if it was
methodAdapter.ifNonNull(returnTrueLabel);
// return false if we haven't jumped anywhere
methodAdapter.push(false);
methodAdapter.returnValue();
// mark the returnTrueLable
methodAdapter.mark(returnTrueLabel);
methodAdapter.push(true);
methodAdapter.returnValue();
// end the method
methodAdapter.endMethod();
// ///////////////////////////////////////////////////////
}
/**
* We write createNewProxyInstance separately because it isn't final, and is
* overridden on each class, we also write a constructor for this method to
* use if we don't have one.
*/
private final void writeCreateNewProxyInstanceAndConstructor() {
GeneratorAdapter methodAdapter = getMethodGenerator(ACC_PUBLIC, new Method(
"org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance",
WOVEN_PROXY_IFACE_TYPE, DISPATCHER_LISTENER_METHOD_ARGS));
// /////////////////////////////////////////////////////
// Implement the method
// Create and instantiate a new instance, then return it
methodAdapter.newInstance(typeBeingWoven);
methodAdapter.dup();
methodAdapter.loadArgs();
methodAdapter.invokeConstructor(typeBeingWoven, new Method("<init>",
Type.VOID_TYPE, DISPATCHER_LISTENER_METHOD_ARGS));
methodAdapter.returnValue();
methodAdapter.endMethod();
//////////////////////////////////////////////////////////
// Write a protected no-args constructor for this class
methodAdapter = getMethodGenerator(ACC_PROTECTED | ACC_SYNTHETIC, ARGS_CONSTRUCTOR);
// /////////////////////////////////////////////////////
// Implement the constructor
// For the top level supertype we need to invoke a no-args super, on object
//if we have to
if(implementWovenProxy) {
methodAdapter.loadThis();
if (superHasNoArgsConstructor)
methodAdapter.invokeConstructor(superType, NO_ARGS_CONSTRUCTOR);
else {
if(hasNoArgsConstructor)
methodAdapter.invokeConstructor(typeBeingWoven, NO_ARGS_CONSTRUCTOR);
else
throw new RuntimeException(new UnableToProxyException(typeBeingWoven.getClassName(),
String.format("The class %s and its superclass %s do not have no-args constructors and cannot be woven.",
typeBeingWoven.getClassName(), superType.getClassName())));
}
methodAdapter.loadThis();
methodAdapter.loadArg(0);
methodAdapter.putField(typeBeingWoven, DISPATCHER_FIELD, DISPATCHER_TYPE);
methodAdapter.loadThis();
methodAdapter.loadArg(1);
methodAdapter.putField(typeBeingWoven, LISTENER_FIELD, LISTENER_TYPE);
} else {
//We just invoke the super with args
methodAdapter.loadThis();
methodAdapter.loadArgs();
methodAdapter.invokeConstructor(superType, ARGS_CONSTRUCTOR);
}
//Throw an NPE if the dispatcher is null, return otherwise
methodAdapter.loadArg(0);
Label returnValue = methodAdapter.newLabel();
methodAdapter.ifNonNull(returnValue);
methodAdapter.newInstance(NPE_TYPE);
methodAdapter.dup();
methodAdapter.push("The dispatcher must never be null!");
methodAdapter.invokeConstructor(NPE_TYPE, NPE_CONSTRUCTOR);
methodAdapter.throwException();
methodAdapter.mark(returnValue);
methodAdapter.returnValue();
methodAdapter.endMethod();
//////////////////////////////////////////////////////////
}
/**
* Create fields and an initialiser for {@link java.lang.reflect.Method}
* objects in our class
*/
private final void writeStaticInitMethod() {
// we create a static field for each method we encounter with a *unique*
// random name
// since each method needs to be stored individually
for (String methodStaticFieldName : transformedMethods.keySet()) {
// add a private static field for the method
cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_SYNTHETIC,
methodStaticFieldName, METHOD_TYPE.getDescriptor(), null, null)
.visitEnd();
}
GeneratorAdapter staticAdapter = new GeneratorAdapter(staticInitMethodFlags,
staticInitMethod, null, null, cv);
for (Entry<String, TypeMethod> entry : transformedMethods.entrySet()) {
// Add some more code to the static initializer
TypeMethod m = entry.getValue();
Type[] targetMethodParameters = m.method.getArgumentTypes();
String methodStaticFieldName = entry.getKey();
Label beginPopulate = staticAdapter.newLabel();
Label endPopulate = staticAdapter.newLabel();
Label catchHandler = staticAdapter.newLabel();
staticAdapter.visitTryCatchBlock(beginPopulate, endPopulate,
catchHandler, THROWABLE_INAME);
staticAdapter.mark(beginPopulate);
staticAdapter.push(m.declaringClass);
// push the method name string arg onto the stack
staticAdapter.push(m.method.getName());
// create an array of the method parm class[] arg
staticAdapter.push(targetMethodParameters.length);
staticAdapter.newArray(CLASS_TYPE);
int index = 0;
for (Type t : targetMethodParameters) {
staticAdapter.dup();
staticAdapter.push(index);
staticAdapter.push(t);
staticAdapter.arrayStore(CLASS_TYPE);
index++;
}
// invoke the getMethod
staticAdapter.invokeVirtual(CLASS_TYPE,
new Method("getDeclaredMethod", METHOD_TYPE, new Type[] {
STRING_TYPE, CLASS_ARRAY_TYPE}));
// store the reflected method in the static field
staticAdapter.putStatic(typeBeingWoven, methodStaticFieldName,
METHOD_TYPE);
Label afterCatch = staticAdapter.newLabel();
staticAdapter.mark(endPopulate);
staticAdapter.goTo(afterCatch);
staticAdapter.mark(catchHandler);
// We don't care about the exception, so pop it off
staticAdapter.pop();
// store the reflected method in the static field
staticAdapter.visitInsn(ACONST_NULL);
staticAdapter.putStatic(typeBeingWoven, methodStaticFieldName,
METHOD_TYPE);
staticAdapter.mark(afterCatch);
}
staticAdapter.returnValue();
staticAdapter.endMethod();
}
/**
* Get a new UUID suitable for use in method and field names
*
* @return
*/
public static final String getSanitizedUUIDString() {
return UUID.randomUUID().toString().replace('-', '_');
}
/**
* This method will read the bytes for the supplied {@link Class} using the
* supplied ASM {@link ClassVisitor}, the reader will skip DEBUG, FRAMES and CODE.
* @param c
* @param adapter
* @throws IOException
*/
public static void readClass(Class<?> c, ClassVisitor adapter) throws IOException {
String className = c.getName().replace(".", "/") + ".class";
//Load the class bytes and copy methods across
ClassLoader loader = c.getClassLoader();
if (loader == null) {
//system class, use SystemModuleClassLoader as fallback
loader = new SystemModuleClassLoader();
}
ClassReader cReader = new ClassReader(loader.getResourceAsStream(className));
cReader.accept(adapter, ClassReader.SKIP_CODE |
ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
}
/**
* Generate an instance field that should be "invisible" to normal code
*
* @param fieldName
* @param fieldDescriptor
*/
private final void generateField(String fieldName, String fieldDescriptor) {
FieldVisitor fv = cv.visitField(ACC_PROTECTED | ACC_TRANSIENT | ACC_SYNTHETIC
| ACC_FINAL, fieldName, fieldDescriptor, null, null);
for (String s : annotationTypeDescriptors)
fv.visitAnnotation(s, true).visitEnd();
fv.visitEnd();
}
/**
* Get a generator for a method, this be annotated with the "invisibility"
* annotations (and ensured synthetic)
*
* @param methodSignature
* @return
*/
private final GeneratorAdapter getMethodGenerator(int access, Method method) {
access = access | ACC_SYNTHETIC;
GeneratorAdapter ga = new GeneratorAdapter(access, method, null, null, cv);
for (String s : annotationTypeDescriptors)
ga.visitAnnotation(s, true).visitEnd();
ga.visitCode();
return ga;
}
public final void setCurrentMethodDeclaringType(Type type, boolean isInterface) {
currentMethodDeclaringType = type;
currentMethodDeclaringTypeIsInterface = isInterface;
}
}
| 7,844 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/OSGiFriendlyClassVisitor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.JSRInlinerAdapter;
/**
* We need to override ASM's default behaviour in {@link #getCommonSuperClass(String, String)}
* so that it doesn't load classes (which it was doing on the wrong {@link ClassLoader}
* anyway...)
*/
public final class OSGiFriendlyClassVisitor extends ClassVisitor {
private final boolean inlineJSR;
public OSGiFriendlyClassVisitor(ClassVisitor cv, int arg1) {
super(Opcodes.ASM9, cv);
inlineJSR = arg1 == ClassWriter.COMPUTE_FRAMES;
}
@Override
public MethodVisitor visitMethod(int arg0, String arg1, String arg2,
String arg3, String[] arg4) {
MethodVisitor mv = cv.visitMethod(arg0, arg1, arg2, arg3, arg4);
if(inlineJSR)
mv = new JSRInlinerAdapter(mv, arg0, arg1, arg2, arg3, arg4);
return mv;
}
}
| 7,845 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/WovenProxyConcreteMethodAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.DISPATCHER_FIELD;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.DISPATCHER_TYPE;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.OBJECT_TYPE;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
public final class WovenProxyConcreteMethodAdapter extends AbstractWovenProxyMethodAdapter {
/** Jump here to start executing the original method body **/
private final Label executeDispatch = new Label();
public WovenProxyConcreteMethodAdapter(MethodVisitor mv, int access, String name,
String desc, String[] exceptions, String methodStaticFieldName, Method currentTransformMethod,
Type typeBeingWoven, Type methodDeclaringType, boolean isMethodDeclaringTypeInterface) {
//If we're running on Java 6+ We need to inline any JSR instructions because we're computing stack frames.
//otherwise we can save the overhead
super(mv, access, name, desc, methodStaticFieldName, currentTransformMethod, typeBeingWoven,
methodDeclaringType, isMethodDeclaringTypeInterface, false);
}
/**
* We weave instructions before the normal method body. We must be careful not
* to violate the "rules" of Java (e.g. that try blocks cannot intersect, but
* can be nested). We must also not violate the ordering that ASM expects, so
* we must not call visitMaxs, or define labels before a try/catch that uses
* them!
*/
@Override
public final void visitCode()
{
//Notify our parent that the method code is starting. This must happen first
mv.visitCode();
//unwrap for equals if we need to
if(currentTransformMethod.getName().equals("equals") &&
currentTransformMethod.getArgumentTypes().length == 1 &&
currentTransformMethod.getArgumentTypes()[0].equals(OBJECT_TYPE)) {
unwrapEqualsArgument();
}
//Check if we have a dispatcher, if so then we need to dispatch!
loadThis();
getField(typeBeingWoven, DISPATCHER_FIELD, DISPATCHER_TYPE);
ifNonNull(executeDispatch);
}
@Override
public final void visitMaxs(int stack, int locals) {
//Mark this location for continuing execution when a dispatcher is set
mark(executeDispatch);
//Write the dispatcher code in here
writeDispatcher();
mv.visitMaxs(stack, locals);
}
} | 7,846 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/ConstructorFinder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
public class ConstructorFinder extends ClassVisitor
{
private boolean hasNoArgsConstructor = false;
public boolean hasNoArgsConstructor()
{
return hasNoArgsConstructor;
}
public ConstructorFinder()
{
super(Opcodes.ASM9);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature,
String[] exceptions)
{
if("<init>".equals(name)) {
if(Type.getArgumentTypes(desc).length == 0 && (access & ACC_PRIVATE) == 0)
hasNoArgsConstructor = true;
}
return null;
}
}
| 7,847 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/OSGiFriendlyClassWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import org.apache.aries.proxy.UnableToProxyException;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
/**
* We need to override ASM's default behaviour in {@link #getCommonSuperClass(String, String)}
* so that it doesn't load classes (which it was doing on the wrong {@link ClassLoader}
* anyway...)
*/
public final class OSGiFriendlyClassWriter extends ClassWriter {
private static final String OBJECT_INTERNAL_NAME = "java/lang/Object";
private final ClassLoader loader;
public OSGiFriendlyClassWriter(ClassReader arg0, int arg1, ClassLoader loader) {
super(arg0, arg1);
this.loader = loader;
}
public OSGiFriendlyClassWriter(int arg0, ClassLoader loader) {
super(arg0);
this.loader = loader;
}
/**
* We provide an implementation that doesn't cause class loads to occur. It may
* not be sufficient because it expects to find the common parent using a single
* classloader, though in fact the common parent may only be loadable by another
* bundle from which an intermediate class is loaded
*
* precondition: arg0 and arg1 are not equal. (checked before this method is called)
*/
@Override
protected final String getCommonSuperClass(String arg0, String arg1) {
//If either is Object, then Object must be the answer
if(arg0.equals(OBJECT_INTERNAL_NAME) || arg1.equals(OBJECT_INTERNAL_NAME)) {
return OBJECT_INTERNAL_NAME;
}
Set<String> names = new HashSet<String>();
names.add(arg0);
names.add(arg1);
//Try loading the class (in ASM not for real)
try {
boolean bRunning = true;
boolean aRunning = true;
InputStream is;
String arg00 = arg0;
String arg11 = arg1;
String unable = null;
while(aRunning || bRunning ) {
if(aRunning) {
is = loader.getResourceAsStream(arg00 + ".class");
if(is != null) {
ClassReader cr = new ClassReader(is);
arg00 = cr.getSuperName();
if(arg00 == null) {
if (names.size() == 2) {
return OBJECT_INTERNAL_NAME; //arg0 is an interface
}
aRunning = false; //old arg00 was java.lang.Object
} else if(!!!names.add(arg00)) {
return arg00;
}
} else {
//The class file isn't visible on this ClassLoader
unable = arg0;
aRunning = false;
}
}
if(bRunning) {
is = loader.getResourceAsStream(arg11 + ".class");
if(is != null) {
ClassReader cr = new ClassReader(is);
arg11 = cr.getSuperName();
if(arg11 == null) {
if (names.size() == 3) {
return OBJECT_INTERNAL_NAME; //arg1 is an interface
}
bRunning = false; //old arg11 was java.lang.Object
} else if(!!!names.add(arg11)) {
return arg11;
}
} else {
unable = arg1;
bRunning = false;
}
}
}
String msg = String.format("The class %s and %s do not have a common super class.", arg0, arg1);
if (unable == null) {
throw new RuntimeException(msg);
} else {
throw new RuntimeException(new UnableToProxyException(unable, msg));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 7,848 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/MethodCopyingClassAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import static java.lang.String.format;
import java.util.Map;
import java.util.Set;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.UnableToProxyException;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;
/**
* This class is used to copy concrete methods from a super-class into a sub-class,
* but then delegate up to the super-class implementation. We expect to be called
* with {@link ClassReader#SKIP_CODE}. This class is used when we can't weave
* all the way up the Class hierarchy and need to override methods on the first
* subclass we can weave.
*/
final class MethodCopyingClassAdapter extends ClassVisitor implements Opcodes {
/** The super-class to copy from */
private final Class<?> superToCopy;
/** Is the sub-class in the same package as the super */
private final boolean samePackage;
/** The ASM {@link Type} of the sub-class */
private final Type overridingClassType;
/**
* The Set of {@link Method}s that exist in the sub-class. This set must be
* live so modifications will be reflected in the parent and prevent clashes
*/
private final Set<Method> knownMethods;
/**
* The map of field names to methods being added
*/
private final Map<String, TypeMethod> transformedMethods;
private final AbstractWovenProxyAdapter wovenProxyAdapter;
public MethodCopyingClassAdapter(AbstractWovenProxyAdapter awpa, ClassLoader definingLoader,
Class<?> superToCopy, Type overridingClassType, Set<Method> knownMethods,
Map<String, TypeMethod> transformedMethods) {
super(Opcodes.ASM9);
this.wovenProxyAdapter = awpa;
this.superToCopy = superToCopy;
this.overridingClassType = overridingClassType;
this.knownMethods = knownMethods;
this.transformedMethods = transformedMethods;
//To be in the same package they must be loaded by the same classloader and be in the same package!
if(definingLoader != superToCopy.getClassLoader()) {
samePackage = false;
} else {
String overridingClassName = overridingClassType.getClassName();
int lastIndex1 = superToCopy.getName().lastIndexOf('.');
int lastIndex2 = overridingClassName.lastIndexOf('.');
if(lastIndex1 != lastIndex2) {
samePackage = false;
} else if (lastIndex1 == -1) {
samePackage = true;
} else {
samePackage = superToCopy.getName().substring(0, lastIndex1)
.equals(overridingClassName.substring(0, lastIndex2));
}
}
}
@Override
public final MethodVisitor visitMethod(final int access, String name, String desc,
String sig, String[] exceptions) {
MethodVisitor mv = null;
//As in WovenProxyAdapter, we only care about "real" methods, but also not
//abstract ones!.
if (!!!name.equals("<init>") && !!!name.equals("<clinit>")
&& (access & (ACC_STATIC | ACC_PRIVATE | ACC_SYNTHETIC | ACC_ABSTRACT
| ACC_NATIVE | ACC_BRIDGE)) == 0) {
// identify the target method parameters and return type
Method currentTransformMethod = new Method(name, desc);
// We don't want to duplicate a method we already overrode!
if(!!!knownMethods.add(currentTransformMethod))
return null;
// found a method we should weave
// We can't override a final method
if((access & ACC_FINAL) != 0)
throw new RuntimeException(new FinalModifierException(
superToCopy, name));
// We can't call up to a default access method if we aren't in the same
// package
if((access & (ACC_PUBLIC | ACC_PROTECTED | ACC_PRIVATE)) == 0) {
if(!!!samePackage) {
methodHiddenException(name);
}
}
//Safe to copy a call to this method!
Type superType = Type.getType(superToCopy);
// identify the target method parameters and return type
String methodStaticFieldName = "methodField" + AbstractWovenProxyAdapter.getSanitizedUUIDString();
transformedMethods.put(methodStaticFieldName, new TypeMethod(
superType, currentTransformMethod));
//Remember we need to copy the fake method *and* weave it, use a
//WovenProxyMethodAdapter as well as a CopyingMethodAdapter
MethodVisitor weaver = wovenProxyAdapter.getWeavingMethodVisitor(
access, name, desc, sig, exceptions, currentTransformMethod,
methodStaticFieldName, superType, false);
if(weaver instanceof AbstractWovenProxyMethodAdapter) {
//If we are weaving this method then we might have a problem. If it's a protected method and we
//aren't in the same package then we can't dispatch the call to another object. This may sound
//odd, but if class Super has a protected method foo(), then class Sub, that extends Super, cannot
//call ((Super)o).foo() in code (it can call super.foo()). If we are in the same package then this
//gets around the problem, but if not the class will fail verification.
if(!samePackage && (access & ACC_PROTECTED) != 0) {
methodHiddenException(name);
}
mv = new CopyingMethodAdapter((GeneratorAdapter) weaver, superType, currentTransformMethod);
}
else {
//For whatever reason we aren't weaving this method. The call to super.xxx() will always work
mv = new CopyingMethodAdapter(new GeneratorAdapter(access, currentTransformMethod, mv),
superType, currentTransformMethod);
}
}
return mv;
}
private void methodHiddenException(String name) {
String msg = format("The method %s in class %s cannot be called by %s because it is in a different package.",
name, superToCopy.getName(), overridingClassType.getClassName());
throw new RuntimeException(msg,
new UnableToProxyException(superToCopy));
}
/**
* This class is used to prevent any method body being copied, instead replacing
* the body with a call to the super-types implementation. The original annotations
* attributes etc are all copied.
*/
private static final class CopyingMethodAdapter extends MethodVisitor {
/** The visitor to delegate to */
private final GeneratorAdapter mv;
/** The type that declares this method (not the one that will override it) */
private final Type superType;
/** The method we are weaving */
private final Method currentTransformMethod;
public CopyingMethodAdapter(GeneratorAdapter mv, Type superType,
Method currentTransformMethod) {
super(Opcodes.ASM9);
this.mv = mv;
this.superType = superType;
this.currentTransformMethod = currentTransformMethod;
}
//TODO might not work for attributes
@Override
public final AnnotationVisitor visitAnnotation(String arg0, boolean arg1) {
return mv.visitAnnotation(arg0, arg1);
}
@Override
public final AnnotationVisitor visitAnnotationDefault() {
return mv.visitAnnotationDefault();
}
@Override
public final AnnotationVisitor visitParameterAnnotation(int arg0, String arg1,
boolean arg2) {
return mv.visitParameterAnnotation(arg0, arg1, arg2);
}
@Override
public final void visitAttribute(Attribute attr) {
mv.visitAttribute(attr);
}
/**
* We skip code for speed when processing super-classes, this means we
* need to manually drive some methods here!
*/
@Override
public final void visitEnd() {
mv.visitCode();
//Equivalent to return super.method(args);
mv.loadThis();
mv.loadArgs();
mv.visitMethodInsn(INVOKESPECIAL, superType.getInternalName(),
currentTransformMethod.getName(), currentTransformMethod.getDescriptor());
mv.returnValue();
mv.visitMaxs(currentTransformMethod.getArgumentTypes().length + 1, 0);
mv.visitEnd();
}
}
}
| 7,849 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/AbstractWovenProxyMethodAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import static java.lang.String.format;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.DISPATCHER_FIELD;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.DISPATCHER_TYPE;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.LISTENER_FIELD;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.LISTENER_TYPE;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.METHOD_TYPE;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.NO_ARGS;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.OBJECT_TYPE;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.THROWABLE_INAME;
import static org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter.WOVEN_PROXY_IFACE_TYPE;
import static org.objectweb.asm.Opcodes.*;
import java.util.Arrays;
import org.apache.aries.proxy.InvocationListener;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;
/**
* This class weaves dispatch and listener code into a method, there are two known
* subclasses {@link WovenProxyConcreteMethodAdapter} is used for weaving instance methods
* {@link WovenProxyAbstractMethodAdapter} is used to provide a delegating
* implementation of an interface method.
*
* Roughly (but not exactly because it's easier to write working bytecode
* if you don't have to exactly recreate the Java!) this is trying to
* do the following: <code>
*
*
if(dispatcher != null) {
int returnValue;
Object token = null;
boolean inInvoke = false;
try {
Object toInvoke = dispatcher.call();
if(listener != null)
token = listener.preInvoke(toInvoke, method, args);
inInvoke = true;
returnValue = ((Template) toInvoke).doStuff(args);
inInvoke = false;
if(listener != null)
listener.postInvoke(token, toInvoke, method, args);
} catch (Throwable e){
// whether the the exception is an error is an application decision
// if we catch an exception we decide carefully which one to
// throw onwards
Throwable exceptionToRethrow = null;
// if the exception came from a precall or postcall
// we will rethrow it
if (!inInvoke) {
exceptionToRethrow = e;
}
// if the exception didn't come from precall or postcall then it
// came from invoke
// we will rethrow this exception if it is not a runtime
// exception, but we must unwrap InvocationTargetExceptions
else {
if (!(e instanceof RuntimeException)) {
exceptionToRethrow = e;
}
}
try {
if(listener != null)
listener.postInvokeExceptionalReturn(token, method, null, e);
} catch (Throwable f) {
// we caught an exception from
// postInvokeExceptionalReturn
// if we haven't already chosen an exception to rethrow then
// we will throw this exception
if (exceptionToRethrow == null) {
exceptionToRethrow = f;
}
}
// if we made it this far without choosing an exception we
// should throw e
if (exceptionToRethrow == null) {
exceptionToRethrow = e;
}
throw exceptionToRethrow;
}
}
//...original method body
</code>
*
*
*/
public abstract class AbstractWovenProxyMethodAdapter extends GeneratorAdapter
{
/** The type of a RuntimeException */
private static final Type RUNTIME_EX_TYPE = Type.getType(RuntimeException.class);
private static final Type THROWABLE_TYPE = Type.getType(Throwable.class);
/** The postInvoke method of an {@link InvocationListener} */
private static final Method POST_INVOKE_METHOD = getAsmMethodFromClass(InvocationListener.class, "postInvoke", Object.class,
Object.class, java.lang.reflect.Method.class, Object.class);
/** The postInvokeExceptionalReturn method of an {@link InvocationListener} */
private static final Method POST_INVOKE_EXCEPTIONAL_METHOD = getAsmMethodFromClass(InvocationListener.class,
"postInvokeExceptionalReturn", Object.class, Object.class,
java.lang.reflect.Method.class, Throwable.class);
/** The preInvoke method of an {@link InvocationListener} */
private static final Method PRE_INVOKE_METHOD = getAsmMethodFromClass(InvocationListener.class, "preInvoke", Object.class,
java.lang.reflect.Method.class, Object[].class);
/** The name of the static field that stores our {@link java.lang.reflect.Method} */
private final String methodStaticFieldName;
/** The current method */
protected final Method currentTransformMethod;
/** The type of <code>this</code> */
protected final Type typeBeingWoven;
/** True if this is a void method */
private final boolean isVoid;
//ints for local store
/** The local we use to store the {@link InvocationListener} token */
private int preInvokeReturnedToken;
/** The local we use to note whether we are in the original method body or not */
private int inNormalMethod;
/** The local we use to store the invocation target to dispatch to */
private int dispatchTarget;
/** The local for storing our method's result */
private int normalResult;
//the Labels we need for jumping around the pre/post/postexception and current method code
/** This marks the start of the try/catch around the pre/postInvoke*/
private final Label beginTry = new Label();
/** This marks the end of the try/catch around the pre/postInvoke*/
private final Label endTry = new Label();
/** The return type of this method */
private final Type returnType;
private final Type methodDeclaringType;
private final boolean isMethodDeclaringTypeInterface;
private boolean isDefaultMethod;
/**
* Construct a new method adapter
* @param mv - the method visitor to write to
* @param access - the access modifiers on this method
* @param name - the name of this method
* @param desc - the descriptor of this method
* @param methodStaticFieldName - the name of the static field that will hold
* the {@link java.lang.reflect.Method} representing
* this method.
* @param currentTransformMethod - the ASM representation of this method
* @param proxyType - the type being woven that contains this method
*/
public AbstractWovenProxyMethodAdapter(MethodVisitor mv, int access, String name, String desc,
String methodStaticFieldName, Method currentTransformMethod, Type typeBeingWoven,
Type methodDeclaringType, boolean isMethodDeclaringTypeInterface, boolean isDefaultMethod)
{
super(ASM9, mv, access, name, desc);
this.methodStaticFieldName = methodStaticFieldName;
this.currentTransformMethod = currentTransformMethod;
returnType = currentTransformMethod.getReturnType();
isVoid = returnType.getSort() == Type.VOID;
this.typeBeingWoven = typeBeingWoven;
this.methodDeclaringType = methodDeclaringType;
this.isMethodDeclaringTypeInterface = isMethodDeclaringTypeInterface;
this.isDefaultMethod = isDefaultMethod;
}
@Override
public abstract void visitCode();
@Override
public abstract void visitMaxs(int stack, int locals);
/**
* Write out the bytecode instructions necessary to do the dispatch.
* We know the dispatcher is non-null, and we need a try/catch around the
* invocation and listener calls.
*/
protected final void writeDispatcher() {
// Setup locals we will use in the dispatch
setupLocals();
//Write the try catch block
visitTryCatchBlock(beginTry, endTry, endTry, THROWABLE_INAME);
mark(beginTry);
//Start dispatching, get the target object and store it
loadThis();
getField(typeBeingWoven, DISPATCHER_FIELD, DISPATCHER_TYPE);
invokeInterface(DISPATCHER_TYPE, new Method("call", OBJECT_TYPE, NO_ARGS));
storeLocal(dispatchTarget);
//Pre-invoke, invoke, post-invoke, return
writePreInvoke();
//Start the real method
push(true);
storeLocal(inNormalMethod);
//Dispatch the method and store the result (null for void)
loadLocal(dispatchTarget);
checkCast(methodDeclaringType);
loadArgs();
if(isMethodDeclaringTypeInterface) {
invokeInterface(methodDeclaringType, currentTransformMethod);
} else {
invokeVirtual(methodDeclaringType, currentTransformMethod);
}
if(isVoid) {
visitInsn(ACONST_NULL);
}
storeLocal(normalResult);
// finish the real method and post-invoke
push(false);
storeLocal(inNormalMethod);
writePostInvoke();
//Return, with the return value if necessary
if(!!!isVoid) {
loadLocal(normalResult);
}
returnValue();
//End of our try, start of our catch
mark(endTry);
writeMethodCatchHandler();
}
/**
* Setup the normalResult, inNormalMethod, preInvokeReturnedToken and
* dispatch target locals.
*/
private final void setupLocals() {
if (isVoid){
normalResult = newLocal(OBJECT_TYPE);
} else{
normalResult = newLocal(returnType);
}
preInvokeReturnedToken = newLocal(OBJECT_TYPE);
visitInsn(ACONST_NULL);
storeLocal(preInvokeReturnedToken);
inNormalMethod = newLocal(Type.BOOLEAN_TYPE);
push(false);
storeLocal(inNormalMethod);
dispatchTarget = newLocal(OBJECT_TYPE);
visitInsn(ACONST_NULL);
storeLocal(dispatchTarget);
}
/**
* Begin trying to invoke the listener, if the listener is
* null the bytecode will branch to the supplied label, other
* otherwise it will load the listener onto the stack.
* @param l The label to branch to
*/
private final void beginListenerInvocation(Label l) {
//If there's no listener then skip invocation
loadThis();
getField(typeBeingWoven, LISTENER_FIELD, LISTENER_TYPE);
ifNull(l);
loadThis();
getField(typeBeingWoven, LISTENER_FIELD, LISTENER_TYPE);
}
/**
* Write out the preInvoke. This copes with the listener being null
*/
private final void writePreInvoke() {
//The place to go if the listener is null
Label nullListener = newLabel();
beginListenerInvocation(nullListener);
// The listener is on the stack, we need (target, method, args)
loadLocal(dispatchTarget);
getStatic(typeBeingWoven, methodStaticFieldName, METHOD_TYPE);
loadArgArray();
//invoke it and store the token returned
invokeInterface(LISTENER_TYPE, PRE_INVOKE_METHOD);
storeLocal(preInvokeReturnedToken);
mark(nullListener);
}
/**
* Write out the postInvoke. This copes with the listener being null
*/
private final void writePostInvoke() {
//The place to go if the listener is null
Label nullListener = newLabel();
beginListenerInvocation(nullListener);
// The listener is on the stack, we need (token, target, method, result)
loadLocal(preInvokeReturnedToken);
loadLocal(dispatchTarget);
getStatic(typeBeingWoven, methodStaticFieldName, METHOD_TYPE);
loadLocal(normalResult);
//If the result a primitive then we need to box it
if (!!!isVoid && returnType.getSort() != Type.OBJECT && returnType.getSort() != Type.ARRAY){
box(returnType);
}
//invoke the listener
invokeInterface(LISTENER_TYPE, POST_INVOKE_METHOD);
mark(nullListener);
}
/**
* Write the catch handler for our method level catch, this runs the exceptional
* post-invoke if there is a listener, and throws the correct exception at the
* end
*/
private final void writeMethodCatchHandler() {
//Store the original exception
int originalException = newLocal(THROWABLE_TYPE);
storeLocal(originalException);
//Start by initialising exceptionToRethrow
int exceptionToRethrow = newLocal(THROWABLE_TYPE);
visitInsn(ACONST_NULL);
storeLocal(exceptionToRethrow);
//We need another try catch around the postInvokeExceptionalReturn, so here
//are some labels and the declaration for it
Label beforeInvoke = newLabel();
Label afterInvoke = newLabel();
visitTryCatchBlock(beforeInvoke, afterInvoke, afterInvoke, THROWABLE_INAME);
//If we aren't in normal flow then set exceptionToRethrow = originalException
loadLocal(inNormalMethod);
Label inNormalMethodLabel = newLabel();
// Jump if not zero (false)
visitJumpInsn(IFNE, inNormalMethodLabel);
loadLocal(originalException);
storeLocal(exceptionToRethrow);
goTo(beforeInvoke);
mark(inNormalMethodLabel);
//We are in normal method flow so set exceptionToRethrow = originalException
//if originalException is not a runtime exception
loadLocal(originalException);
instanceOf(RUNTIME_EX_TYPE);
//If false then store original in toThrow, otherwise go to beforeInvoke
visitJumpInsn(IFNE, beforeInvoke);
loadLocal(originalException);
storeLocal(exceptionToRethrow);
goTo(beforeInvoke);
//Setup of variables finished, begin try/catch
//Mark the start of our try
mark(beforeInvoke);
//Begin invocation of the listener, jump to throw if null
Label throwSelectedException = newLabel();
beginListenerInvocation(throwSelectedException);
//We have a listener, so call it (token, target, method, exception)
loadLocal(preInvokeReturnedToken);
loadLocal(dispatchTarget);
getStatic(typeBeingWoven, methodStaticFieldName, METHOD_TYPE);
loadLocal(originalException);
invokeInterface(LISTENER_TYPE, POST_INVOKE_EXCEPTIONAL_METHOD);
goTo(throwSelectedException);
mark(afterInvoke);
//catching another exception replaces the original
storeLocal(originalException);
//Throw exceptionToRethrow if it isn't null, or the original if it is
Label throwException = newLabel();
mark(throwSelectedException);
loadLocal(exceptionToRethrow);
ifNonNull(throwException);
loadLocal(originalException);
storeLocal(exceptionToRethrow);
mark(throwException);
loadLocal(exceptionToRethrow);
throwException();
}
/**
* This method unwraps woven proxy instances for use in the right-hand side
* of equals methods
*/
protected final void unwrapEqualsArgument() {
//Create and initialize a local for our work
int unwrapLocal = newLocal(OBJECT_TYPE);
visitInsn(ACONST_NULL);
storeLocal(unwrapLocal);
Label startUnwrap = newLabel();
mark(startUnwrap);
//Load arg and check if it is a WovenProxy instances
loadArg(0);
instanceOf(WOVEN_PROXY_IFACE_TYPE);
Label unwrapFinished = newLabel();
//Jump if zero (false)
visitJumpInsn(Opcodes.IFEQ, unwrapFinished);
//Arg is a wovenProxy, if it is the same as last time then we're done
loadLocal(unwrapLocal);
loadArg(0);
ifCmp(OBJECT_TYPE, EQ, unwrapFinished);
//Not the same, store current arg in unwrapLocal for next loop
loadArg(0);
storeLocal(unwrapLocal);
//So arg is a WovenProxy, but not the same as last time, cast it and store
//the result of unwrap.call in the arg
loadArg(0);
checkCast(WOVEN_PROXY_IFACE_TYPE);
//Now unwrap
invokeInterface(WOVEN_PROXY_IFACE_TYPE, new Method("org_apache_aries_proxy_weaving_WovenProxy_unwrap",
DISPATCHER_TYPE, NO_ARGS));
//Now we may have a Callable to invoke
int callable = newLocal(DISPATCHER_TYPE);
storeLocal(callable);
loadLocal(callable);
ifNull(unwrapFinished);
loadLocal(callable);
invokeInterface(DISPATCHER_TYPE, new Method("call",
OBJECT_TYPE, NO_ARGS));
//Store the result and we're done (for this iteration)
storeArg(0);
goTo(startUnwrap);
mark(unwrapFinished);
}
/**
* A utility method for getting an ASM method from a Class
* @param clazz the class to search
* @param name The method name
* @param argTypes The method args
* @return
*/
private static final Method getAsmMethodFromClass(Class<?> clazz, String name, Class<?>... argTypes)
{
//get the java.lang.reflect.Method to get the types
java.lang.reflect.Method ilMethod = null;
try {
ilMethod = clazz.getMethod(name, argTypes);
} catch (Exception e) {
//Should be impossible!
throw new RuntimeException(format("Error finding InvocationListener method %s with argument types %s.",
name, Arrays.toString(argTypes)), e);
}
//get the ASM method
return new Method(name, Type.getReturnType(ilMethod), Type.getArgumentTypes(ilMethod));
}
}
| 7,850 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/common/TypeMethod.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.common;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
/**
* This object stores a {@link Method} and the class that declares it
*/
public final class TypeMethod {
final Type declaringClass;
final Method method;
public TypeMethod(Type declaringClass,
Method method) {
this.declaringClass = declaringClass;
this.method = method;
}
}
| 7,851 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/interfaces/InterfaceCombiningClassAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.interfaces;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.ProxyUtils;
import org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter;
import org.apache.aries.proxy.impl.common.OSGiFriendlyClassVisitor;
import org.apache.aries.proxy.impl.common.OSGiFriendlyClassWriter;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
/**
* This class is used to aggregate several interfaces into a real class which implements all of them
*/
final class InterfaceCombiningClassAdapter extends ClassVisitor implements Opcodes {
/** The superclass we should use */
private final Class<?> superclass;
/** The interfaces we need to implement */
private final Collection<Class<?>> interfaces;
/** The {@link ClassWriter} we use to write our class */
private final ClassWriter writer;
/** The adapter we use to weave in our method implementations */
private final AbstractWovenProxyAdapter adapter;
/** Whether we have already written the class bytes */
private boolean done = false;
/**
* Construct an {@link InterfaceCombiningClassAdapter} to combine the supplied
* interfaces into a class with the supplied name using the supplied classloader
* @param className
* @param loader
* @param interfaces
*/
InterfaceCombiningClassAdapter(String className,
ClassLoader loader, Class<?> superclass, Collection<Class<?>> interfaces) {
super(Opcodes.ASM9);
writer = new OSGiFriendlyClassWriter(ClassWriter.COMPUTE_FRAMES, loader);
ClassVisitor cv = new OSGiFriendlyClassVisitor(writer, ClassWriter.COMPUTE_FRAMES);
adapter = new InterfaceUsingWovenProxyAdapter(cv, className, loader);
this.interfaces = interfaces;
this.superclass = superclass;
String[] interfaceNames = new String[interfaces.size()];
int i = 0;
for(Class<?> in : interfaces) {
interfaceNames[i] = Type.getInternalName(in);
i++;
}
adapter.visit(ProxyUtils.getWeavingJavaVersion(), ACC_PUBLIC | ACC_SYNTHETIC, className, null,
(superclass == null) ? AbstractWovenProxyAdapter.OBJECT_TYPE.getInternalName() :
Type.getInternalName(superclass), interfaceNames);
}
@Override
public final MethodVisitor visitMethod(int access, String name, String desc,
String sig, String[] arg4) {
//If we already implement this method (from another interface) then we don't
//want a duplicate. We also don't want to copy any static init blocks (these
//initialize static fields on the interface that we don't copy
if(adapter.getKnownMethods().contains(new Method(name, desc)) ||
"<clinit>".equals(name)) {
return null;
}
else if(((access & (ACC_PRIVATE|ACC_SYNTHETIC)) == (ACC_PRIVATE|ACC_SYNTHETIC))) {
// private, synthetic methods on interfaces don't need to be proxied.
return null;
} else if (((access & (ACC_STATIC)) == (ACC_STATIC))) {
//static methods on interfaces don't need to be proxied
return null;
}
else {//We're going to implement this method, so make it non abstract!
return adapter.visitMethod(access, name, desc, null, arg4);
}
}
/**
* Generate the byte[] for our class
* @return
* @throws UnableToProxyException
*/
final byte[] generateBytes() throws UnableToProxyException {
if(!!!done) {
for(Class<?> c : interfaces) {
adapter.setCurrentMethodDeclaringType(Type.getType(c), true);
try {
AbstractWovenProxyAdapter.readClass(c, this);
} catch (IOException e) {
throw new UnableToProxyException(c, e);
}
}
Class<?> clazz = superclass;
while(clazz != null && (clazz.getModifiers() & Modifier.ABSTRACT) != 0) {
adapter.setCurrentMethodDeclaringType(Type.getType(clazz), false);
visitAbstractMethods(clazz);
clazz = clazz.getSuperclass();
}
adapter.setCurrentMethodDeclaringType(AbstractWovenProxyAdapter.OBJECT_TYPE, false);
visitObjectMethods();
adapter.visitEnd();
done = true;
}
return writer.toByteArray();
}
private void visitAbstractMethods(Class<?> clazz) {
for(java.lang.reflect.Method m : clazz.getDeclaredMethods()) {
int modifiers = m.getModifiers();
if((modifiers & Modifier.ABSTRACT) != 0) {
List<String> exceptions = new ArrayList<String>();
for(Class<?> c : m.getExceptionTypes()) {
exceptions.add(Type.getInternalName(c));
}
MethodVisitor visitor = visitMethod(modifiers, m.getName(), Method.getMethod(m).getDescriptor(),
null, exceptions.toArray(new String[exceptions.size()]));
if (visitor != null) visitor.visitEnd();
}
}
}
/**
* Make sure that the three common Object methods toString, equals and hashCode are redirected to the delegate
* even if they are not on any of the interfaces
*/
private void visitObjectMethods() {
MethodVisitor visitor = visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "toString", "()Ljava/lang/String;", null, null);
if (visitor != null) visitor.visitEnd();
visitor = visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "equals", "(Ljava/lang/Object;)Z", null, null);
if (visitor != null) visitor.visitEnd();
visitor = visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "hashCode", "()I", null, null);
if (visitor != null) visitor.visitEnd();
}
}
| 7,852 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/interfaces/ProxyClassLoader.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.proxy.impl.interfaces;
import java.security.AllPermission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.ProtectionDomain;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter;
import org.apache.aries.proxy.weaving.WovenProxy;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
/** An implementation of ClassLoader that will be used to define our proxy class */
final class ProxyClassLoader extends ClassLoader {
private static final ProtectionDomain PROXY_PROTECTION_DOMAIN;
static {
PermissionCollection pc = new Permissions();
pc.add(new AllPermission());
PROXY_PROTECTION_DOMAIN = new ProtectionDomain(null, pc);
}
/** A {@link Map} of classes we already know */
private final ConcurrentMap<LinkedHashSet<Class<?>>, String> classes =
new ConcurrentHashMap<LinkedHashSet<Class<?>>, String>();
private final ConcurrentMap<String, Class<?>> locatedClasses =
new ConcurrentHashMap<String, Class<?>>();
private final Set<Class<?>> ifaces = new HashSet<Class<?>>();
private final ReadWriteLock ifacesLock = new ReentrantReadWriteLock();
public ProxyClassLoader(Bundle bundle) {
// super(AriesFrameworkUtil.getClassLoader(bundle));
super(getClassloader(bundle));
}
private static ClassLoader getClassloader(Bundle bundle) {
if (bundle == null) return ProxyClassLoader.class.getClassLoader();
BundleWiring wiring = bundle != null ? bundle.adapt(BundleWiring.class) : null;
return wiring != null ? wiring.getClassLoader() : null;
}
@Override
protected Class<?> findClass(String className) {
if(WovenProxy.class.getName().equals(className))
return WovenProxy.class;
else if (InvocationListener.class.getName().equals(className))
return InvocationListener.class;
else {
Class<?> c = locatedClasses.get(className);
if(c != null)
return c;
Lock rLock = ifacesLock.readLock();
rLock.lock();
try {
Set<ClassLoader> cls = new HashSet<ClassLoader>();
for(Class<?> iface : ifaces) {
if(cls.add(iface.getClassLoader())) {
try {
c = Class.forName(className, false, iface.getClassLoader());
locatedClasses.put(className, c);
return c;
} catch (ClassNotFoundException e) {
// This is a no-op
}
}
}
} finally {
rLock.unlock();
}
}
return null;
}
/**
* Test whether the classloader is invalidated by the set of classes
* @return
*/
public boolean isInvalid(Set<Class<?>> createSet) {
for (Class<?> iface : createSet) {
try {
Class<?> newIFace = Class.forName(iface.getName(), false, this);
if (!!!newIFace.equals(iface)) return true;
} catch (ClassNotFoundException cnfe) {
return true;
}
}
return false;
}
public Class<?> createProxyClass(Class<?> superclass, SortedSet<Class<?>> interfaces) throws UnableToProxyException {
LinkedHashSet<Class<?>> createSet = new LinkedHashSet<Class<?>>(interfaces);
//Even a null superclass helps with key uniqueness
createSet.add(superclass);
String className = classes.get(createSet);
if(className != null) {
try {
return Class.forName(className, false, this);
} catch (ClassNotFoundException cnfe) {
//This is odd, but we should be able to recreate the class, continue
classes.remove(createSet);
}
}
Lock wLock = ifacesLock.writeLock();
wLock.lock();
try {
//We want the superclass, but only if it isn't null
ifaces.addAll(interfaces);
if(superclass != null) ifaces.add(superclass);
} finally {
wLock.unlock();
}
className = "Proxy" + AbstractWovenProxyAdapter.getSanitizedUUIDString();
InterfaceCombiningClassAdapter icca = new InterfaceCombiningClassAdapter(
className, this, superclass, interfaces);
//Use a special protection domain that grants AllPermission to our Proxy
//object. This is important so that we never get in the way of any security
//checks. This isn't unsafe because we only add simple dispatch/listener code
try {
byte[] bytes = icca.generateBytes();
Class<?> c = defineClass(className, bytes, 0, bytes.length,
PROXY_PROTECTION_DOMAIN);
String old = classes.putIfAbsent(createSet, className);
if(old != null) {
c = Class.forName(className, false, this);
}
return c;
} catch (ClassFormatError cfe) {
throw new UnableToProxyException(createSet.iterator().next(), cfe);
} catch (ClassNotFoundException e) {
throw new UnableToProxyException(createSet.iterator().next(), e);
}
}
} | 7,853 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/interfaces/InterfaceProxyGenerator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.interfaces;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.FinalModifierException;
import org.apache.aries.proxy.InvocationListener;
import org.apache.aries.proxy.UnableToProxyException;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Opcodes;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
/**
* This class is used to aggregate several interfaces into a real class which implements all of them
* It also allows you specify a superclass that the class should implement - this will add delegating
* method overrides for any abstract methods in the hierarchy, but not override any non-abstract methods.
* To be safely used as a supertype the superclass should be a WovenProxy.
*/
public final class InterfaceProxyGenerator extends ClassVisitor implements Opcodes {
public InterfaceProxyGenerator()
{
super(Opcodes.ASM9);
}
private static final Map<BundleWiring, WeakReference<ProxyClassLoader>> cache =
new WeakHashMap<BundleWiring, WeakReference<ProxyClassLoader>>(128);
/**
* Generate a new proxy instance implementing the supplied interfaces and using the supplied
* dispatcher and listener
* @param client the bundle that is trying to generate this proxy (can be null)
* @param superclass The superclass to use (or null for Object)
* @param ifaces The set of interfaces to implement (may be empty if superclass is non null)
* @param dispatcher
* @param listener
* @return
* @throws UnableToProxyException
*/
public static Object getProxyInstance(Bundle client, Class<?> superclass,
Collection<Class<?>> ifaces, Callable<Object> dispatcher, InvocationListener listener) throws UnableToProxyException{
if(superclass != null && (superclass.getModifiers() & Modifier.FINAL) != 0)
throw new FinalModifierException(superclass);
ProxyClassLoader pcl = null;
SortedSet<Class<?>> interfaces = createSet(ifaces);
synchronized (cache) {
BundleWiring wiring = client == null ? null : (BundleWiring)client.adapt(BundleWiring.class);
WeakReference<ProxyClassLoader> ref = cache.get(wiring);
if(ref != null)
pcl = ref.get();
if (pcl != null && pcl.isInvalid(interfaces)) {
pcl = null;
cache.remove(wiring);
}
if(pcl == null) {
pcl = new ProxyClassLoader(client);
cache.put(wiring, new WeakReference<ProxyClassLoader>(pcl));
}
}
Class<?> c = pcl.createProxyClass(superclass, interfaces);
try {
Constructor<?> con = c.getDeclaredConstructor(Callable.class, InvocationListener.class);
con.setAccessible(true);
return con.newInstance(dispatcher, listener);
} catch (Exception e) {
throw new UnableToProxyException(ifaces.iterator().next(), e);
}
}
/**
* Get the set of interfaces we need to process. This will return a HashSet
* that includes includes the supplied collection and any super-interfaces of
* those classes
* @param ifaces
* @return
*/
private static SortedSet<Class<?>> createSet(Collection<Class<?>> ifaces) {
SortedSet<Class<?>> classes = new TreeSet<Class<?>>(new Comparator<Class<?>>() {
public int compare(Class<?> object1, Class<?> object2) {
if (object1.getName().equals(object2.getName())) {
return 0;
} else if (object1.isAssignableFrom(object2)) {
// first class is parent of second, it occurs earlier in type hierarchy
return -1;
} else if (object2.isAssignableFrom(object1)) {
// second class is subclass of first one, it occurs later in hierarchy
return 1;
}
// types have separate inheritance trees, but it does matter which one is first or second, so we
// won't end up with duplicates
// however we can't mark them as equal cause one of them will be removed
return object1.getName().compareTo(object2.getName());
}
});
for(Class<?> c : ifaces) {
//If we already have a class contained then we have already covered its hierarchy
if(classes.add(c))
classes.addAll(createSet(Arrays.asList(c.getInterfaces())));
}
return classes;
}
}
| 7,854 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/interfaces/InterfaceUsingWovenProxyAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.impl.interfaces;
import org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter;
import org.apache.aries.proxy.impl.common.AbstractWovenProxyMethodAdapter;
import org.apache.aries.proxy.impl.common.WovenProxyAbstractMethodAdapter;
import org.apache.aries.proxy.impl.common.WovenProxyConcreteMethodAdapter;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
/**
* Used to copy method signatures into a new class
*/
final class InterfaceUsingWovenProxyAdapter extends AbstractWovenProxyAdapter {
public InterfaceUsingWovenProxyAdapter(ClassVisitor writer, String className,
ClassLoader loader) {
super(writer, className, loader);
}
/**
* Return a {@link MethodVisitor} that provides basic implementations for all
* methods - the easiest thing to do for methods that aren't abstract is to
* pretend that they are, but drive the adapter ourselves
*/
protected final AbstractWovenProxyMethodAdapter getWeavingMethodVisitor(int access, String name,
String desc, String signature, String[] exceptions, Method currentMethod,
String methodStaticFieldName, Type currentMethodDeclaringType,
boolean currentMethodDeclaringTypeIsInterface) {
boolean isDefaultMethod = currentMethodDeclaringTypeIsInterface &&
((access & (ACC_ABSTRACT | ACC_PUBLIC | ACC_STATIC)) == ACC_PUBLIC);
if ((access & ACC_ABSTRACT) != 0 || isDefaultMethod) {
access &= ~ACC_ABSTRACT;
return new WovenProxyAbstractMethodAdapter(cv.visitMethod(
access, name, desc, signature, exceptions), access, name, desc,
methodStaticFieldName, currentMethod, typeBeingWoven,
currentMethodDeclaringType, currentMethodDeclaringTypeIsInterface, isDefaultMethod);
} else {
return new WovenProxyConcreteMethodAdapter(cv.visitMethod(
access, name, desc, signature, exceptions), access, name, desc, exceptions,
methodStaticFieldName, currentMethod, typeBeingWoven,
currentMethodDeclaringType, currentMethodDeclaringTypeIsInterface);
}
}
}
| 7,855 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/weaving/WovenProxy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.weaving;
import java.util.concurrent.Callable;
import org.apache.aries.proxy.InvocationListener;
public interface WovenProxy {
/**
* @return true if this instance has a non null dispatcher or listener
*/
public boolean org_apache_aries_proxy_weaving_WovenProxy_isProxyInstance();
/**
* @return the dispatcher, or null if no dispatcher is set
*/
public Callable<Object> org_apache_aries_proxy_weaving_WovenProxy_unwrap();
/**
* @return A new proxy instance that can be used for delegation. Note that this object should
* not be used without setting a dispatcher!
*/
public WovenProxy org_apache_aries_proxy_weaving_WovenProxy_createNewProxyInstance(
Callable<Object> dispatcher, InvocationListener listener);
} | 7,856 |
0 | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy | Create_ds/aries/proxy/proxy-impl/src/main/java/org/apache/aries/proxy/synthesizer/Synthesizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.proxy.synthesizer;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
/**
* The Synthesizer class can be run from a java command with arguments
* of paths to class files that should be modified to have the synthetic
* attribute added.
*
*/
public class Synthesizer
{
/**
* This is the main method for running the Synthesizer
*
* @param args - String[] of file paths to class files
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
//add the synthetic modifier for each of the supplied args
for (String arg : args) {
FileInputStream classInStream = null;
ClassWriter writer = null;
try {
//read in the class
classInStream = new FileInputStream(arg);
ClassReader reader = new ClassReader(classInStream);
//make a ClassWriter constructed with the reader for speed
//since we are mostly just copying
//we just need to override the visit method so we can add
//the synthetic modifier, otherwise we use the methods in
//a standard writer
writer = new ClassWriter(reader, 0) ;
ClassVisitor cv = new CustomClassVisitor((ClassVisitor)writer);
//call accept on the reader to start the visits
//using the writer we created as the visitor
reader.accept(cv, 0);
} finally {
if (classInStream != null) classInStream.close();
}
FileOutputStream classOutStream = null;
try {
//write out the new bytes of the class file
classOutStream = new FileOutputStream(arg);
if (writer != null) classOutStream.write(writer.toByteArray());
} finally {
//close the OutputStream if it is still around
if (classOutStream != null) classOutStream.close();
}
}
}
public static class CustomClassVisitor extends ClassVisitor
{
public CustomClassVisitor( ClassVisitor cv)
{
super(Opcodes.ASM8, cv);
}
@Override
public void visit(int version, int access, String name, String signature,
String superName, String[] interfaces)
{
cv.visit(version, access | Opcodes.ACC_SYNTHETIC, name, signature, superName,
interfaces);
}
}
}
| 7,857 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries | Create_ds/aries/util/src/test/java/org/apache/aries/util/FragmentUtilsTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.aries.mocks.BundleMock;
import org.apache.aries.unittest.mocks.Skeleton;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
@SuppressWarnings("rawtypes")
public class FragmentUtilsTest {
private Bundle hostBundle;
@Before
public void setUp() throws Exception {
hostBundle = Skeleton.newMock(new BundleMock("scooby.doo",
new Hashtable<String, Object>()), Bundle.class);
}
@Test
public void testFragmentCreation() throws Exception {
Bundle exportBundle = makeBundleWithExports("export.bundle", "1.2.3",
"export.package;version=\"1.0.0\";uses:=\"foo.jar,bar.jar\";singleton:=true");
Dictionary fragmentHeaders = makeFragmentFromExportBundle(exportBundle)
.getHeaders();
assertNotNull("No headers in the fragment", fragmentHeaders);
assertEquals("Wrong symbolicName", "scooby.doo.test.fragment",
fragmentHeaders.get(Constants.BUNDLE_SYMBOLICNAME));
assertEquals("Wrong version", "0.0.0",
fragmentHeaders.get(Constants.BUNDLE_VERSION));
assertEquals("Wrong Bundle manifest version", "2",
fragmentHeaders.get(Constants.BUNDLE_MANIFESTVERSION));
assertEquals("Wrong Fragment host", "scooby.doo;bundle-version=\"0.0.0\"",
fragmentHeaders.get(Constants.FRAGMENT_HOST));
assertEquals("Wrong Bundle Name", "Test Fragment bundle",
fragmentHeaders.get(Constants.BUNDLE_NAME));
assertEquals(
"Wrong Imports",
"export.package;version=\"1.0.0\";bundle-symbolic-name=\"export.bundle\";bundle-version=\"[1.2.3,1.2.3]\"",
fragmentHeaders.get(Constants.IMPORT_PACKAGE));
}
private Bundle makeBundleWithExports(String symbolicName, String version,
String exports) {
Hashtable<String, Object> headers = new Hashtable<String, Object>();
headers.put(Constants.BUNDLE_VERSION, version);
headers.put(Constants.EXPORT_PACKAGE, exports);
Bundle exportBundle = Skeleton.newMock(new BundleMock(symbolicName,
headers), Bundle.class);
return exportBundle;
}
private Bundle makeFragmentFromExportBundle(Bundle exportBundle)
throws Exception {
FragmentBuilder builder = new FragmentBuilder(hostBundle, "test.fragment", "fragment");
builder.setName("Test Fragment bundle");
builder.addImportsFromExports(exportBundle);
return builder.install(hostBundle.getBundleContext());
}
@Test
public void testManifestAttributes() throws Exception {
String fakeExportsListNoExtras = "no.such.export,no.such.export2";
String fakeExportsListAttrOnly = "no.such.export;version=\"1.1.1\",no.such.export2;version=\"2.2.2\"";
String fakeExportsListDirOnly = "no.such.export;uses:=\"some.other.thing\",no.such.export2;include:=\"some.thing\"";
String fakeExportsListMixed = "no.such.export;version=\"1.1.1\";uses:=\"some.other.thing\",no.such.export2;include:=\"some.thing\"";
String fakeExportsListFunkyAttr = "no.such.export;attribute=\"a:=\",no.such.export2;attributeTwo=\"b:=\";include:=\"some.thing\"";
String expectedImportsListNoExtras = "no.such.export;bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\",no.such.export2;bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\"";
String expectedImportsListAttrOnly = "no.such.export;version=\"1.1.1\";bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\",no.such.export2;version=\"2.2.2\";bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\"";
String expectedImportsListDirOnly = "no.such.export;bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\",no.such.export2;bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\"";
String expectedImportsListMixed = "no.such.export;version=\"1.1.1\";bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\",no.such.export2;bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\"";
String expectedImportsListFunkyAttr = "no.such.export;attribute=\"a:=\";bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\",no.such.export2;attributeTwo=\"b:=\";bundle-symbolic-name=\"no.such.provider\";bundle-version=\"[1.1.1,1.1.1]\"";
Bundle exportBundle = makeBundleWithExports("no.such.provider",
"1.1.1", fakeExportsListNoExtras);
Dictionary headers = makeFragmentFromExportBundle(exportBundle)
.getHeaders();
assertEquals(
"Import list did not match expected value, expectedImportsListNoExtras",
expectedImportsListNoExtras, headers
.get(Constants.IMPORT_PACKAGE));
exportBundle = makeBundleWithExports("no.such.provider", "1.1.1",
fakeExportsListAttrOnly);
headers = makeFragmentFromExportBundle(exportBundle).getHeaders();
assertEquals(
"Import list did not match expected value, expectedImportsListAttrOnly",
expectedImportsListAttrOnly, headers
.get(Constants.IMPORT_PACKAGE));
exportBundle = makeBundleWithExports("no.such.provider", "1.1.1",
fakeExportsListDirOnly);
headers = makeFragmentFromExportBundle(exportBundle).getHeaders();
assertEquals(
"Import list did not match expected value, expectedImportsListDirOnly",
expectedImportsListDirOnly, headers
.get(Constants.IMPORT_PACKAGE));
exportBundle = makeBundleWithExports("no.such.provider", "1.1.1",
fakeExportsListMixed);
headers = makeFragmentFromExportBundle(exportBundle).getHeaders();
assertEquals(
"Import list did not match expected value, expectedImportsListMixed",
expectedImportsListMixed, headers.get(Constants.IMPORT_PACKAGE));
exportBundle = makeBundleWithExports("no.such.provider", "1.1.1",
fakeExportsListFunkyAttr);
headers = makeFragmentFromExportBundle(exportBundle).getHeaders();
assertEquals(
"Import list did not match expected value, expectedImportsListFunkyAttr",
expectedImportsListFunkyAttr, headers
.get(Constants.IMPORT_PACKAGE));
}
}
| 7,858 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries | Create_ds/aries/util/src/test/java/org/apache/aries/util/VersionRangeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.osgi.framework.Version;
public class VersionRangeTest
{
/**
* Test the version range created correctly
* @throws Exception
*/
@Test
public void testVersionRange() throws Exception {
String version1 = "[1.2.3, 4.5.6]";
String version2="(1, 2]";
String version3="[2,4)";
String version4="(1,2)";
String version5="2";
String version6 = "2.3";
String version7="[1.2.3.q, 2.3.4.p)";
String version8="1.2.2.5";
String version9="a.b.c";
String version10=null;
String version11="";
String version12="\"[1.2.3, 4.5.6]\"";
VersionRange vr = new VersionRange(version1);
assertEquals("The value is wrong", "1.2.3", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "4.5.6", vr.getMaximumVersion().toString());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = new VersionRange(version2);
assertEquals("The value is wrong", "1.0.0", vr.getMinimumVersion().toString());
assertTrue("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "2.0.0", vr.getMaximumVersion().toString());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = new VersionRange(version3);
assertEquals("The value is wrong", "2.0.0", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "4.0.0", vr.getMaximumVersion().toString());
assertTrue("The value is wrong", vr.isMaximumExclusive());
vr = new VersionRange(version4);
assertEquals("The value is wrong", "1.0.0", vr.getMinimumVersion().toString());
assertTrue("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "2.0.0", vr.getMaximumVersion().toString());
assertTrue("The value is wrong", vr.isMaximumExclusive());
vr = new VersionRange(version5);
assertEquals("The value is wrong", "2.0.0", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertNull("The value is wrong", vr.getMaximumVersion());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = new VersionRange(version6);
assertEquals("The value is wrong", "2.3.0", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertNull("The value is wrong", vr.getMaximumVersion());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = new VersionRange(version7);
assertEquals("The value is wrong", "1.2.3.q", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "2.3.4.p", vr.getMaximumVersion().toString());
assertTrue("The value is wrong", vr.isMaximumExclusive());
vr = new VersionRange(version8);
assertEquals("The value is wrong", "1.2.2.5", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertNull("The value is wrong", vr.getMaximumVersion());
assertFalse("The value is wrong", vr.isMaximumExclusive());
boolean exception = false;
try {
vr = new VersionRange(version9);
} catch (Exception e){
exception = true;
}
assertTrue("The value is wrong", exception);
boolean exceptionNull = false;
try {
vr = new VersionRange(version10);
} catch (Exception e){
exceptionNull = true;
}
assertTrue("The value is wrong", exceptionNull);
// empty version should be defaulted to >=0.0.0
vr = new VersionRange(version11);
assertEquals("The value is wrong", "0.0.0", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertNull("The value is wrong", vr.getMaximumVersion());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = new VersionRange(version12);
assertEquals("The value is wrong", "1.2.3", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "4.5.6", vr.getMaximumVersion().toString());
assertFalse("The value is wrong", vr.isMaximumExclusive());
}
@Test
public void testInvalidVersions() throws Exception
{
try {
new VersionRange("a");
assertTrue("Should have thrown an exception", false);
} catch (IllegalArgumentException e) {
}
try {
new VersionRange("[1.0.0,1.0.1]", true);
assertTrue("Should have thrown an exception", false);
} catch (IllegalArgumentException e) {
}
}
@Test
public void testExactVersion() throws Exception
{
VersionRange vr;
try {
vr = new VersionRange("[1.0.0, 2.0.0]", true);
fail("from 1 to 2 not excludsive is not an exact range");
} catch (IllegalArgumentException e) {
// expected
}
vr = new VersionRange("[1.0.0, 1.0.0]", true);
assertTrue(vr.isExactVersion());
try {
vr = new VersionRange("(1.0.0, 1.0.0]", true);
fail("from 1 (not including 1) to 1, is not valid");
} catch (IllegalArgumentException e) {
// expected
}
try {
vr = new VersionRange("[1.0.0, 1.0.0)", true);
fail("sfrom 1 to 1 (not including 1), is not valid");
} catch (IllegalArgumentException e) {
// expected
}
vr = new VersionRange("1.0.0", true);
assertTrue(vr.isExactVersion());
vr = new VersionRange("1.0.0", false);
assertFalse(vr.isExactVersion());
vr = new VersionRange("[1.0.0, 2.0.0]");
assertFalse(vr.isExactVersion());
vr = new VersionRange("[1.0.0, 1.0.0]");
assertTrue(vr.isExactVersion());
vr = new VersionRange("1.0.0", true);
assertEquals(new Version("1.0.0"), vr.getMinimumVersion());
assertTrue(vr.isExactVersion());
vr = new VersionRange("1.0.0", false);
assertEquals(new Version("1.0.0"), vr.getMinimumVersion());
assertNull(vr.getMaximumVersion());
assertFalse(vr.isExactVersion());
// don't throw any silly exceptions
vr = new VersionRange("[1.0.0,2.0.0)", false);
assertFalse(vr.isExactVersion());
vr = new VersionRange("[1.0.0, 2.0.0]");
assertFalse(vr.isExactVersion());
vr = new VersionRange("[1.0.0, 1.0.0]");
assertTrue(vr.isExactVersion());
}
@Test
public void testMatches()
{
VersionRange vr = new VersionRange("[1.0.0, 2.0.0]");
assertFalse(vr.matches(new Version(0,9,0)));
assertFalse(vr.matches(new Version(2,1,0)));
assertTrue(vr.matches(new Version(2,0,0)));
assertTrue(vr.matches(new Version(1,0,0)));
assertTrue(vr.matches(new Version(1,5,0)));
vr = new VersionRange("[1.0.0, 2.0.0)");
assertFalse(vr.matches(new Version(0,9,0)));
assertFalse(vr.matches(new Version(2,1,0)));
assertFalse(vr.matches(new Version(2,0,0)));
assertTrue(vr.matches(new Version(1,0,0)));
assertTrue(vr.matches(new Version(1,5,0)));
vr = new VersionRange("(1.0.0, 2.0.0)");
assertFalse(vr.matches(new Version(0,9,0)));
assertFalse(vr.matches(new Version(2,1,0)));
assertFalse(vr.matches(new Version(2,0,0)));
assertFalse(vr.matches(new Version(1,0,0)));
assertTrue(vr.matches(new Version(1,5,0)));
vr = new VersionRange("[1.0.0, 1.0.0]");
assertFalse(vr.matches(new Version(0,9,0)));
assertFalse(vr.matches(new Version(2,0,0)));
assertTrue(vr.matches(new Version(1,0,0)));
assertFalse(vr.matches(new Version(1,5,0)));
assertFalse(vr.matches(new Version(1,9,9)));
}
@Test
public void testIntersectVersionRange_Valid1()
{
VersionRange v1 = new VersionRange("[1.0.0,3.0.0]");
VersionRange v2 = new VersionRange("[2.0.0,3.0.0)");
VersionRange result = v1.intersect(v2);
assertNotNull(result);
assertEquals("[2.0.0,3.0.0)", result.toString());
}
@Test
public void testIntersectVersionRange_Valid2()
{
VersionRange v1 = new VersionRange("[1.0.0,3.0.0)");
VersionRange v2 = new VersionRange("(2.0.0,3.0.0]");
VersionRange result = v1.intersect(v2);
assertNotNull(result);
assertEquals("(2.0.0,3.0.0)", result.toString());
}
@Test
public void testIntersectVersionRange_Valid3()
{
VersionRange v1 = new VersionRange("[2.0.0,2.0.0]");
VersionRange v2 = new VersionRange("[1.0.0,3.0.0]");
VersionRange result = v1.intersect(v2);
assertNotNull(result);
assertEquals("[2.0.0,2.0.0]", result.toString());
}
@Test
public void testIntersectVersionRange_Invalid1()
{
VersionRange v1 = new VersionRange("[1.0.0,2.0.0]");
VersionRange v2 = new VersionRange("(2.0.0,3.0.0]");
VersionRange result = v1.intersect(v2);
assertNull(result);
}
@Test
public void testIntersectVersionRange_Invalid2()
{
VersionRange v1 = new VersionRange("[1.0.0,2.0.0)");
VersionRange v2 = new VersionRange("[2.0.0,3.0.0]");
VersionRange result = v1.intersect(v2);
assertNull(result);
}
@Test
public void testIntersectVersionRange_Invalid3()
{
VersionRange v1 = new VersionRange("[1.0.0,1.0.0]");
VersionRange v2 = new VersionRange("[2.0.0,2.0.0]");
VersionRange result = v1.intersect(v2);
assertNull(result);
}
} | 7,859 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries | Create_ds/aries/util/src/test/java/org/apache/aries/util/BundleToClassLoaderAdapterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.Skeleton;
import org.apache.aries.util.internal.BundleToClassLoaderAdapter;
import org.junit.Test;
import org.osgi.framework.Bundle;
import static org.junit.Assert.assertEquals;
public class BundleToClassLoaderAdapterTest {
@Test(expected=ClassNotFoundException.class)
public void testInheritance() throws Exception {
ClassLoader testLoader = new ClassLoader(makeSUT(false)) {
};
testLoader.loadClass(Bundle.class.getName());
}
@Test
public void testInheritancePositive() throws Exception {
ClassLoader testLoader = new ClassLoader(makeSUT(true)) {
};
assertEquals(Bundle.class, testLoader.loadClass(Bundle.class.getName()));
}
@Test
public void testStraightLoadClass() throws Exception {
assertEquals(Bundle.class, makeSUT(true).loadClass(Bundle.class.getName()));
}
@Test(expected=ClassNotFoundException.class)
public void testLoadClassFailure() throws Exception {
makeSUT(false).loadClass(Bundle.class.getName());
}
@Test
public void testLoadWithResolve() throws Exception {
assertEquals(Bundle.class, makeSUT(true).loadClass(Bundle.class.getName(), true));
}
private BundleToClassLoaderAdapter makeSUT(boolean includeBundleClass) {
Bundle bundle = Skeleton.newMock(Bundle.class);
if (includeBundleClass) {
Skeleton.getSkeleton(bundle).setReturnValue(new MethodCall(Bundle.class, "loadClass", Bundle.class.getName()), Bundle.class);
} else {
Skeleton.getSkeleton(bundle).setThrows(new MethodCall(Bundle.class, "loadClass", Bundle.class.getName()), new ClassNotFoundException());
}
return new BundleToClassLoaderAdapter(bundle);
}
}
| 7,860 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries | Create_ds/aries/util/src/test/java/org/apache/aries/util/SingleServiceTrackerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.aries.mocks.BundleContextMock;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.Skeleton;
import org.apache.aries.util.tracker.SingleServiceTracker;
import org.apache.aries.util.tracker.SingleServiceTracker.SingleServiceListener;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import static org.junit.Assert.*;
public class SingleServiceTrackerTest {
private BundleContext ctx;
private SingleServiceTracker<String> sut;
private SingleServiceTracker.SingleServiceListener listener;
@Before
public void setup() {
ctx = Skeleton.newMock(new BundleContextMock(), BundleContext.class);
}
@After
public void teardown() {
BundleContextMock.clear();
}
private void createSut() {
createSut(null);
}
private void createSut(String filter) {
listener = Skeleton.newMock(SingleServiceListener.class);
try {
sut = new SingleServiceTracker<String>(ctx, String.class, filter, listener);
} catch (InvalidSyntaxException e) {
throw new RuntimeException(e);
}
sut.open();
}
@Test
public void testBeforeTheFactService() {
ctx.registerService("java.lang.String", "uno", null);
createSut();
Skeleton.getSkeleton(listener).assertCalled(Arrays.asList(new MethodCall(SingleServiceListener.class, "serviceFound")), true);
assertEquals("uno", sut.getService());
}
@Test
public void testBeforeTheFactServiceDoubleRegistration() {
testBeforeTheFactService();
ctx.registerService("java.lang.String", "due", null);
Skeleton.getSkeleton(listener).assertCalled(Arrays.asList(new MethodCall(SingleServiceListener.class, "serviceFound")), true);
assertEquals("uno", sut.getService());
}
@Test
public void testBeforeTheFactChoice() {
ctx.registerService("java.lang.String", "uno", null);
ctx.registerService("java.lang.String", "due", null);
createSut();
Skeleton.getSkeleton(listener).assertCalled(Arrays.asList(new MethodCall(SingleServiceListener.class, "serviceFound")), true);
assertEquals("uno", sut.getService());
}
@Test
public void testBeforeTheFactChoiceWithPropertiesAndFilterWithFirstMatch() {
Dictionary<String, String> props = new Hashtable<String, String>();
props.put("foo", "bar");
ctx.registerService("java.lang.String", "uno", props);
ctx.registerService("java.lang.String", "due", null);
createSut("(foo=bar)");
Skeleton.getSkeleton(listener).assertCalled(Arrays.asList(new MethodCall(SingleServiceListener.class, "serviceFound")), true);
assertEquals("uno", sut.getService());
}
@Test
public void testBeforeTheFactChoiceWithPropertiesAndFilterWithSecondMatch() {
Dictionary<String, String> props = new Hashtable<String, String>();
props.put("foo", "bar");
ctx.registerService("java.lang.String", "uno", null);
ctx.registerService("java.lang.String", "due", props);
createSut("(foo=bar)");
Skeleton.getSkeleton(listener).assertCalled(Arrays.asList(new MethodCall(SingleServiceListener.class, "serviceFound")), true);
assertEquals("due", sut.getService());
}
@Test
public void testAfterTheFactService()
{
createSut();
Skeleton.getSkeleton(listener).assertSkeletonNotCalled();
ctx.registerService("java.lang.String", "uno", null);
Skeleton.getSkeleton(listener).assertCalled(new MethodCall(SingleServiceListener.class, "serviceFound"));
assertEquals("uno", sut.getService());
}
@Test
public void testDoubleRegistration() {
testAfterTheFactService();
Skeleton.getSkeleton(listener).clearMethodCalls();
ctx.registerService("java.lang.String", "due", null);
Skeleton.getSkeleton(listener).assertSkeletonNotCalled();
assertEquals("uno", sut.getService());
}
@Test
public void testAfterTheFactChoiceWithPropertiesAndFilterWithSecondMatch() {
createSut("(foo=bar)");
Skeleton.getSkeleton(listener).assertSkeletonNotCalled();
ctx.registerService("java.lang.String", "uno", null);
Skeleton.getSkeleton(listener).assertSkeletonNotCalled();
Dictionary<String, String> props = new Hashtable<String, String>();
props.put("foo", "bar");
ctx.registerService("java.lang.String", "due", props);
Skeleton.getSkeleton(listener).assertCalled(Arrays.asList(new MethodCall(SingleServiceListener.class, "serviceFound")), true);
assertEquals("due", sut.getService());
}
@Test
public void testRegistrationWhileClosed() {
createSut();
sut.close();
ctx.registerService("java.lang.String", "uno", null);
Skeleton.getSkeleton(listener).assertSkeletonNotCalled();
assertNull(sut.getService());
}
}
| 7,861 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries | Create_ds/aries/util/src/test/java/org/apache/aries/util/RecursiveBundleTrackerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.Skeleton;
import org.apache.aries.util.tracker.BundleTrackerFactory;
import org.apache.aries.util.tracker.InternalRecursiveBundleTracker;
import org.apache.aries.util.tracker.RecursiveBundleTracker;
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.BundleEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.osgi.service.framework.CompositeBundle;
import org.osgi.util.tracker.BundleTrackerCustomizer;
import static org.junit.Assert.*;
public class RecursiveBundleTrackerTest {
BundleContext context;
InternalRecursiveBundleTracker sut;
@Before
public void setup() {
context = Skeleton.newMock(BundleContext.class);
Skeleton.getSkeleton(context).setReturnValue(
new MethodCall(BundleContext.class, "getServiceReference", "org.osgi.service.framework.CompositeBundleFactory"),
Skeleton.newMock(ServiceReference.class));
}
@After
public void closeTrackes() {
BundleTrackerFactory.unregisterAndCloseBundleTracker("test");
}
@Test
public void testCompositeLifeCycle() {
makeSUT();
CompositeBundle cb = composite("test.composite", "1.0.0");
assertNoTrackers();
// full lifecycle
sut.addingBundle(cb, new BundleEvent(BundleEvent.INSTALLED, cb));
assertTracker(cb);
sut.modifiedBundle(cb, new BundleEvent(BundleEvent.RESOLVED, cb), cb);
sut.modifiedBundle(cb, new BundleEvent(BundleEvent.STARTING, cb), cb);
sut.modifiedBundle(cb, new BundleEvent(BundleEvent.STARTED, cb), cb);
sut.modifiedBundle(cb, new BundleEvent(BundleEvent.STOPPING, cb), cb);
sut.removedBundle(cb, new BundleEvent(BundleEvent.STOPPED, cb), cb);
assertNoTrackers();
// short lifecycle
sut.addingBundle(cb, new BundleEvent(BundleEvent.INSTALLED, cb));
assertTracker(cb);
sut.modifiedBundle(cb, new BundleEvent(BundleEvent.RESOLVED, cb), cb);
sut.removedBundle(cb, new BundleEvent(BundleEvent.UNRESOLVED, cb), cb);
assertNoTrackers();
// shortest lifecycle
sut.addingBundle(cb, new BundleEvent(BundleEvent.INSTALLED, cb));
assertTracker(cb);
sut.removedBundle(cb, new BundleEvent(BundleEvent.UNINSTALLED, cb), cb);
assertNoTrackers();
}
@Test(expected=IllegalArgumentException.class)
public void testMissingStopping() {
new RecursiveBundleTracker(null, Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.ACTIVE, null);
}
@Test(expected=IllegalArgumentException.class)
public void testMissingStarting() {
new RecursiveBundleTracker(null, Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE | Bundle.STOPPING, null);
}
@Test(expected=IllegalArgumentException.class)
public void testMissingInstalled() {
new RecursiveBundleTracker(null, Bundle.RESOLVED | Bundle.STARTING | Bundle.ACTIVE | Bundle.STOPPING, null);
}
private void assertNoTrackers() {
assertTrue(BundleTrackerFactory.getAllBundleTracker().isEmpty());
}
private void assertTracker(CompositeBundle cb) {
assertEquals(1, BundleTrackerFactory.getAllBundleTracker().size());
assertEquals(1, BundleTrackerFactory.getBundleTrackerList(cb.getSymbolicName()+"_"+cb.getVersion()).size());
}
@SuppressWarnings("rawtypes")
private void makeSUT() {
BundleTrackerCustomizer customizer = Skeleton.newMock(BundleTrackerCustomizer.class);
sut = new InternalRecursiveBundleTracker(context,
Bundle.INSTALLED | Bundle.STARTING | Bundle.ACTIVE | Bundle.STOPPING, customizer, true);
sut.open();
}
private CompositeBundle composite(String symbolicName, String version) {
CompositeBundle cb = Skeleton.newMock(CompositeBundle.class);
Skeleton cbSkel = Skeleton.getSkeleton(cb);
cbSkel.setReturnValue(new MethodCall(CompositeBundle.class, "getSymbolicName"), symbolicName);
cbSkel.setReturnValue(new MethodCall(CompositeBundle.class, "getVersion"), new Version(version));
return cb;
}
}
| 7,862 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries/util | Create_ds/aries/util/src/test/java/org/apache/aries/util/manifest/BundleManifestTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.manifest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.aries.util.io.IOUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class BundleManifestTest
{
private static final String EXPECTED_VERSION = "1.0.0";
private static final String EXPECTED_SYMBOLIC_NAME = "com.ibm.test";
private static File BUNDLE_WITHOUT_NAME_HEADER;
private static File BUNDLE_WITH_NAME_HEADER;
@BeforeClass
public static void setup() throws Exception
{
BUNDLE_WITHOUT_NAME_HEADER = new File ("./bundleManifestTest/nonExploded.jar");
BUNDLE_WITHOUT_NAME_HEADER.getParentFile().mkdirs();
BUNDLE_WITH_NAME_HEADER = new File ("./bundleManifestTest/nonExplodedWithName.jar");
BUNDLE_WITH_NAME_HEADER.getParentFile().mkdirs();
createZippedJar(BUNDLE_WITHOUT_NAME_HEADER, "exploded.jar");
createZippedJar(BUNDLE_WITH_NAME_HEADER, "exploded-jar-with-name.jar");
}
private static void createZippedJar(File outputFile, String inputFolderName) throws FileNotFoundException, IOException {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
ZipEntry ze = new ZipEntry("META-INF/");
out.putNextEntry(ze);
File f = new File("../src/test/resources/bundles/" + inputFolderName + "/META-INF/beforeManifest.file");
ze = new ZipEntry("META-INF/beforeManifest.file");
ze.setSize(f.length());
out.putNextEntry(ze);
IOUtils.copy(new FileInputStream(f), out);
f = new File("../src/test/resources/bundles/" + inputFolderName + "/META-INF/MANIFEST.MF");
ze = new ZipEntry("META-INF/MANIFEST.MF");
ze.setSize(f.length());
out.putNextEntry(ze);
IOUtils.copy(new FileInputStream(f), out);
out.close();
}
@AfterClass
public static void cleanup()
{
IOUtils.deleteRecursive(new File("bundleManifestTest/"));
}
@Test
public void testExploded()
{
BundleManifest sut = BundleManifest.fromBundle(new File("../src/test/resources/bundles/exploded.jar"));
assertEquals(EXPECTED_SYMBOLIC_NAME, sut.getSymbolicName());
assertEquals(EXPECTED_VERSION, sut.getVersion().toString());
}
@Test
public void testExplodedFromIDirectory()
{
BundleManifest sut = BundleManifest.fromBundle(FileSystem.getFSRoot(
new File("../src/test/resources/bundles/exploded.jar")));
assertEquals(EXPECTED_SYMBOLIC_NAME, sut.getSymbolicName());
assertEquals(EXPECTED_VERSION, sut.getVersion().toString());
}
@Test
public void testExplodedWithName()
{
BundleManifest sut = BundleManifest.fromBundle(new File("../src/test/resources/bundles/exploded-jar-with-name.jar"));
assertEquals(EXPECTED_SYMBOLIC_NAME, sut.getSymbolicName());
assertEquals(EXPECTED_VERSION, sut.getVersion().toString());
}
@Test
public void testExplodedWithNameFromIDirectory()
{
BundleManifest sut = BundleManifest.fromBundle(FileSystem.getFSRoot(
new File("../src/test/resources/bundles/exploded-jar-with-name.jar")));
assertEquals(EXPECTED_SYMBOLIC_NAME, sut.getSymbolicName());
assertEquals(EXPECTED_VERSION, sut.getVersion().toString());
}
@Test
public void testZip() throws Exception
{
// make sure that the manifest is not the first file in the jar archive
JarInputStream jarIs = new JarInputStream(new FileInputStream(BUNDLE_WITHOUT_NAME_HEADER));
assertNull(jarIs.getManifest());
jarIs.close();
BundleManifest sut = BundleManifest.fromBundle(BUNDLE_WITHOUT_NAME_HEADER);
assertEquals(EXPECTED_SYMBOLIC_NAME, sut.getSymbolicName());
assertEquals(EXPECTED_VERSION, sut.getVersion().toString());
}
@Test
public void testZipFromIDirectory() throws Exception
{
// make sure that the manifest is not the first file in the jar archive
JarInputStream jarIs = new JarInputStream(new FileInputStream(BUNDLE_WITHOUT_NAME_HEADER));
assertNull(jarIs.getManifest());
jarIs.close();
BundleManifest sut = BundleManifest.fromBundle(
FileSystem.getFSRoot(BUNDLE_WITHOUT_NAME_HEADER));
assertEquals(EXPECTED_SYMBOLIC_NAME, sut.getSymbolicName());
assertEquals(EXPECTED_VERSION, sut.getVersion().toString());
}
@Test
public void testZipWithName() throws Exception
{
// make sure that the manifest is not the first file in the jar archive
JarInputStream jarIs = new JarInputStream(new FileInputStream(BUNDLE_WITH_NAME_HEADER));
assertNull(jarIs.getManifest());
jarIs.close();
BundleManifest sut = BundleManifest.fromBundle(BUNDLE_WITH_NAME_HEADER);
assertEquals(EXPECTED_SYMBOLIC_NAME, sut.getSymbolicName());
assertEquals(EXPECTED_VERSION, sut.getVersion().toString());
}
@Test
public void testZipWithNameFromIDirectory() throws Exception
{
// make sure that the manifest is not the first file in the jar archive
JarInputStream jarIs = new JarInputStream(new FileInputStream(BUNDLE_WITH_NAME_HEADER));
assertNull(jarIs.getManifest());
jarIs.close();
BundleManifest sut = BundleManifest.fromBundle(
FileSystem.getFSRoot(BUNDLE_WITH_NAME_HEADER));
assertEquals(EXPECTED_SYMBOLIC_NAME, sut.getSymbolicName());
assertEquals(EXPECTED_VERSION, sut.getVersion().toString());
}
}
| 7,863 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries/util | Create_ds/aries/util/src/test/java/org/apache/aries/util/manifest/ManifestHeaderProcessorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.manifest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.aries.util.VersionRange;
import org.apache.aries.util.manifest.ManifestHeaderProcessor.GenericMetadata;
import org.apache.aries.util.manifest.ManifestHeaderProcessor.NameValuePair;
import org.junit.Test;
import org.osgi.framework.Version;
public class ManifestHeaderProcessorTest
{
@Test
public void testNameValuePair() throws Exception {
HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put("some", "value");
NameValuePair nvp = new NameValuePair("key", attrs);
assertEquals("The name value pair is not set properly.", nvp.getName(), "key");
assertEquals("The value is not set properly.", nvp.getAttributes().get("some"), "value");
attrs = new HashMap<String, String>();
attrs.put("some", "value");
NameValuePair anotherNvp = new NameValuePair("key", attrs);
assertEquals("The two objects of NameValuePair is not equal.", nvp, anotherNvp);
nvp.setName("newKey");
attrs = new HashMap<String, String>();
attrs.put("some", "newValue");
nvp.setAttributes(attrs);
assertEquals("The name value pair is not set properly.", nvp.getName(), "newKey");
assertEquals("The value is not set properly.", nvp.getAttributes().get("some"), "newValue");
Map<String,String> nvm1 = new HashMap<String,String>();
nvm1.put("a","b");
nvm1.put("c","d");
Map<String,String> nvm2 = new HashMap<String,String>();
nvm2.put("c","d");
nvm2.put("a","b");
assertEquals("The maps are not equal.", nvm1, nvm2);
nvm2.put("e","f");
assertNotSame("The maps are the same.", nvm1, nvm2);
NameValuePair nvp1 = new NameValuePair("one",nvm1);
NameValuePair nvp2 = new NameValuePair("one",nvm2);
assertNotSame("The pairs are identical ",nvp1,nvp2);
nvm1.put("e","f");
assertEquals("The pairs are not equal.", nvp1,nvp2);
List<NameValuePair> bundleInfoList1 = new ArrayList<NameValuePair>();
bundleInfoList1.add(nvp1);
List<NameValuePair> bundleInfoList2 = new ArrayList<NameValuePair>();
bundleInfoList2.add(nvp1);
bundleInfoList1.removeAll(bundleInfoList2);
assertEquals("The List should be empty", bundleInfoList1.isEmpty(), true);
assertNotSame("The two objects of NameValuePair is not equal.", nvp, anotherNvp);
}
/**
* Test the Bundle manifest header entry of
* Bundle-SymbolicName: com.acme.foo;singleton:=true
*/
@Test
public void testParseBundleSymbolicName()
{
String bundleSymbolicNameEntry = "com.acme.foo;singleton:=true;fragment-attachment:=always";
NameValuePair nvp = ManifestHeaderProcessor.parseBundleSymbolicName(bundleSymbolicNameEntry);
assertEquals("The symbolic name is wrong.", nvp.getName(), "com.acme.foo");
assertEquals("The value is wrong.", "true", nvp.getAttributes().get("singleton:") );
assertEquals("The directive is wrong.", "always", nvp.getAttributes().get("fragment-attachment:") );
String bundleSymbolicNameEntry2 = "com.acme.foo";
NameValuePair nvp2 = ManifestHeaderProcessor.parseBundleSymbolicName(bundleSymbolicNameEntry2);
assertEquals("The symbolic name is wrong.", nvp2.getName(), "com.acme.foo");
}
/**
* Test the import package and import service
* Import-Package: com.acme.foo;come.acm,e.bar;version="[1.23,1.24.5]";resolution:=mandatory
*/
@Test
public void testParseImportString()
{
String importPackage = "com.acme.foo,come.acm.e.bar;version=\"[1.23,1.24.5]\";resolution:=mandatory;company=\"ACME\",a.b.c;version=1.2.3;company=com";
Map<String, Map<String, String>> importPackageReturn = ManifestHeaderProcessor.parseImportString(importPackage);
assertTrue("The package is not set.", importPackageReturn.containsKey("com.acme.foo"));
assertTrue("The package is not set.", importPackageReturn.containsKey("come.acm.e.bar"));
assertTrue("The package is not set.", importPackageReturn.containsKey("come.acm.e.bar"));
assertTrue("The package is not set.", importPackageReturn.containsKey("a.b.c"));
assertTrue("The package should not contain any attributes.", importPackageReturn.get("com.acme.foo").isEmpty());
assertEquals("The directive is not set correctly.", "[1.23,1.24.5]", importPackageReturn.get("come.acm.e.bar").get("version"));
assertEquals("The directive is not set correctly.", "mandatory", importPackageReturn.get("come.acm.e.bar").get("resolution:"));
assertEquals("The directive is not set correctly.", "ACME", importPackageReturn.get("come.acm.e.bar").get("company"));
assertEquals("The directive is not set correctly.", "1.2.3", importPackageReturn.get("a.b.c").get("version"));
assertEquals("The directive is not set correctly.", "com", importPackageReturn.get("a.b.c").get("company"));
importPackage="com.acme.foo";
assertTrue("The package is not set.", importPackageReturn.containsKey("com.acme.foo"));
assertTrue("The package should not contain any attributes.", importPackageReturn.get("com.acme.foo").isEmpty());
importPackage="com.acme.foo;com.acme.bar;version=2";
Map<String, Map<String, String>> importPackageReturn2 = ManifestHeaderProcessor.parseImportString(importPackage);
assertTrue("The package is not set.", importPackageReturn2.containsKey("com.acme.foo"));
assertTrue("The package is not set.", importPackageReturn2.containsKey("com.acme.bar"));
assertEquals("The directive is not set correctly.", "2", importPackageReturn2.get("com.acme.foo").get("version"));
assertEquals("The directive is not set correctly.", "2", importPackageReturn2.get("com.acme.bar").get("version"));
}
@Test
public void testParseExportString()
{
String exportPackage = "com.acme.foo,com.acme.bar;version=1,com.acme.bar;version=2;uses:=\"a.b.c,d.e.f\";security=false;mandatory:=security";
List<NameValuePair> exportPackageReturn = ManifestHeaderProcessor.parseExportString(exportPackage);
int i =0;
assertEquals("The number of the packages is wrong.", 3, exportPackageReturn.size());
for (NameValuePair nvp : exportPackageReturn) {
if (nvp.getName().equals("com.acme.foo")) {
i++;
assertTrue("The directive or attribute should not be set.", nvp.getAttributes().isEmpty() );
} else if ((nvp.getName().equals("com.acme.bar")) && ("2".equals(nvp.getAttributes().get("version")))) {
i++;
assertEquals("The directive is wrong.", "a.b.c,d.e.f", nvp.getAttributes().get("uses:"));
assertEquals("The directive is wrong.", "false", nvp.getAttributes().get("security"));
assertEquals("The directive is wrong.", "security", nvp.getAttributes().get("mandatory:"));
} else if ((nvp.getName().equals("com.acme.bar")) && ("1".equals(nvp.getAttributes().get("version")))) {
i++;
assertNull("The directive is wrong.", nvp.getAttributes().get("uses:"));
assertNull("The directive is wrong.", nvp.getAttributes().get("security"));
assertNull("The directive is wrong.", nvp.getAttributes().get("mandatory:"));
}
}
// make sure all three packages stored
assertEquals("The names of the packages are wrong.", 3, i);
exportPackage = "com.acme.foo";
exportPackageReturn = ManifestHeaderProcessor.parseExportString(exportPackage);
int k =0;
assertEquals("The number of the packages is wrong.", 1, exportPackageReturn.size());
for (NameValuePair nvp : exportPackageReturn) {
if (nvp.getName().equals("com.acme.foo")) {
k++;
assertTrue("The directive or attribute should not be set.", nvp.getAttributes().isEmpty() );
}
}
assertEquals("The names of the packages are wrong.", 1, k);
// test multiple packages separated by ;
exportPackage = "com.acme.foo;com.acme.bar;version=\"2\";resolution:=optional";
exportPackageReturn = ManifestHeaderProcessor.parseExportString(exportPackage);
k =0;
assertEquals("The number of the packages is wrong.", 2, exportPackageReturn.size());
for (NameValuePair nvp : exportPackageReturn) {
if (nvp.getName().equals("com.acme.foo")) {
k++;
assertEquals("The attribute is wrong.", "2", nvp.getAttributes().get("version") );
assertEquals("The attribute is wrong.", "optional", nvp.getAttributes().get("resolution:"));
} else if (nvp.getName().equals("com.acme.bar")) {
k++;
assertEquals("The attribute is wrong.", "2", nvp.getAttributes().get("version") );
assertEquals("The attribute is wrong.", "optional", nvp.getAttributes().get("resolution:"));
}
}
assertEquals("The names of the packages are wrong.", 2, k);
exportPackageReturn = ManifestHeaderProcessor.parseExportString("some.export.with.space.in;directive := spacey");
assertEquals(exportPackageReturn.toString(), "spacey", exportPackageReturn.get(0).getAttributes().get("directive:"));
}
@Test
public void testExportMandatoryAttributes() {
String exportPackage = "com.acme.foo,com.acme.bar;version=2;company=dodo;security=false;mandatory:=\"security,company\"";
List<NameValuePair> exportPackageReturn = ManifestHeaderProcessor.parseExportString(exportPackage);
int i =0;
assertEquals("The number of the packages is wrong.", 2, exportPackageReturn.size());
for (NameValuePair nvp : exportPackageReturn) {
if (nvp.getName().equals("com.acme.foo")) {
i++;
assertTrue("The directive or attribute should not be set.", nvp.getAttributes().isEmpty() );
} else if ((nvp.getName().equals("com.acme.bar")) && ("2".equals(nvp.getAttributes().get("version")))) {
i++;
assertEquals("The directive is wrong.", "dodo", nvp.getAttributes().get("company"));
assertEquals("The directive is wrong.", "false", nvp.getAttributes().get("security"));
assertEquals("The directive is wrong.", "security,company", nvp.getAttributes().get("mandatory:"));
}
}
// make sure all three packages stored
assertEquals("The names of the packages are wrong.", 2, i);
}
private String createExpectedFilter(Map<String, String> values, String ... parts)
{
StringBuilder builder = new StringBuilder(parts[0]);
for (Map.Entry<String, String> entry : values.entrySet()) {
if ("version".equals(entry.getKey())) builder.append(parts[2]);
else if ("company".equals(entry.getKey())) builder.append(parts[1]);
}
builder.append(parts[3]);
return builder.toString();
}
/**
* Test the filter generated correctly
* @throws Exception
*/
@Test
public void testGenerateFilter() throws Exception {
Map<String, String> valueMap = new HashMap<String, String>();
valueMap.put("version", "[1.2, 2.3]");
valueMap.put("resulution:", "mandatory");
valueMap.put("company", "com");
String filter = ManifestHeaderProcessor.generateFilter("symbolic-name", "com.ibm.foo", valueMap);
String expected = createExpectedFilter(valueMap, "(&(symbolic-name=com.ibm.foo)", "(company=com)", "(version>=1.2.0)(version<=2.3.0)", "(mandatory:<*company))");
assertEquals("The filter is wrong.", expected, filter );
valueMap.clear();
valueMap.put("version", "(1.2, 2.3]");
valueMap.put("resulution:", "mandatory");
valueMap.put("company", "com");
filter = ManifestHeaderProcessor.generateFilter("symbolic-name", "com.ibm.foo", valueMap);
expected = createExpectedFilter(valueMap, "(&(symbolic-name=com.ibm.foo)", "(company=com)", "(version>=1.2.0)(version<=2.3.0)(!(version=1.2.0))", "(mandatory:<*company))");
assertEquals("The filter is wrong.", expected, filter );
valueMap.clear();
valueMap.put("version", "(1.2, 2.3)");
valueMap.put("resulution:", "mandatory");
valueMap.put("company", "com");
filter = ManifestHeaderProcessor.generateFilter("symbolic-name", "com.ibm.foo", valueMap);
expected = createExpectedFilter(valueMap, "(&(symbolic-name=com.ibm.foo)", "(company=com)", "(version>=1.2.0)(version<=2.3.0)(!(version=1.2.0))(!(version=2.3.0))", "(mandatory:<*company))");
assertEquals("The filter is wrong.", expected, filter );
valueMap.clear();
valueMap.put("version", "1.2");
valueMap.put("resulution:", "mandatory");
valueMap.put("company", "com");
filter = ManifestHeaderProcessor.generateFilter("symbolic-name", "com.ibm.foo", valueMap);
expected = createExpectedFilter(valueMap, "(&(symbolic-name=com.ibm.foo)", "(company=com)", "(version>=1.2.0)", "(mandatory:<*company))");
assertEquals("The filter is wrong.", expected, filter );
valueMap.clear();
valueMap.put("resulution:", "mandatory");
valueMap.put("company", "com");
filter = ManifestHeaderProcessor.generateFilter("symbolic-name", "com.ibm.foo", valueMap);
expected = createExpectedFilter(valueMap, "(&(symbolic-name=com.ibm.foo)", "(company=com)", "", "(mandatory:<*company))");
assertEquals("The filter is wrong.", expected, filter );
}
/**
* Test the version range created correctly
* @throws Exception
*/
@Test
public void testVersionRange() throws Exception {
String version1 = "[1.2.3, 4.5.6]";
String version2="(1, 2]";
String version3="[2,4)";
String version4="(1,2)";
String version5="2";
String version6 = "2.3";
String version7="[1.2.3.q, 2.3.4.p)";
String version8="1.2.2.5";
String version9="a.b.c";
String version10=null;
String version11="";
String version12="\"[1.2.3, 4.5.6]\"";
VersionRange vr = ManifestHeaderProcessor.parseVersionRange(version1);
assertEquals("The value is wrong", "1.2.3", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "4.5.6", vr.getMaximumVersion().toString());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = ManifestHeaderProcessor.parseVersionRange(version2);
assertEquals("The value is wrong", "1.0.0", vr.getMinimumVersion().toString());
assertTrue("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "2.0.0", vr.getMaximumVersion().toString());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = ManifestHeaderProcessor.parseVersionRange(version3);
assertEquals("The value is wrong", "2.0.0", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "4.0.0", vr.getMaximumVersion().toString());
assertTrue("The value is wrong", vr.isMaximumExclusive());
vr = ManifestHeaderProcessor.parseVersionRange(version4);
assertEquals("The value is wrong", "1.0.0", vr.getMinimumVersion().toString());
assertTrue("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "2.0.0", vr.getMaximumVersion().toString());
assertTrue("The value is wrong", vr.isMaximumExclusive());
vr = ManifestHeaderProcessor.parseVersionRange(version5);
assertEquals("The value is wrong", "2.0.0", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertNull("The value is wrong", vr.getMaximumVersion());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = ManifestHeaderProcessor.parseVersionRange(version6);
assertEquals("The value is wrong", "2.3.0", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertNull("The value is wrong", vr.getMaximumVersion());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = ManifestHeaderProcessor.parseVersionRange(version7);
assertEquals("The value is wrong", "1.2.3.q", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "2.3.4.p", vr.getMaximumVersion().toString());
assertTrue("The value is wrong", vr.isMaximumExclusive());
vr = ManifestHeaderProcessor.parseVersionRange(version8);
assertEquals("The value is wrong", "1.2.2.5", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertNull("The value is wrong", vr.getMaximumVersion());
assertFalse("The value is wrong", vr.isMaximumExclusive());
boolean exception = false;
try {
vr = ManifestHeaderProcessor.parseVersionRange(version9);
} catch (Exception e){
exception = true;
}
assertTrue("The value is wrong", exception);
boolean exceptionNull = false;
try {
vr = ManifestHeaderProcessor.parseVersionRange(version10);
} catch (Exception e){
exceptionNull = true;
}
assertTrue("The value is wrong", exceptionNull);
// empty version should be defaulted to >=0.0.0
vr = ManifestHeaderProcessor.parseVersionRange(version11);
assertEquals("The value is wrong", "0.0.0", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertNull("The value is wrong", vr.getMaximumVersion());
assertFalse("The value is wrong", vr.isMaximumExclusive());
vr = ManifestHeaderProcessor.parseVersionRange(version12);
assertEquals("The value is wrong", "1.2.3", vr.getMinimumVersion().toString());
assertFalse("The value is wrong", vr.isMinimumExclusive());
assertEquals("The value is wrong", "4.5.6", vr.getMaximumVersion().toString());
assertFalse("The value is wrong", vr.isMaximumExclusive());
}
@Test
public void testInvalidVersions() throws Exception
{
try {
ManifestHeaderProcessor.parseVersionRange("a");
assertTrue("Should have thrown an exception", false);
} catch (IllegalArgumentException e) {
// assertEquals(MessageUtil.getMessage("APPUTILS0009E", "a"), e.getMessage());
}
try {
ManifestHeaderProcessor.parseVersionRange("[1.0.0,1.0.1]", true);
assertTrue("Should have thrown an exception", false);
} catch (IllegalArgumentException e) {
// assertEquals(MessageUtil.getMessage("APPUTILS0011E", "[1.0.0,1.0.1]"), e.getMessage());
}
}
@Test
public void testSplit() throws Exception {
String export = "com.ibm.ws.eba.obr.fep.bundle122;version=\"3\";company=mood;local=yes;security=yes;mandatory:=\"mood,security\"";
List<String> result = ManifestHeaderProcessor.split(export, ",");
assertEquals("The result is wrong.", export, result.get(0));
assertEquals("The result is wrong.", 1, result.size());
String aString = "com.acme.foo;weirdAttr=\"one;two;three\";weirdDir:=\"1;2;3\"";
result = ManifestHeaderProcessor.split(aString, ";");
assertEquals("The result is wrong.", "com.acme.foo", result.get(0));
assertEquals("The result is wrong.", "weirdAttr=\"one;two;three\"", result.get(1));
assertEquals("The result is wrong.", "weirdDir:=\"1;2;3\"", result.get(2));
assertEquals("The result is wrong.", 3, result.size());
String pkg1 = "com.ibm.ws.eba.example.helloIsolation;version=\"1.0.0\" ";
String pkg2 = "com.ibm.ws.eba.helloWorldService;version=\"[1.0.0,1.0.0]\"";
String pkg3 = " com.ibm.ws.eba.helloWorldService;version=\"1.0.0\"";
String pkg4 = "com.ibm.ws.eba.helloWorldService;version=\"[1.0.0,1.0.0]\";sharing:=shared" ;
String pkg5 = "com.ibm.ws.eba.helloWorldService;sharing:=shared;version=\"[1.0.0,1.0.0]\"";
String appContent1 = pkg1 + ", " + pkg2 + ", " + pkg3;
String appContent2 = pkg2 + ", " + pkg1 + ", " + pkg3;
String appContent3 = pkg1 + ", " + pkg3 + ", " + pkg2;
String appContent4 = pkg1 + ", " + pkg3 + ", " + pkg4;
String appContent5 = pkg1 + ", " + pkg3 + ", " + pkg5;
List<String> splitList = ManifestHeaderProcessor.split(appContent1, ",");
assertEquals(pkg1.trim(), splitList.get(0));
assertEquals(pkg2.trim(), splitList.get(1));
assertEquals(pkg3.trim(), splitList.get(2));
splitList = ManifestHeaderProcessor.split(appContent2, ",");
assertEquals(pkg2.trim(), splitList.get(0));
assertEquals(pkg1.trim(), splitList.get(1));
assertEquals(pkg3.trim(), splitList.get(2));
splitList = ManifestHeaderProcessor.split(appContent3, ",");
assertEquals(pkg1.trim(), splitList.get(0));
assertEquals(pkg3.trim(), splitList.get(1));
assertEquals(pkg2.trim(), splitList.get(2));
splitList = ManifestHeaderProcessor.split(appContent4, ",");
assertEquals(pkg1.trim(), splitList.get(0));
assertEquals(pkg3.trim(), splitList.get(1));
assertEquals(pkg4.trim(), splitList.get(2));
splitList = ManifestHeaderProcessor.split(appContent5, ",");
assertEquals(pkg1.trim(), splitList.get(0));
assertEquals(pkg3.trim(), splitList.get(1));
assertEquals(pkg5.trim(), splitList.get(2));
}
@Test
public void testParseFilter()
{
Map<String,String> attrs = ManifestHeaderProcessor.parseFilter("(package=com.ibm.test)");
assertEquals("com.ibm.test", attrs.get("package"));
attrs = ManifestHeaderProcessor.parseFilter("(&(package=com.ibm.test)(attr=value))");
assertEquals("com.ibm.test", attrs.get("package"));
assertEquals("value", attrs.get("attr"));
assertEquals(2, attrs.size());
attrs = ManifestHeaderProcessor.parseFilter("(&(version>=1.0.0))");
assertEquals("1.0.0", attrs.get("version"));
attrs = ManifestHeaderProcessor.parseFilter("(&(version>=1.0.0)(version<=2.0.0))");
assertEquals("[1.0.0,2.0.0]", attrs.get("version"));
attrs = ManifestHeaderProcessor.parseFilter("(&(version>=1.0.0)(version<=2.0.0)(!(version=1.0.0)))");
assertEquals("(1.0.0,2.0.0]", attrs.get("version"));
attrs = ManifestHeaderProcessor.parseFilter("(&(!(version=2.0.0))(!(version=1.0.0))(version>=1.0.0)(version<=2.0.0))");
assertEquals("(1.0.0,2.0.0)", attrs.get("version"));
}
@Test
public void testExactVersion() throws Exception
{
VersionRange vr;
try {
vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 2.0.0]", true);
fail("should not get here 1");
} catch (IllegalArgumentException e) {
// expected
}
vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 1.0.0]", true);
assertTrue(vr.isExactVersion());
try {
vr = ManifestHeaderProcessor.parseVersionRange("(1.0.0, 1.0.0]", true);
fail("should not get here 2");
} catch (IllegalArgumentException e) {
// expected
}
try {
vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 1.0.0)", true);
fail("should not get here 3");
} catch (IllegalArgumentException e) {
// expected
}
vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 2.0.0]");
assertFalse(vr.isExactVersion());
vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 1.0.0]");
assertTrue(vr.isExactVersion());
}
@Test
public void testCapabilityHeader() throws Exception {
String s =
"com.acme.dictionary; effective:=resolve; from:String=nl; to=de; version:Version=3.4.0.test;somedir:=test, " +
"com.acme.dictionary; filter:=\"(&(width>=1000)(height>=1000))\", " +
"com.acme.ip2location;country:List<String>=\"nl,be,fr,uk\";version:Version=1.3;long:Long=" + Long.MAX_VALUE + ";d:Double=\"3.141592653589793\"";
List<GenericMetadata> capabilities = ManifestHeaderProcessor.parseCapabilityString(s);
testCapabilitiesOrRequirements(capabilities);
}
@Test
public void testRequirementHeader() throws Exception {
String s =
"com.acme.dictionary; effective:=resolve; from:String=nl; to=de; version:Version=3.4.0.test;somedir:=test, " +
"com.acme.dictionary; filter:=\"(&(width>=1000)(height>=1000))\", " +
"com.acme.ip2location;country:List<String>=\"nl,be,fr,uk\";version:Version=1.3;long:Long=" + Long.MAX_VALUE + ";d:Double=\"3.141592653589793\"";
List<GenericMetadata> capabilities = ManifestHeaderProcessor.parseRequirementString(s);
testCapabilitiesOrRequirements(capabilities);
}
private void testCapabilitiesOrRequirements(List<GenericMetadata> metadata) {
assertEquals(3, metadata.size());
boolean found1 = false, found2 = false, found3 = false;
for (GenericMetadata cap : metadata) {
if ("com.acme.dictionary".equals(cap.getNamespace()) && cap.getDirectives().containsKey("effective")) {
testDictionaryCapability1(cap);
found1 = true;
} else if ("com.acme.dictionary".equals(cap.getNamespace()) && cap.getDirectives().containsKey("filter")) {
testDictionaryCapability2(cap);
found2 = true;
} else if ("com.acme.ip2location".equals(cap.getNamespace())) {
testIP2LocationCapability(cap);
found3 = true;
}
}
assertTrue(found1);
assertTrue(found2);
assertTrue(found3);
}
private void testDictionaryCapability1(GenericMetadata cap) {
assertEquals(2, cap.getDirectives().size());
assertEquals("resolve", cap.getDirectives().get("effective"));
assertEquals("test", cap.getDirectives().get("somedir"));
assertEquals(3, cap.getAttributes().size());
assertEquals("nl", cap.getAttributes().get("from"));
assertEquals("de", cap.getAttributes().get("to"));
assertEquals(new Version(3, 4, 0, "test"), cap.getAttributes().get("version"));
}
private void testDictionaryCapability2(GenericMetadata cap) {
assertEquals(1, cap.getDirectives().size());
assertEquals("(&(width>=1000)(height>=1000))", cap.getDirectives().get("filter"));
assertEquals(0, cap.getAttributes().size());
}
private void testIP2LocationCapability(GenericMetadata cap) {
assertEquals(0, cap.getDirectives().size());
assertEquals(4, cap.getAttributes().size());
assertEquals(new Version(1, 3, 0), cap.getAttributes().get("version"));
assertEquals(Arrays.asList("nl", "be", "fr", "uk"), cap.getAttributes().get("country"));
assertEquals(Long.MAX_VALUE, cap.getAttributes().get("long"));
assertEquals(0, new Double("3.141592653589793").compareTo((Double) cap.getAttributes().get("d")));
}
}
| 7,864 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries/util | Create_ds/aries/util/src/test/java/org/apache/aries/util/filesystem/IOUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipFile;
import org.apache.aries.util.io.IOUtils;
import org.junit.AfterClass;
import org.junit.Test;
public class IOUtilsTest
{
@AfterClass
public static void cleanUp()
{
new File("ioUtilsTest/test.zip").delete();
IOUtils.deleteRecursive(new File("ioUtilsTest"));
}
@Test
public void testZipUpAndUnzipAndDeleteRecursive() throws IOException
{
new File ("ioUtilsTest").mkdir();
IOUtils.zipUp(new File("../src/test/resources/zip"), new File("ioUtilsTest/test.zip"));
ZipFile zip = new ZipFile("ioUtilsTest/test.zip");
assertNotNull(zip.getEntry("file.txt"));
assertNotNull(zip.getEntry("subdir/someFile.txt"));
zip.close();
IDirectory dir = FileSystem.getFSRoot(new File("ioUtilsTest"));
IFile izip = dir.getFile("test.zip");
File output = new File("ioUtilsTest/zipout");
output.mkdirs();
IOUtils.unpackZip(izip, output);
File a = new File(output,"file.txt");
File b = new File(output,"subdir");
File c = new File(b,"someFile.txt");
assertTrue(output.exists());
assertTrue(a.exists() && a.isFile());
assertTrue(b.exists() && b.isDirectory());
assertTrue(c.exists() && c.isFile());
IOUtils.deleteRecursive(output);
assertFalse(output.exists());
}
@Test
public void testWriteOut() throws IOException
{
File tmpDir = new File("target/ioUtilsTest/tmp");
tmpDir.mkdirs();
IOUtils.writeOut(tmpDir, "simple.txt", new ByteArrayInputStream( "abc".getBytes()));
IOUtils.writeOut(tmpDir, "some/relative/directory/complex.txt", new ByteArrayInputStream( "def".getBytes()));
IOUtils.writeOut(tmpDir, "some/relative/directory/complex2.txt", new ByteArrayInputStream( "ghi".getBytes()));
File simple = new File(tmpDir, "simple.txt");
assertTrue(simple.exists());
File complex = new File(tmpDir, "some/relative/directory/complex.txt");
assertTrue(complex.exists());
File complex2 = new File(tmpDir, "some/relative/directory/complex2.txt");
assertTrue(complex2.exists());
BufferedReader r = new BufferedReader(new FileReader(simple));
assertEquals("abc", r.readLine());
assertNull(r.readLine());
r.close();
r = new BufferedReader(new FileReader(complex));
assertEquals("def", r.readLine());
assertNull(r.readLine());
r.close();
r = new BufferedReader(new FileReader(complex2));
assertEquals("ghi", r.readLine());
assertNull(r.readLine());
r.close();
}
@Test
public void testWriteOutAndDoNotCloseInputStream() throws IOException{
InputStream is = new InputStream(){
int idx=0;
int data[]=new int[]{1,2,3,4,5,-1};
@Override
public int read() throws IOException
{
if(idx<data.length)
return data[idx++];
else
return -1;
}
@Override
public void close() throws IOException
{
fail("Close was invoked");
}
};
File f = new File("ioUtilsTest/outtest1");
f.mkdirs();
IOUtils.writeOutAndDontCloseInputStream(f, "/fred", is);
File fred = new File(f,"/fred");
assertTrue(fred.exists());
File outtest = fred.getParentFile();
fred.delete();
outtest.delete();
}
@Test
public void testCopy() throws IOException{
InputStream is = new InputStream(){
boolean closed=false;
int idx=0;
int data[]=new int[]{1,2,3,4,5,-1};
@Override
public int read() throws IOException
{
if(idx<data.length)
return data[idx++];
else
return -1;
}
@Override
public void close() throws IOException
{
closed=true;
}
@Override
public int available() throws IOException
{
if(!closed)
return super.available();
else
return 123456789;
}
};
OutputStream os = new OutputStream(){
int idx=0;
int data[]=new int[]{1,2,3,4,5,-1};
@Override
public void write(int b) throws IOException
{
if(b!=data[idx++]){
fail("Data written to outputstream was not as expected");
}
}
};
IOUtils.copy(is,os);
if(is.available()!=123456789){
fail("close was not invoked");
}
}
@Test
public void testCopyAndDoNotClose() throws IOException{
InputStream is = new InputStream(){
int idx=0;
int data[]=new int[]{1,2,3,4,5,-1};
@Override
public int read() throws IOException
{
if(idx<data.length)
return data[idx++];
else
return -1;
}
@Override
public void close() throws IOException
{
fail("Close invoked");
}
};
OutputStream os = new OutputStream(){
int idx=0;
int data[]=new int[]{1,2,3,4,5,-1};
@Override
public void write(int b) throws IOException
{
if(b!=data[idx++]){
fail("Data written to outputstream was not as expected");
}
}
};
IOUtils.copyAndDoNotCloseInputStream(is,os);
}
}
| 7,865 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries/util | Create_ds/aries/util/src/test/java/org/apache/aries/util/filesystem/FileUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import org.apache.aries.unittest.fixture.ArchiveFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture;
import org.apache.aries.util.io.IOUtils;
import org.junit.Test;
import org.osgi.framework.Constants;
/**
* This class contains tests for the virtual file system.
*/
public class FileUtilsTest
{
/**
* Make sure we get the bundles files recursively regardless of the file extension.
* @throws IOException
*/
@Test
public void testGetBundlesRecursive() throws IOException {
File tmpDir = new File("../src/test/resources/tmpJars");
tmpDir.mkdirs();
for (int n =0; n< 2; n++) {
ZipFixture bundle = ArchiveFixture.newJar().manifest()
.attribute(Constants.BUNDLE_SYMBOLICNAME, "aa" + n)
.attribute(Constants.BUNDLE_MANIFESTVERSION, "2")
.attribute(Constants.IMPORT_PACKAGE, "a.b.c, p.q.r, x.y.z, javax.naming")
.attribute(Constants.BUNDLE_VERSION, "1.0.0").end();
FileOutputStream fout = new FileOutputStream(new File (tmpDir.getAbsoluteFile(), "aa" + n + ((n == 0)? ".jar": ".war")));
bundle.writeOut(fout);
fout.close();
}
File subDir = new File(tmpDir, "subDir");
subDir.mkdirs();
for (int n =0; n< 2; n++) {
ZipFixture bundle = ArchiveFixture.newJar().manifest()
.attribute(Constants.BUNDLE_SYMBOLICNAME, "aa" + n)
.attribute(Constants.BUNDLE_MANIFESTVERSION, "2")
.attribute(Constants.IMPORT_PACKAGE, "a.b.c, p.q.r, x.y.z, javax.naming")
.attribute(Constants.BUNDLE_VERSION, "1.0.0").end();
FileOutputStream fout = new FileOutputStream(new File (subDir.getAbsoluteFile(), "aa" + n + ((n == 0)? ".jar": ".war")));
bundle.writeOut(fout);
fout.close();
}
for (int n =0; n< 2; n++) {
ZipFixture bundle = ArchiveFixture.newJar().manifest()
.attribute(Constants.BUNDLE_MANIFESTVERSION, "2")
.attribute(Constants.IMPORT_PACKAGE, "a.b.c, p.q.r, x.y.z, javax.naming")
.attribute(Constants.BUNDLE_VERSION, "1.0.0").end();
FileOutputStream fout = new FileOutputStream(new File (tmpDir, "bb" + n + ".jar"));
bundle.writeOut(fout);
fout.close();
}
IOUtils.writeOut(tmpDir, "simple.jar", new ByteArrayInputStream("abc".getBytes()));
IOUtils.writeOut(tmpDir, "simple.war", new ByteArrayInputStream("sss".getBytes()));
IOUtils.writeOut(tmpDir, "simple.txt", new ByteArrayInputStream("abc".getBytes()));
IOUtils.writeOut(tmpDir, "some/relative/directory/complex.jar", new ByteArrayInputStream("def".getBytes()));
IOUtils.writeOut(tmpDir, "some/relative/directory/aa/complex2.war", new ByteArrayInputStream("ghi".getBytes()));
IOUtils.writeOut(tmpDir, "simple", new ByteArrayInputStream("abc".getBytes()));
List<URI> jarFiles = FileUtils.getBundlesRecursive(tmpDir.toURI());
assertEquals("There should be 4 entries.", 4, jarFiles.size());
assertTrue("The entry should contain this aa0.jar", jarFiles.contains(new File(tmpDir, "aa0.jar").toURI()));
assertTrue("The entry should contain this aa1.war", jarFiles.contains(new File(tmpDir, "aa1.war").toURI()));
assertTrue("The entry should contain this aa0.jar", jarFiles.contains(new File(subDir, "aa0.jar").toURI()));
assertTrue("The entry should contain this aa1.war", jarFiles.contains(new File(subDir, "aa1.war").toURI()));
IOUtils.deleteRecursive(tmpDir);
}
}
| 7,866 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries/util | Create_ds/aries/util/src/test/java/org/apache/aries/util/filesystem/FileSystemTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.aries.unittest.junit.Assert;
import org.apache.aries.util.IORuntimeException;
import org.apache.aries.util.io.IOUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* This class contains tests for the virtual file system.
*/
public class FileSystemTest
{
/**
* Make sure we correctly understand the content of the application when the
* application is an exploded directory. This test just checks that the
* root directory returns the expected information.
*
* @throws IOException
*/
@Test(expected=UnsupportedOperationException.class)
public void basicRootDirTestsWithFiles() throws IOException
{
File baseDir = new File(getTestResourceDir(), "/app1");
File manifest = new File(baseDir, "META-INF/APPLICATION.MF");
IDirectory dir = FileSystem.getFSRoot(baseDir);
runBasicRootDirTests(dir, baseDir.length(), manifest.lastModified());
}
/**
* Make sure we correctly understand the directory structure for exploded
* directories.
*
* @throws IOException
*/
@Test
public void basicDirTestsWithFiles() throws IOException
{
File baseDir = new File(getTestResourceDir(), "/app1");
IDirectory dir = FileSystem.getFSRoot(baseDir);
File desiredFile = new File(baseDir, "META-INF/APPLICATION.MF");
runBasicDirTest(dir, desiredFile.length(), desiredFile.lastModified());
runBasicDirTest(dir.toCloseable(), desiredFile.length(), desiredFile.lastModified());
}
/**
* Make sure we correctly understand the content of the application when the
* application is a zip. This test just checks that the
* root directory returns the expected information.
*
* @throws IOException
*/
@Test(expected=UnsupportedOperationException.class)
public void basicRootDirTestsWithZip() throws IOException
{
File baseDir = new File("fileSystemTest/app2.zip");
IDirectory dir = FileSystem.getFSRoot(baseDir);
runBasicRootDirTests(dir, baseDir.length(), baseDir.lastModified());
}
/**
* Make sure we correctly understand the content of the application when the
* application is a zip. This test just checks that the
* root directory returns the expected information.
*
* @throws IOException
*/
@Test(expected=UnsupportedOperationException.class)
public void basicRootDirTestsWithZipInputStream() throws IOException
{
File baseDir = new File("fileSystemTest/app2.zip");
ICloseableDirectory dir = FileSystem.getFSRoot(new FileInputStream(baseDir));
try {
runBasicRootDirTests(dir, baseDir.length(), baseDir.lastModified());
} finally {
dir.close();
}
}
@Test
public void testInvalidFSRoot() throws IOException
{
File baseDir = new File(getTestResourceDir(), "/app1");
File manifest = new File(baseDir, "META-INF/APPLICATION.MF");
try {
FileSystem.getFSRoot(manifest);
fail("Should have thrown an IORuntimeException");
} catch (IORuntimeException e) {
// good!
}
}
/**
* Make sure that operations work on zip files nested in file IDirectories
* @throws IOException
*/
@Test
public void nestedZipInDirectory() throws IOException
{
IDirectory dir = FileSystem.getFSRoot(new File("").getAbsoluteFile());
// base convert does not do nested zips
IDirectory zip = dir.getFile("fileSystemTest/app2.zip").convert();
assertNull(zip);
// basic conversion works
zip = dir.getFile("fileSystemTest/app2.zip").convertNested();
assertNotNull(zip);
// we get the parent and our path right
assertNotNull(zip.getParent());
assertEquals("fileSystemTest", zip.getParent().getName());
assertEquals("fileSystemTest/app2.zip", zip.getName());
// files inside the nested zip have the correct path as well
IFile appMf = zip.getFile("META-INF/APPLICATION.MF");
assertNotNull(appMf);
assertEquals("fileSystemTest/app2.zip/META-INF/APPLICATION.MF", appMf.getName());
checkManifest(appMf.open());
// root is right
assertFalse(zip.isRoot());
assertEquals(dir, zip.getRoot());
assertEquals(dir, appMf.getRoot());
// check URLs are correct
checkManifest(appMf.toURL().openStream());
runBasicDirTest(zip, "fileSystemTest/app2.zip/", appMf.getSize(), appMf.getLastModified());
}
/**
* Make sure that the operations work with zip files inside other zip files. Performance is not going to be great though :)
*/
@Test
public void nestedZipInZip() throws IOException
{
IDirectory outer = FileSystem.getFSRoot(new File("fileSystemTest/outer.zip"));
IFile innerFile = outer.getFile("app2.zip");
assertNotNull(innerFile);
IDirectory inner = innerFile.convertNested();
assertNotNull(inner);
File desiredFile = new File(new File(getTestResourceDir(), "/app1"), "META-INF/APPLICATION.MF");
// no size information when stream reading :(
runBasicDirTest(inner, "app2.zip/", -1, desiredFile.lastModified());
runBasicDirTest(inner.toCloseable(), "app2.zip/", desiredFile.length(), desiredFile.lastModified());
}
/**
* Make sure that the operations work with zip files inside other zip files. Performance is not going to be great though :)
*/
@Test
public void nestedZipInZipInputStream() throws Exception
{
ICloseableDirectory outer = FileSystem.getFSRoot(new FileInputStream("fileSystemTest/outer.zip"));
try {
IFile innerFile = outer.getFile("app2.zip");
assertNotNull(innerFile);
IDirectory inner = innerFile.convertNested();
assertNotNull(inner);
File desiredFile = new File(new File(getTestResourceDir(), "/app1"), "META-INF/APPLICATION.MF");
// no size information when stream reading :(
runBasicDirTest(inner, "app2.zip/", -1, desiredFile.lastModified());
runBasicDirTest(inner.toCloseable(), "app2.zip/", desiredFile.length(), desiredFile.lastModified());
} finally {
outer.close();
Field f = outer.getClass().getDeclaredField("tempFile");
f.setAccessible(true);
assertFalse(((File)f.get(outer)).exists());
}
}
/**
* Make sure we correctly understand the directory structure for zips.
*
* @throws IOException
*/
@Test
public void basicDirTestsWithZip() throws IOException
{
File baseDir = new File("fileSystemTest/app2.zip");
IDirectory dir = FileSystem.getFSRoot(baseDir);
assertTrue(dir.toString(), dir.toString().endsWith("app2.zip"));
File desiredFile = new File(new File(getTestResourceDir(), "/app1"), "META-INF/APPLICATION.MF");
runBasicDirTest(dir, desiredFile.length(), desiredFile.lastModified());
runBasicDirTest(dir.toCloseable(), desiredFile.length(), desiredFile.lastModified());
}
/**
* Make sure we correctly understand the directory structure for zips.
*
* @throws IOException
*/
@Test
public void basicDirTestsWithZipInputStream() throws IOException
{
File baseDir = new File("fileSystemTest/app2.zip");
ICloseableDirectory dir = FileSystem.getFSRoot(new FileInputStream(baseDir));
try {
File desiredFile = new File(new File(getTestResourceDir(), "/app1"), "META-INF/APPLICATION.MF");
runBasicDirTest(dir, desiredFile.length(), desiredFile.lastModified());
runBasicDirTest(dir.toCloseable(), desiredFile.length(), desiredFile.lastModified());
} finally {
dir.close();
}
}
@Test
public void zipCloseableZipSimplePerformanceTest() throws IOException
{
int N = 100000;
File baseDir = new File("fileSystemTest/app2.zip");
ZipFile zip = new ZipFile(baseDir);
long start = System.currentTimeMillis();
for (int i=0; i<N; i++) {
ZipEntry ze = zip.getEntry("META-INF/APPLICATION.MF");
InputStream is = zip.getInputStream(ze);
is.close();
}
zip.close();
long duration = System.currentTimeMillis() - start;
// normal zip files
ICloseableDirectory dir = FileSystem.getFSRoot(baseDir).toCloseable();
start = System.currentTimeMillis();
for (int i=0; i<N; i++) {
IFile appMf = dir.getFile("META-INF/APPLICATION.MF");
InputStream is = appMf.open();
is.close();
}
long duration2 = System.currentTimeMillis() - start;
dir.close();
// within an order of magnitude
assertTrue("ZipFile: "+duration+", IDirectory: "+duration2 , duration2 < 10*duration );
// nested zip files
IDirectory outer = FileSystem.getFSRoot(new File("fileSystemTest/outer.zip"));
IFile innerFile = outer.getFile("app2.zip");
dir = innerFile.convertNested().toCloseable();
start = System.currentTimeMillis();
for (int i=0; i<N; i++) {
IFile appMf = dir.getFile("META-INF/APPLICATION.MF");
InputStream is = appMf.open();
is.close();
}
long duration3 = System.currentTimeMillis() - start;
dir.close();
// within an order of magnitude
assertTrue("ZipFile: "+duration+", IDirectory: "+duration3 , duration3 < 10*duration );
}
/**
* Zip up the app1 directory to create a zippped version before running any
* tests.
*
* @throws IOException
*/
@BeforeClass
public static void makeZip() throws IOException
{
File zipFile = new File("fileSystemTest/app2.zip");
zipFile.getParentFile().mkdirs();
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
int index = new File(getTestResourceDir(), "/app1").getAbsolutePath().length();
writeEnties(out, new File(getTestResourceDir(), "/app1"), index);
out.close();
zipFile = new File("outer.zip");
out = new ZipOutputStream(new FileOutputStream(zipFile));
index = new File("fileSystemTest").getAbsolutePath().length();
writeEnties(out, new File("fileSystemTest"), index);
out.close();
if (!!!zipFile.renameTo(new File("fileSystemTest/outer.zip"))) throw new IOException("Rename failed");
}
private static File getTestResourceDir() {
File root = new File("").getAbsoluteFile();
if (root.getName().equals("target")) return new File("../src/test/resources");
else return new File("src/test/resources");
}
/**
* Make sure the test zip is deleted afterwards.
*/
@AfterClass
public static void destroyZip()
{
IOUtils.deleteRecursive(new File("fileSystemTest"));
}
/**
* This method writes the given directory into the provided zip output stream.
* It removes the first <code>index</code> bytes from the absolute path name
* when building the zip.
*
* @param zos the zip output stream to use
* @param f the directory to write into the zip.
* @param index how much of the file name to chop off.
* @throws IOException
*/
public static void writeEnties(ZipOutputStream zos, File f, int index) throws IOException {
File[] files = f.listFiles();
if (files != null) {
for (File file : files) {
String fileName = file.getAbsolutePath().substring(index + 1);
// Bug 1954: replace any '\' characters with '/' - required by ZipEntry
fileName = fileName.replace('\\', '/');
if (file.isDirectory()) fileName = fileName + "/";
ZipEntry ze = new ZipEntry(fileName);
ze.setSize(file.length());
ze.setTime(file.lastModified());
zos.putNextEntry(ze);
if (file.isFile()) {
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
int len = is.read(buffer);
zos.write(buffer, 0, len);
is.close(); // Bug 1594
}
zos.closeEntry();
if (file.isDirectory()) {
writeEnties(zos, file, index);
}
}
}
}
/**
* This method makes sure that the data is correctly understood from disk. It
* is called for both the file and zip versions of the test to ensure we have
* consistent results.
*
* @param dir The IDirectory for the root of the vFS.
* @param len The size of the file.
* @param time The time the file was last updated.
* @throws IOException
*/
public void runBasicRootDirTests(IDirectory dir, long len, long time) throws IOException
{
assertEquals("The root file system name is not correct", "", dir.getName());
assertEquals("The size of the file is not correct", len, dir.getSize());
// This assertion just isn't working on Hudson as of build #79
// assertEquals("The last modified time of the file is not correct", time, dir.getLastModified());
assertNull("I managed to get a parent of a root", dir.getParent());
assertTrue("The root dir does not know it is a dir", dir.isDirectory());
assertFalse("The root dir has an identity crisis and thinks it is a file", dir.isFile());
dir.open();
}
private void runBasicDirTest(IDirectory dir, long len, long time) throws IOException
{
runBasicDirTest(dir, "", len, time);
}
/**
* This method makes sure that the data is correctly understood from disk. It
* is called for both the file and zip versions of the test to ensure we have
* consistent results.
*
* @param dir The IDirectory for the root of the vFS.
* @param len The size of the file.
* @param time The time the file was last updated.
* @throws IOException
*/
private void runBasicDirTest(IDirectory dir, String namePrefix, long len, long time) throws IOException
{
assertNull("for some reason our fake app has a fake blueprint file.", dir.getFile("OSGI-INF/blueprint/aries.xml"));
IFile file = dir.getFile("META-INF/APPLICATION.MF");
assertNotNull("we could not find the application manifest", file);
assertNull(file.convert());
assertNull(file.convertNested());
assertEquals(namePrefix+"META-INF/APPLICATION.MF", file.getName().replace('\\', '/'));
assertTrue("The last update time is not within 2 seconds of the expected value. Expected: " + time + " Actual: " + file.getLastModified(), Math.abs(time - file.getLastModified()) < 2000);
assertEquals(len, file.getSize());
assertEquals(namePrefix+"META-INF", file.getParent().getName());
assertFalse(file.isDirectory());
assertTrue(file.isFile());
List<IFile> files = dir.listFiles();
filterOutSvn(files);
assertEquals(1, files.size());
List<IFile> allFiles = dir.listAllFiles();
filterOutSvn(allFiles);
assertEquals(3, allFiles.size());
assertEquals(namePrefix+"META-INF", allFiles.get(1).getParent().getName());
IFile metaInf = files.get(0);
assertTrue(metaInf.isDirectory());
assertEquals(namePrefix+"META-INF", metaInf.getName());
assertNotNull(metaInf.convert());
files = metaInf.convert().listAllFiles();
filterOutSvn(files);
assertEquals(2, files.size());
for (IFile aFile : dir) {
if (!aFile.getName().contains(".svn")) {
assertTrue(aFile.isDirectory());
assertEquals(namePrefix+"META-INF", aFile.getName());
assertNotNull(aFile.convert());
}
}
checkManifest(file.open());
IFile applicationMF2 = dir.getFile("META-INF/APPLICATION.MF");
Assert.assertEqualsContract(file, applicationMF2, dir);
Assert.assertHashCodeEquals(file, applicationMF2, true);
}
private void filterOutSvn(Collection<IFile> files) {
Iterator<IFile> its = files.iterator();
while (its.hasNext()) {
IFile f = its.next();
if (f.getName().toLowerCase().contains(".svn")) its.remove();
}
}
private void checkManifest(InputStream is) throws IOException {
Manifest man = new Manifest(is);
//remember to close the input stream after use
is.close();
assertEquals("com.travel.reservation", man.getMainAttributes().getValue("Application-SymbolicName"));
}
}
| 7,867 |
0 | Create_ds/aries/util/src/test/java/org/apache/aries/util | Create_ds/aries/util/src/test/java/org/apache/aries/util/log/LoggerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.aries.mocks.BundleContextMock;
import org.apache.aries.unittest.mocks.Skeleton;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
@SuppressWarnings("rawtypes")
public class LoggerTest {
private BundleContext ctx;
@Before
public void setup() {
ctx = Skeleton.newMock(new BundleContextMock(), BundleContext.class);
}
@After
public void teardown() {
BundleContextMock.clear();
}
@Test
public void testLogger() {
Logger logger = new Logger(ctx);
logger.open();
logger.log(LogService.LOG_INFO, "This message will disappear");
TestLogService tls = new TestLogService();
ctx.registerService(LogService.class.getName(), tls, null);
Assert.assertEquals("Precondition", 0, tls.logData.size());
logger.log(LogService.LOG_INFO, "Hi");
Assert.assertEquals(1, tls.logData.size());
LogData ld = tls.logData.get(0);
Assert.assertEquals(LogService.LOG_INFO, ld.level);
Assert.assertEquals("Hi", ld.message);
logger.close();
logger.log(LogService.LOG_INFO, "This message will disappear too");
Assert.assertEquals("The logger was closed so log messages shouldn't appear in the LogService any more",
1, tls.logData.size());
}
@Test
public void testLogger2() {
Logger logger = new Logger(ctx);
logger.open();
TestLogService tls = new TestLogService();
ctx.registerService(LogService.class.getName(), tls, null);
Assert.assertEquals("Precondition", 0, tls.logData.size());
Throwable th = new Throwable();
logger.log(LogService.LOG_INFO, "Hi", th);
Assert.assertEquals(1, tls.logData.size());
LogData ld = tls.logData.get(0);
Assert.assertEquals(LogService.LOG_INFO, ld.level);
Assert.assertEquals("Hi", ld.message);
Assert.assertEquals(th, ld.throwable);
}
@Test
public void testLogger3() {
Logger logger = new Logger(ctx);
logger.open();
TestLogService tls = new TestLogService();
ctx.registerService(LogService.class.getName(), tls, null);
Assert.assertEquals("Precondition", 0, tls.logData.size());
ServiceReference sr = new MockServiceReference();
logger.log(sr, LogService.LOG_INFO, "Hi");
Assert.assertEquals(1, tls.logData.size());
LogData ld = tls.logData.get(0);
Assert.assertSame(sr, ld.serviceReference);
Assert.assertEquals(LogService.LOG_INFO, ld.level);
Assert.assertEquals("Hi", ld.message);
}
@Test
public void testLogger4() {
Logger logger = new Logger(ctx);
logger.open();
TestLogService tls = new TestLogService();
ctx.registerService(LogService.class.getName(), tls, null);
Assert.assertEquals("Precondition", 0, tls.logData.size());
ServiceReference sr = new MockServiceReference();
Throwable th = new Throwable();
logger.log(sr, LogService.LOG_INFO, "Hi", th);
Assert.assertEquals(1, tls.logData.size());
LogData ld = tls.logData.get(0);
Assert.assertSame(sr, ld.serviceReference);
Assert.assertEquals(LogService.LOG_INFO, ld.level);
Assert.assertEquals("Hi", ld.message);
Assert.assertEquals(th, ld.throwable);
}
private class TestLogService implements LogService {
List<LogData> logData = Collections.synchronizedList(new ArrayList<LogData>());
public void log(int level, String message) {
logData.add(new LogData(null, level, message, null));
}
public void log(int level, String message, Throwable exception) {
logData.add(new LogData(null, level, message, exception));
}
public void log(ServiceReference sr, int level, String message) {
logData.add(new LogData(sr, level, message, null));
}
public void log(ServiceReference sr, int level, String message, Throwable exception) {
logData.add(new LogData(sr, level, message, exception));
}
}
private static class LogData {
private final ServiceReference serviceReference;
private final int level;
private final String message;
private final Throwable throwable;
private LogData(ServiceReference sr, int level, String message, Throwable th) {
this.serviceReference = sr;
this.level = level;
this.message = message;
this.throwable = th;
}
}
private static class MockServiceReference implements ServiceReference {
public Object getProperty(String key) {
return null;
}
public String[] getPropertyKeys() {
return null;
}
public Bundle getBundle() {
return null;
}
public Bundle[] getUsingBundles() {
return null;
}
public boolean isAssignableTo(Bundle bundle, String className) {
return false;
}
public int compareTo(Object reference) {
return 0;
}
}
}
| 7,868 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries | Create_ds/aries/util/src/main/java/org/apache/aries/util/FragmentBuilder.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.util.internal.MessageUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
public class FragmentBuilder {
private List<String> importPackages = new ArrayList<String>();
private List<String> exportPackages = new ArrayList<String>();
private Bundle hostBundle;
private String nameExtension;
private String bundleNameExtension;
private String fragmentName;
private Map<String, byte[]> files = new HashMap<String, byte[]>();
public FragmentBuilder(Bundle host) {
this(host, ".fragment", "Fragment");
}
public FragmentBuilder(Bundle host, String symbolicNameSuffix, String bundleNameSuffix) {
hostBundle = host;
nameExtension = symbolicNameSuffix;
bundleNameExtension = bundleNameSuffix;
// make sure we have an initial '.'
if (!!!nameExtension.startsWith(".")) {
nameExtension = "." + nameExtension;
}
}
public void setName(String name) {
fragmentName = name;
}
public void addImports(String... imports) {
importPackages.addAll(Arrays.asList(imports));
}
public void addExports(String... imports) {
exportPackages.addAll(Arrays.asList(imports));
}
public void addImportsFromExports(Bundle exportBundle) {
String exportString = (String) exportBundle.getHeaders().get(Constants.EXPORT_PACKAGE);
if (exportString != null) {
String exportVersion = exportBundle.getVersion().toString();
String bundleConstraint = Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE
+ "=\"" + exportBundle.getSymbolicName() + "\"";
String bundleVersionConstraint = Constants.BUNDLE_VERSION_ATTRIBUTE
+ "=\"[" + exportVersion + "," + exportVersion + "]\"";
List<String> exports = parseDelimitedString(exportString, ",", true);
for (String export : exports) {
importPackages.add(convertExportToImport(export, bundleConstraint, bundleVersionConstraint));
}
}
}
/**
* Filter out directives in the export statement
*
* @param exportStatement
* @return
*/
private String convertExportToImport(String exportStatement,
String bundleConstraint,
String bundleVersionConstraint) {
StringBuffer result = new StringBuffer();
for (String fragment : exportStatement.split("\\s*;\\s*")) {
int pos = fragment.indexOf('=');
// similar to fragment.contains(":=") but looks for the first '='
// and checks whether this is part of ':='
// in this way we will not be fooled by attributes like
// a="something:=strange"
if (!!!(pos > 0 && fragment.charAt(pos - 1) == ':')) {
result.append(fragment);
result.append(';');
}
}
result.append(bundleConstraint);
result.append(';');
result.append(bundleVersionConstraint);
return result.toString();
}
public void addFile(String path, byte[] content) {
files.put(path, content);
}
public Bundle install(BundleContext ctx) throws IOException, BundleException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = null;
try {
jos = new JarOutputStream(baos, makeManifest());
addFileContent(jos);
} finally {
if (jos != null)
jos.close();
baos.close();
}
byte[] inMemoryJar = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(inMemoryJar);
return ctx.installBundle(getFragmentSymbolicName(), bais);
}
private void addFileContent(JarOutputStream jos) throws IOException {
for (Map.Entry<String, byte[]> entry : files.entrySet()) {
jos.putNextEntry(new JarEntry(entry.getKey()));
jos.write(entry.getValue());
}
}
public String getFragmentSymbolicName() {
return hostBundle.getSymbolicName() + nameExtension;
}
public String getFragmentBundleName() {
if (fragmentName != null) {
return fragmentName;
} else {
String bundleName = (String) hostBundle.getHeaders().get(Constants.BUNDLE_NAME);
if (bundleName != null && bundleNameExtension != null) {
return bundleName.trim() + " " + bundleNameExtension.trim();
}
}
return null;
}
private Manifest makeManifest() {
String commonVersion = hostBundle.getVersion().toString();
String fragmentHost = hostBundle.getSymbolicName() + ";"
+ Constants.BUNDLE_VERSION_ATTRIBUTE + "=\"" + commonVersion
+ "\"";
Manifest m = new Manifest();
Attributes manifestAttributes = m.getMainAttributes();
manifestAttributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
manifestAttributes.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
manifestAttributes.putValue(Constants.BUNDLE_SYMBOLICNAME, getFragmentSymbolicName());
String bundleName = getFragmentBundleName();
if (bundleName != null) {
manifestAttributes.putValue(Constants.BUNDLE_NAME, bundleName);
}
manifestAttributes.putValue(Constants.BUNDLE_VERSION, commonVersion);
manifestAttributes.putValue(Constants.BUNDLE_VENDOR, "Apache");
manifestAttributes.putValue(Constants.FRAGMENT_HOST, fragmentHost);
addImportsAndExports(manifestAttributes);
return m;
}
private void addImportsAndExports(Attributes attrs) {
if (!!!importPackages.isEmpty()) {
attrs.putValue(Constants.IMPORT_PACKAGE, joinStrings(importPackages, ','));
}
if (!!!exportPackages.isEmpty()) {
attrs.putValue(Constants.EXPORT_PACKAGE, joinStrings(exportPackages, ','));
}
}
private String joinStrings(List<String> strs, char separator) {
StringBuilder result = new StringBuilder();
boolean first = true;
for (String str : strs) {
if (first)
first = false;
else
result.append(separator);
result.append(str);
}
return result.toString();
}
private static List<String> parseDelimitedString(String value, String delim, boolean includeQuotes) {
if (value == null) {
value = "";
}
List<String> list = new ArrayList<String>();
int CHAR = 1;
int DELIMITER = 2;
int STARTQUOTE = 4;
int ENDQUOTE = 8;
StringBuffer sb = new StringBuffer();
int expecting = (CHAR | DELIMITER | STARTQUOTE);
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
boolean isDelimiter = (delim.indexOf(c) >= 0);
boolean isQuote = (c == '"');
if (isDelimiter && ((expecting & DELIMITER) > 0)) {
list.add(sb.toString().trim());
sb.delete(0, sb.length());
expecting = (CHAR | DELIMITER | STARTQUOTE);
} else if (isQuote && ((expecting & STARTQUOTE) > 0)) {
if (includeQuotes) {
sb.append(c);
}
expecting = CHAR | ENDQUOTE;
} else if (isQuote && ((expecting & ENDQUOTE) > 0)) {
if (includeQuotes) {
sb.append(c);
}
expecting = (CHAR | STARTQUOTE | DELIMITER);
} else if ((expecting & CHAR) > 0) {
sb.append(c);
} else {
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0012E", value));
}
}
if (sb.length() > 0) {
list.add(sb.toString().trim());
}
return list;
}
}
| 7,869 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries | Create_ds/aries/util/src/main/java/org/apache/aries/util/ManifestHeaderUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.util.internal.MessageUtil;
public class ManifestHeaderUtils {
/**
*
* Splits a delimiter separated string, tolerating presence of non separator commas
* within double quoted segments.
*
* Eg.
* com.ibm.ws.eba.helloWorldService;version="[1.0.0, 1.0.0]"
* com.ibm.ws.eba.helloWorldService;version="1.0.0"
* com.ibm.ws.eba.helloWorld;version="2";bundle-version="[2,30)"
* com.acme.foo;weirdAttr="one;two;three";weirdDir:="1;2;3"
* @param value the value to be split
* @param delimiter the delimiter string such as ',' etc.
* @return the components of the split String in a list
*/
public static List<String> split(String value, String delimiter)
{
List<String> result = new ArrayList<String>();
if (value != null) {
String[] packages = value.split(delimiter);
for (int i = 0; i < packages.length; ) {
String tmp = packages[i++].trim();
// if there is a odd number of " in a string, we need to append
while (count(tmp, "\"") % 2 != 0) {
// check to see if we need to append the next package[i++]
if (i<packages.length)
tmp = tmp + delimiter + packages[i++].trim();
else
// oops. The double quotes are not paired up. We have reached to the end of the string.
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0008E",tmp));
}
result.add(tmp);
}
}
return result;
}
/**
* count the number of characters in a string
* @param parent The string to be searched
* @param subString The substring to be found
* @return the number of occurrence of the subString
*/
private static int count(String parent, String subString) {
int count = 0 ;
int i = parent.indexOf(subString);
while (i > -1) {
if (parent.length() >= i+1)
parent = parent.substring(i+1);
count ++;
i = parent.indexOf(subString);
}
return count;
}
}
| 7,870 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries | Create_ds/aries/util/src/main/java/org/apache/aries/util/AriesFrameworkUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util;
import org.apache.aries.util.internal.DefaultWorker;
import org.apache.aries.util.internal.EquinoxWorker;
import org.apache.aries.util.internal.FelixWorker;
import org.apache.aries.util.internal.FrameworkUtilWorker;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
public final class AriesFrameworkUtil
{
private static FrameworkUtilWorker worker;
static {
Bundle b = FrameworkUtil.getBundle(AriesFrameworkUtil.class);
String bundleClassName = b == null ? "": b.getClass().getName();
if (isEquinox(bundleClassName)) {
worker = new EquinoxWorker();
} else if (bundleClassName.startsWith("org.apache.felix")) {
worker = new FelixWorker();
}
if (worker == null || !!!worker.isValid()) worker = new DefaultWorker();
}
/**
* This method attempts to get the classloader for a bundle. It may return null if
* their is no such classloader, or if it cannot obtain the classloader for the bundle.
*
* @param b the bundle whose classloader is desired.
* @return the classloader if found, or null if for example the bundle is in INSTALLED or UNINSTALLED state
*/
public static ClassLoader getClassLoader(Bundle b)
{
if (b != null && b.getState() != Bundle.UNINSTALLED && b.getState() != Bundle.INSTALLED) {
return worker.getClassLoader(b);
} else {
return null;
}
}
/**
* Returns true if we are in equinox, and we can access the interfaces we need.
* @param bundleClassName the class name of the bundle implementation.
* @return true if we are in equinox, false otherwise.
*/
private static boolean isEquinox(String bundleClassName)
{
if (bundleClassName.startsWith("org.eclipse.osgi")) {
try {
Class.forName("org.eclipse.osgi.framework.internal.core.BundleHost");
return true;
} catch (ClassNotFoundException e) {
}
}
return false;
}
/**
* This method attempts to get the classloader for a bundle. It will force the creation
* of a classloader, so if no classloader exists. If the bundle is in installed state, but
* cannot be resolved the null will be returned.
*
* @param b the bundle to get a classloader for
* @return the classloader.
*/
public static ClassLoader getClassLoaderForced(Bundle b)
{
if (b == null)
return null;
try {
b.loadClass("java.lang.Object");
} catch (ClassNotFoundException e) {
}
return worker.getClassLoader(b);
}
/**
* Safely unregister the supplied ServiceRegistration, for when you don't
* care about the potential IllegalStateException and don't want
* it to run wild through your code
*
* @param reg The {@link ServiceRegistration}, may be null
*/
@SuppressWarnings("rawtypes")
public static void safeUnregisterService(ServiceRegistration reg)
{
if(reg != null) {
try {
reg.unregister();
} catch (IllegalStateException e) {
//This can be safely ignored
}
}
}
} | 7,871 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries | Create_ds/aries/util/src/main/java/org/apache/aries/util/VersionRange.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.aries.util.internal.MessageUtil;
import org.osgi.framework.Version;
public final class VersionRange {
/** A string representation of the version. */
private String version;
/** The minimum desired version for the bundle */
private Version minimumVersion;
/** The maximum desired version for the bundle */
private Version maximumVersion;
/** True if the match is exclusive of the minimum version */
private boolean minimumExclusive;
/** True if the match is exclusive of the maximum version */
private boolean maximumExclusive;
/** A regexp to select the version */
private static final Pattern versionCapture = Pattern.compile("\"?(.*?)\"?$");
/**
*
* @param version
* version for the verioninfo
*/
public VersionRange(String version) {
this.version = version;
processVersionAttribute(version);
}
/**
* This method should be used to create a version range from a single
* version string.
* @param version
* version for the versioninfo
* @param exactVersion
* whether this is an exact version {@code true} or goes to infinity
* {@code false}
*/
public VersionRange(String version, boolean exactVersion) {
if (exactVersion) {
// Do not store this string as it might be just a version, or a range!
processExactVersionAttribute(version);
} else {
this.version = version;
processVersionAttribute(this.version);
}
assertInvariants();
}
/**
* Constructor designed for internal use only.
*
* @param maximumVersion
* @param maximumExclusive
* @param minimumVersion
* @param minimumExclusive
* @throws IllegalArgumentException
* if parameters are not valid.
*/
private VersionRange(Version maximumVersion,
boolean maximumExclusive,
Version minimumVersion,
boolean minimumExclusive) {
this.maximumVersion = maximumVersion;
this.maximumExclusive = maximumExclusive;
this.minimumVersion = minimumVersion;
this.minimumExclusive = minimumExclusive;
assertInvariants();
}
/*
* (non-Javadoc)
*
* @see org.apache.aries.application.impl.VersionRange#toString()
*/
@Override
public String toString() {
// Some constructors don't take in a string that we can return directly,
// so construct one if needed
if (version == null) {
if (maximumVersion == null) {
version = minimumVersion.toString();
} else {
version = (minimumExclusive ? "(" : "[") + minimumVersion + "," + maximumVersion
+ (maximumExclusive ? ")" : "]");
}
}
return this.version;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + minimumVersion.hashCode();
result = 31 * result + (minimumExclusive ? 1 : 0);
result = 31 * result + (maximumVersion != null ? maximumVersion.hashCode() : 0);
result = 31 * result + (maximumExclusive ? 1 : 0);
return result;
}
@Override
public boolean equals(Object other) {
boolean result = false;
if (this == other) {
result = true;
} else if (other instanceof VersionRange) {
VersionRange vr = (VersionRange) other;
result = minimumVersion.equals(vr.minimumVersion)
&& minimumExclusive == vr.minimumExclusive
&& (maximumVersion == null ? vr.maximumVersion == null : maximumVersion
.equals(vr.maximumVersion)) && maximumExclusive == vr.maximumExclusive;
}
return result;
}
/**
* this method returns the exact version from the versionInfo obj.
* this is used for DeploymentContent only to return a valid exact version
* otherwise, null is returned.
* @return the exact version
*/
public Version getExactVersion() {
Version v = null;
if (isExactVersion()) {
v = getMinimumVersion();
}
return v;
}
/**
* get the maximum version
* @return the maximum version
*/
public Version getMaximumVersion() {
return maximumVersion;
}
/**
* get the minimum version
* @return the minimum version
*/
public Version getMinimumVersion() {
return minimumVersion;
}
/**
* is the maximum version exclusive
* @return is the max version in the range.
*/
public boolean isMaximumExclusive() {
return maximumExclusive;
}
/**
* is the maximum version unbounded
* @return true if no upper bound was specified.
*/
public boolean isMaximumUnbounded() {
boolean unbounded = maximumVersion == null;
return unbounded;
}
/**
* is the minimum version exclusive
* @return true if the min version is in range.
*/
public boolean isMinimumExclusive() {
return minimumExclusive;
}
/**
* this is designed for deployed-version as that is the exact version.
*
* @param version
* @return
* @throws IllegalArgumentException
*/
private boolean processExactVersionAttribute(String version) throws IllegalArgumentException {
boolean success = processVersionAttribute(version);
if (maximumVersion == null) {
maximumVersion = minimumVersion;
}
if (!minimumVersion.equals(maximumVersion)) {
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0011E", version));
}
if (!!!isExactVersion()) {
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0009E", version));
}
return success;
}
/**
* process the version attribute,
*
* @param version
* the value to be processed
* @return
* @throws IllegalArgumentException
*/
private boolean processVersionAttribute(String version) throws IllegalArgumentException {
boolean success = false;
if (version == null) {
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0010E"));
}
Matcher matches = versionCapture.matcher(version);
if (matches.matches()) {
String versions = matches.group(1);
if ((versions.startsWith("[") || versions.startsWith("("))
&& (versions.endsWith("]") || versions.endsWith(")"))) {
if (versions.startsWith("["))
minimumExclusive = false;
else if (versions.startsWith("("))
minimumExclusive = true;
if (versions.endsWith("]"))
maximumExclusive = false;
else if (versions.endsWith(")"))
maximumExclusive = true;
int index = versions.indexOf(',');
String minVersion = versions.substring(1, index);
String maxVersion = versions.substring(index + 1, versions.length() - 1);
try {
minimumVersion = new Version(minVersion.trim());
maximumVersion = new Version(maxVersion.trim());
success = true;
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0009E", version), nfe);
}
} else {
try {
if (versions.trim().length() == 0)
minimumVersion = new Version(0, 0, 0);
else
minimumVersion = new Version(versions.trim());
success = true;
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0009E", version), nfe);
}
}
} else {
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0009E", version));
}
return success;
}
/**
* Assert object invariants. Called by constructors to verify that arguments
* were valid.
*
* @throws IllegalArgumentException
* if invariants are violated.
*/
private void assertInvariants() {
if (minimumVersion == null
|| !isRangeValid(minimumVersion, minimumExclusive, maximumVersion, maximumExclusive)) {
IllegalArgumentException e = new IllegalArgumentException();
throw e;
}
}
/**
* Check if the supplied parameters describe a valid version range.
*
* @param min
* the minimum version.
* @param minExclusive
* whether the minimum version is exclusive.
* @param max
* the maximum version.
* @param maxExclusive
* whether the maximum version is exclusive.
* @return true is the range is valid; otherwise false.
*/
private boolean isRangeValid(Version min,
boolean minExclusive,
Version max,
boolean maxExclusive) {
boolean result;
// A null maximum version is unbounded so means that minimum is smaller
// than
// maximum.
int minMaxCompare = (max == null ? -1 : min.compareTo(max));
if (minMaxCompare > 0) {
// Minimum larger than maximum is invalid.
result = false;
} else if (minMaxCompare == 0 && (minExclusive || maxExclusive)) {
// If min and max are the same, and either are exclusive, no valid
// range
// exists.
result = false;
} else {
// Range is valid.
result = true;
}
return result;
}
/**
* This method checks that the provided version matches the desired version.
*
* @param version
* the version.
* @return true if the version matches, false otherwise.
*/
public boolean matches(Version version) {
boolean result;
if (this.getMaximumVersion() == null) {
result = this.getMinimumVersion().compareTo(version) <= 0;
} else {
int minN = this.isMinimumExclusive() ? 0 : 1;
int maxN = this.isMaximumExclusive() ? 0 : 1;
result = (this.getMinimumVersion().compareTo(version) < minN)
&& (version.compareTo(this.getMaximumVersion()) < maxN);
}
return result;
}
/**
* check if the versioninfo is the exact version
* @return true if the range will match 1 exact version.
*/
public boolean isExactVersion() {
return minimumVersion.equals(maximumVersion) && minimumExclusive == maximumExclusive
&& !!!minimumExclusive;
}
/**
* Create a new version range that is the intersection of {@code this} and the argument.
* In other words, the largest version range that lies within both {@code this} and
* the parameter.
* @param r a version range to be intersected with {@code this}.
* @return a new version range, or {@code null} if no intersection is possible.
*/
public VersionRange intersect(VersionRange r) {
// Use the highest minimum version.
final Version newMinimumVersion;
final boolean newMinimumExclusive;
int minCompare = minimumVersion.compareTo(r.getMinimumVersion());
if (minCompare > 0) {
newMinimumVersion = minimumVersion;
newMinimumExclusive = minimumExclusive;
} else if (minCompare < 0) {
newMinimumVersion = r.getMinimumVersion();
newMinimumExclusive = r.isMinimumExclusive();
} else {
newMinimumVersion = minimumVersion;
newMinimumExclusive = (minimumExclusive || r.isMinimumExclusive());
}
// Use the lowest maximum version.
final Version newMaximumVersion;
final boolean newMaximumExclusive;
// null maximum version means unbounded, so the highest possible value.
if (maximumVersion == null) {
newMaximumVersion = r.getMaximumVersion();
newMaximumExclusive = r.isMaximumExclusive();
} else if (r.getMaximumVersion() == null) {
newMaximumVersion = maximumVersion;
newMaximumExclusive = maximumExclusive;
} else {
int maxCompare = maximumVersion.compareTo(r.getMaximumVersion());
if (maxCompare < 0) {
newMaximumVersion = maximumVersion;
newMaximumExclusive = maximumExclusive;
} else if (maxCompare > 0) {
newMaximumVersion = r.getMaximumVersion();
newMaximumExclusive = r.isMaximumExclusive();
} else {
newMaximumVersion = maximumVersion;
newMaximumExclusive = (maximumExclusive || r.isMaximumExclusive());
}
}
VersionRange result;
if (isRangeValid(newMinimumVersion, newMinimumExclusive, newMaximumVersion,
newMaximumExclusive)) {
result = new VersionRange(newMaximumVersion, newMaximumExclusive, newMinimumVersion,
newMinimumExclusive);
} else {
result = null;
}
return result;
}
/**
* Parse a version range..
*
* @param s
* @return VersionRange object.
* @throws IllegalArgumentException
* if the String could not be parsed as a VersionRange
*/
public static VersionRange parseVersionRange(String s) throws IllegalArgumentException {
return new VersionRange(s);
}
/**
* Parse a version range and indicate if the version is an exact version
*
* @param s
* @param exactVersion
* @return VersionRange object.
* @throws IllegalArgumentException
* if the String could not be parsed as a VersionRange
*/
public static VersionRange parseVersionRange(String s, boolean exactVersion)
throws IllegalArgumentException {
return new VersionRange(s, exactVersion);
}
}
| 7,872 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries | Create_ds/aries/util/src/main/java/org/apache/aries/util/IORuntimeException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util;
import java.io.IOException;
/**
* This unchecked exception wraps an IOException.
*/
public class IORuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* @param message A detail message.
* @param cause The original IOException.
*/
public IORuntimeException(String message, IOException cause) {
super(message, cause);
}
/**
* @param cause The original IOException.
*/
public IORuntimeException(IOException cause) {
super(cause);
}
/**
* @see java.lang.Throwable#getCause()
*/
@Override
public IOException getCause() {
return (IOException) super.getCause();
}
}
| 7,873 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/nls/MessageUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.nls;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.aries.util.AriesFrameworkUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
/**
* This is a helper class for loading messages for logging and exception messages. It supports translating the message into the
* default Locale. It works out the calling Bundle and uses it to load any resources. If the resource bundle is of type
* java.properties then it tries to find the bundle first via the bundle getResources method, then via the getEntry method. If it
* is of type java.class then it'll use the bundle to load the class.
*/
public final class MessageUtil
{
/** The resource bundle used to translate messages */
private final ResourceBundle messages;
private static final StackFinder finder;
/**
* One of the static methods needs to obtain the caller, so we cheat and use a SecurityManager to get the
* classes on the stack.
*/
private static class StackFinder extends SecurityManager
{
@Override
public Class<?>[] getClassContext()
{
return super.getClassContext();
}
}
static
{
finder = AccessController.doPrivileged(new PrivilegedAction<StackFinder>() {
public StackFinder run()
{
return new StackFinder();
}
});
}
private MessageUtil(ResourceBundle b)
{
messages = b;
}
/**
* This method translates the message and puts the inserts into the message before returning it.
* If the message key does not exist then the key itself is returned.
*
* @param key the message key.
* @param inserts the inserts into the resolved message.
* @return the message in the correct language, or the key if the message does not exist.
*/
public String getMessage(String key, Object ... inserts)
{
String message;
try {
message = messages.getString(key);
if (inserts != null && inserts.length > 0) {
message = MessageFormat.format(message, inserts);
}
} catch (MissingResourceException e) {
message = key;
}
return message;
}
/**
* Loads the MessageUtil using the given context. It resolves the Class to an OSGi bundle.
*
* @param context the bundle this class is in will be used to resolve the base name.
* @param baseName the resource bundle base name
* @return the message util instance.
* @throws MissingResourceException If the resource bundle cannot be located
*/
public static MessageUtil createMessageUtil(Class<?> context, String baseName)
{
return createMessageUtil(FrameworkUtil.getBundle(context), baseName);
}
/**
* This method uses the Bundle associated with the caller of this method.
*
* @param baseName the resource bundle base name
* @return the message util instance.
* @throws MissingResourceException If the resource bundle cannot be located
*/
public static MessageUtil createMessageUtil(String baseName)
{
Class<?>[] stack = finder.getClassContext();
for (Class<?> clazz : stack) {
if (clazz != MessageUtil.class) {
return createMessageUtil(clazz, baseName);
}
}
throw new MissingResourceException(org.apache.aries.util.internal.MessageUtil.getMessage("UTIL0014E", baseName), baseName, null);
}
/**
* This method loads the resource bundle backing the MessageUtil from the provided Bundle.
*
* @param b the bundle to load the resource bundle from
* @param baseName the resource bundle base name
* @return the message util instance.
* @throws MissingResourceException If the resource bundle cannot be located
*/
public static MessageUtil createMessageUtil(final Bundle b, String baseName)
{
ResourceBundle rb;
if (b == null) {
// if the bundle is null we are probably outside of OSGi, so just use non-OSGi resolve rules.
rb = ResourceBundle.getBundle(baseName);
} else {
// if the bundle is OSGi use OSGi resolve rules as best as Java5 allows
ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return AriesFrameworkUtil.getClassLoader(b);
}
});
rb = ResourceBundle.getBundle(baseName, Locale.getDefault(), loader);
}
return new MessageUtil(rb);
}
} | 7,874 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/manifest/ManifestProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.manifest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.apache.aries.util.filesystem.IDirectory;
import org.apache.aries.util.filesystem.IFile;
import org.apache.aries.util.io.IOUtils;
/**
* This class contains utilities for parsing manifests. It provides methods to
* parse the manifest, read a manifest into a map and to split an manifest
* entry that follows the Import-Package syntax.
*/
public class ManifestProcessor
{
/**
* Reads a manifest's main attributes into a map String, String.
* <p>
* Will always return a map, empty if the manifest had no attributes.
*
* @param mf The manifest to read.
* @return Map of manifest main attributes.
*/
public static Map<String, String> readManifestIntoMap(Manifest mf){
HashMap<String, String> props = new HashMap<String, String>();
Attributes mainAttrs = mf.getMainAttributes();
if (mainAttrs!=null){
Set<Entry<Object, Object>> attributeSet = mainAttrs.entrySet();
if (attributeSet != null){
// Copy all the manifest headers across. The entry set should be a set of
// Name to String mappings, by calling String.valueOf we do the conversion
// to a string and we do not NPE.
for (Map.Entry<Object, Object> entry : attributeSet) {
props.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
}
}
return props;
}
/**
* mapToManifest
*/
public static Manifest mapToManifest (Map<String,String> attributes)
{
Manifest man = new Manifest();
Attributes att = man.getMainAttributes();
att.putValue(Attributes.Name.MANIFEST_VERSION.toString(), Constants.MANIFEST_VERSION);
for (Map.Entry<String, String> entry : attributes.entrySet()) {
att.putValue(entry.getKey(), entry.getValue());
}
return man;
}
/**
* This method parses the manifest using a custom manifest parsing routine.
* This means that we can avoid the 76 byte line length in a manifest providing
* a better developer experience.
*
* @param in the input stream to read the manifest from.
* @return the parsed manifest
* @throws IOException
*/
public static Manifest parseManifest(InputStream in) throws IOException
{
Manifest man = new Manifest();
try
{
// I'm assuming that we use UTF-8 here, but the jar spec doesn't say.
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line;
StringBuilder attribute = null;
String namedAttribute = null;
do {
line = reader.readLine();
// if we get a blank line skip to the next one
if (line != null && line.trim().length() == 0) continue;
if (line != null && line.charAt(0) == ' ' && attribute != null) {
// we have a continuation line, so add to the builder, ignoring the
// first character
attribute.append(line.trim());
} else if (attribute == null) {
attribute = new StringBuilder(line.trim());
} else if (attribute != null) {
// We have fully parsed an attribute
int index = attribute.indexOf(":");
String attributeName = attribute.substring(0, index).trim();
// TODO cope with index + 1 being after the end of attribute
String attributeValue = attribute.substring(index + 1).trim();
if ("Name".equals(attributeName)) {
man.getEntries().put(attributeValue, new Attributes());
namedAttribute = attributeValue;
} else {
Attributes.Name nameToAdd = new Attributes.Name(attributeName);
if (namedAttribute == null || !man.getMainAttributes().containsKey(nameToAdd)) {
man.getMainAttributes().put(nameToAdd, attributeValue);
} else {
man.getAttributes(namedAttribute).put(nameToAdd, attributeValue);
}
}
if (line != null) attribute = new StringBuilder(line.trim());
}
} while (line != null);
}
finally {
IOUtils.close(in);
}
return man;
}
/**
* Obtain a manifest from an IDirectory.
*
* @param appDir
* @param manifestName the name of manifest
* @return Manifest, or null if none found.
* @throws IOException
*/
public static Manifest obtainManifestFromAppDir(IDirectory appDir, String manifestName) throws IOException{
IFile manifestFile = appDir.getFile(manifestName);
Manifest man = null;
if (manifestFile != null) {
man = parseManifest(manifestFile.open());
}
return man;
}
/**
*
* Splits a delimiter separated string, tolerating presence of non separator commas
* within double quoted segments.
*
* Eg.
* com.ibm.ws.eba.helloWorldService;version="[1.0.0, 1.0.0]"
* com.ibm.ws.eba.helloWorldService;version="1.0.0"
* com.ibm.ws.eba.helloWorld;version="2";bundle-version="[2,30)"
* com.acme.foo;weirdAttr="one;two;three";weirdDir:="1;2;3"
* @param value the value to be split
* @param delimiter the delimiter string such as ',' etc.
* @return the components of the split String in a list
*/
public static List<String> split(String value, String delimiter)
{
List<String> result = new ArrayList<String>();
if (value != null) {
String[] packages = value.split(delimiter);
for (int i = 0; i < packages.length; ) {
String tmp = packages[i++].trim();
// if there is a odd number of " in a string, we need to append
while (count(tmp, "\"") % 2 == 1) {
// check to see if we need to append the next package[i++]
tmp = tmp + delimiter + packages[i++].trim();
}
result.add(tmp);
}
}
return result;
}
/**
* count the number of characters in a string
* @param parent The string to be searched
* @param subString The substring to be found
* @return the number of occurrence of the subString
*/
private static int count(String parent, String subString) {
int count = 0 ;
int i = parent.indexOf(subString);
while (i > -1) {
if (parent.length() >= i+1)
parent = parent.substring(i+1);
count ++;
i = parent.indexOf(subString);
}
return count;
}
}
| 7,875 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/manifest/BundleManifest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.manifest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.apache.aries.util.IORuntimeException;
import org.apache.aries.util.filesystem.IFile;
import org.apache.aries.util.internal.MessageUtil;
import org.apache.aries.util.io.IOUtils;
import org.apache.aries.util.manifest.ManifestHeaderProcessor.NameValuePair;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
/**
* Entity class to retrieve and represent a bundle manifest (valid or invalid).
*/
public class BundleManifest
{
private static final String MANIFEST_PATH = "META-INF/MANIFEST.MF";
/**
* Read a manifest from a jar input stream. This will find the manifest even if it is NOT
* the first file in the archive.
*
* @param is the jar input stream
* @return the bundle manifest
*/
public static BundleManifest fromBundle(InputStream is) {
JarInputStream jarIs = null;
try {
jarIs = new JarInputStream(is);
Manifest m = jarIs.getManifest();
if (m != null)
return new BundleManifest(m);
else {
ZipEntry entry;
while ((entry = jarIs.getNextEntry()) != null) {
if (entry.getName().equals(MANIFEST_PATH))
return new BundleManifest(jarIs);
}
return null;
}
}
catch (IOException e) {
throw new IORuntimeException("IOException in BundleManifest()", e);
}
finally {
IOUtils.close(jarIs);
}
}
/**
* Retrieve a BundleManifest from the given jar file
*
* @param f the bundle jar file
* @return the bundle manifest
*/
public static BundleManifest fromBundle(IFile f) {
InputStream is = null;
try {
if (f.isDirectory()) {
IFile manFile = f.convert().getFile(MANIFEST_PATH);
if (manFile != null)
return new BundleManifest(manFile.open());
else
return null;
} else {
is = f.open();
return fromBundle(is);
}
} catch (IOException e) {
throw new IORuntimeException("IOException in BundleManifest.fromBundle(IFile)", e);
}
finally {
IOUtils.close(is);
}
}
/**
* Retrieve a bundle manifest from the given jar file, which can be exploded or compressed
*
* @param f the bundle jar file
* @return the bundle manifest
*/
public static BundleManifest fromBundle(File f) {
if (f.isDirectory()) {
File manifestFile = new File(f, MANIFEST_PATH);
if (manifestFile.isFile())
try {
return new BundleManifest(new FileInputStream(manifestFile));
}
catch (IOException e) {
throw new IORuntimeException("IOException in BundleManifest.fromBundle(File)", e);
}
else
return null;
}
else if (f.isFile()) {
try {
return fromBundle(new FileInputStream(f));
}
catch (IOException e) {
throw new IORuntimeException("IOException in BundleManifest.fromBundle(File)", e);
}
}
else {
throw new IllegalArgumentException(MessageUtil.getMessage("UTIL0016E", f.getAbsolutePath()));
}
}
private Manifest manifest;
/**
* Create a BundleManifest object from the InputStream to the manifest (not to the bundle)
* @param manifestIs
* @throws IOException
*/
public BundleManifest(InputStream manifestIs) throws IOException {
this(ManifestProcessor.parseManifest(manifestIs));
}
/**
* Create a BundleManifest object from a common Manifest object
* @param m
*/
public BundleManifest(Manifest m) {
manifest = m;
}
public String getSymbolicName() {
String rawSymName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
String result = null;
if (rawSymName != null) {
NameValuePair info = ManifestHeaderProcessor.parseBundleSymbolicName(rawSymName);
result = info.getName();
}
return result;
}
public Version getVersion() {
String specifiedVersion = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
Version result = (specifiedVersion == null) ? Version.emptyVersion : new Version(specifiedVersion);
return result;
}
public String getManifestVersion() {
return manifest.getMainAttributes().getValue(Constants.BUNDLE_MANIFESTVERSION);
}
public Attributes getRawAttributes() {
return manifest.getMainAttributes();
}
public Manifest getRawManifest() {
return manifest;
}
public boolean isValid() {
return getManifestVersion() != null && getSymbolicName() != null;
}
}
| 7,876 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/manifest/ManifestHeaderProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.manifest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.aries.util.ManifestHeaderUtils;
import org.apache.aries.util.VersionRange;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
public class ManifestHeaderProcessor
{
public static final String NESTED_FILTER_ATTRIBUTE = "org.apache.aries.application.filter.attribute";
private static final Pattern FILTER_ATTR = Pattern.compile("(\\(!)?\\((.*?)([<>]?=)(.*?)\\)\\)?");
private static final String LESS_EQ_OP = "<=";
private static final String GREATER_EQ_OP = ">=";
/**
* A GenericMetadata is either a Generic Capability or a Generic Requirement
*/
public static class GenericMetadata {
private final String namespace;
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Map<String, String> directives = new HashMap<String, String>();
public GenericMetadata(String namespace) {
this.namespace = namespace;
}
public String getNamespace() {
return namespace;
}
public Map<String, Object> getAttributes() {
return attributes;
}
public Map<String, String> getDirectives() {
return directives;
}
}
/**
* A simple class to associate two types.
*/
public static class NameValuePair {
private String name;
private Map<String,String> attributes;
public NameValuePair(String name, Map<String,String> value)
{
this.name = name;
this.attributes = value;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Map<String,String> getAttributes()
{
return attributes;
}
public void setAttributes(Map<String,String> value)
{
this.attributes = value;
}
@Override
public String toString(){
return "{"+name.toString()+"::"+attributes.toString()+"}";
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final NameValuePair other = (NameValuePair) obj;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (attributes == null) {
if (other.attributes != null) return false;
} else if (!attributes.equals(other.attributes)) return false;
return true;
}
}
/**
* Intended to provide a standard way to add Name/Value's to
* aggregations of Name/Value's.
*/
public static interface NameValueCollection {
/**
* Add this Name and Value to the collection.
* @param n
* @param v
*/
public void addToCollection(String n, Map<String,String> v);
}
public static class NameValueMap extends HashMap<String, Map<String,String>> implements NameValueCollection, Map<String, Map<String,String>>{
private static final long serialVersionUID = -6446338858542599141L;
public void addToCollection(String n, Map<String,String> v){
this.put(n,v);
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("{");
boolean first=true;
for(Map.Entry<String, Map<String,String>> entry : this.entrySet()){
if(!first)sb.append(",");
first=false;
sb.append(entry.getKey()+"->"+entry.getValue());
}
sb.append("}");
return sb.toString();
}
}
/**
* List of Name/Value
*/
public static class NameValueList extends ArrayList<NameValuePair> implements NameValueCollection, List<NameValuePair> {
private static final long serialVersionUID = 1808636823825029983L;
public void addToCollection(String n, Map<String,String> v){
this.add(new NameValuePair(n,v));
}
@Override
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("{");
boolean first = true;
for(NameValuePair nvp : this){
if(!first)sb.append(",");
first=false;
sb.append(nvp.toString());
}
sb.append("}");
return sb.toString();
}
}
/**
*
* Splits a delimiter separated string, tolerating presence of non separator commas
* within double quoted segments.
*
* Eg.
* com.ibm.ws.eba.helloWorldService;version="[1.0.0, 1.0.0]"
* com.ibm.ws.eba.helloWorldService;version="1.0.0"
* com.ibm.ws.eba.helloWorld;version="2";bundle-version="[2,30)"
* com.acme.foo;weirdAttr="one;two;three";weirdDir:="1;2;3"
* @param value the value to be split
* @param delimiter the delimiter string such as ',' etc.
* @return the components of the split String in a list
*/
public static List<String> split(String value, String delimiter)
{
return ManifestHeaderUtils.split(value, delimiter);
}
/**
* Internal method to parse headers with the format<p>
* [Name](;[Name])*(;[attribute-name]=[attribute-value])*<br>
* Eg.<br>
* rumplestiltskin;thing=value;other=something<br>
* littleredridinghood
* bundle1;bundle2;other=things
* bundle1;bundle2
*
* @param s data to parse
* @return a list of NameValuePair, with the Name being the name component,
* and the Value being a NameValueMap of key->value mappings.
*/
private static List<NameValuePair> genericNameWithNameValuePairProcess(String s){
String name;
Map<String,String> params = null;
List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
List<String> pkgs = new ArrayList<String>();
int index = s.indexOf(";");
if(index==-1){
name = s;
params = new HashMap<String, String>();
pkgs.add(name);
}else{
name = s.substring(0,index).trim();
String tail = s.substring(index+1).trim();
pkgs.add(name); // add the first package
StringBuilder parameters = new StringBuilder();
// take into consideration of multiple packages separated by ';'
// while they share the same attributes or directives
List<String> tailParts = split(tail, ";");
boolean firstParameter =false;
for (String part : tailParts) {
// if it is not a parameter and no parameter appears in front of it, it must a package
if (!!!(part.contains("="))) {
// Need to make sure no parameter appears before the package, otherwise ignore this string
// as this syntax is invalid
if (!!!(firstParameter))
pkgs.add(part);
} else {
if (!!!(firstParameter))
firstParameter = true;
parameters.append(part + ";");
}
}
if (parameters.length() != 0) {
//remove the final ';' if there is one
if (parameters.toString().endsWith(";")) {
parameters = parameters.deleteCharAt(parameters.length() -1);
}
params = genericNameValueProcess(parameters.toString());
}
}
for (String pkg : pkgs) {
nameValues.add(new NameValuePair(pkg,params));
}
return nameValues;
}
/**
* Internal method to parse headers with the format<p>
* [attribute-name]=[attribute-value](;[attribute-name]=[attribute-value])*<br>
* Eg.<br>
* thing=value;other=something<br>
* <p>
* Note. Directives (name:=value) are represented in the map with name suffixed by ':'
*
* @param s data to parse
* @return a NameValueMap, with attribute-name -> attribute-value.
*/
private static Map<String,String> genericNameValueProcess(String s){
Map<String,String> params = new HashMap<String,String>();
List<String> parameters = split(s, ";");
for(String parameter : parameters) {
List<String> parts = split(parameter,"=");
// do a check, otherwise we might get NPE
if (parts.size() ==2) {
String second = parts.get(1).trim();
if (second.startsWith("\"") && second.endsWith("\""))
second = second.substring(1,second.length()-1);
String first = parts.get(0).trim();
// make sure for directives we clear out any space as in "directive :=value"
if (first.endsWith(":")) {
first = first.substring(0, first.length()-1).trim()+":";
}
params.put(first, second);
}
}
return params;
}
/**
* Processes an import/export style header.. <p>
* pkg1;attrib=value;attrib=value,pkg2;attrib=value,pkg3;attrib=value
*
* @param out The collection to add each package name + attrib map to.
* @param s The data to parse
*/
private static void genericImportExportProcess(NameValueCollection out, String s){
List<String> packages = split(s, ",");
for(String pkg : packages){
List<NameValuePair> ps = genericNameWithNameValuePairProcess(pkg);
for (NameValuePair p : ps) {
out.addToCollection(p.getName(), p.getAttributes());
}
}
}
/**
* Parse an export style header.<p>
* pkg1;attrib=value;attrib=value,pkg2;attrib=value,pkg3;attrib=value2
* <p>
* Result is returned as a list, as export does allow duplicate package exports.
*
* @param s The data to parse.
* @return List of NameValuePairs, where each Name in the list is an exported package,
* with its associated Value being a NameValueMap of any attributes declared.
*/
public static List<NameValuePair> parseExportString(String s){
NameValueList retval = new NameValueList();
genericImportExportProcess(retval, s);
return retval;
}
/**
* Parse an export style header in a list.<p>
* pkg1;attrib=value;attrib=value
* pkg2;attrib=value
* pkg3;attrib=value2
* <p>
* Result is returned as a list, as export does allow duplicate package exports.
*
* @param list The data to parse.
* @return List of NameValuePairs, where each Name in the list is an exported package,
* with its associated Value being a NameValueMap of any attributes declared.
*/
public static List<NameValuePair> parseExportList(List<String> list){
NameValueList retval = new NameValueList();
for(String pkg : list){
List<NameValuePair> ps = genericNameWithNameValuePairProcess(pkg);
for (NameValuePair p : ps) {
retval.addToCollection(p.getName(), p.getAttributes());
}
}
return retval;
}
/**
* Parse an import style header.<p>
* pkg1;attrib=value;attrib=value,pkg2;attrib=value,pkg3;attrib=value
* <p>
* Result is returned as a set, as import does not allow duplicate package imports.
*
* @param s The data to parse.
* @return Map of NameValuePairs, where each Key in the Map is an imported package,
* with its associated Value being a NameValueMap of any attributes declared.
*/
public static Map<String, Map<String, String>> parseImportString(String s){
NameValueMap retval = new NameValueMap();
genericImportExportProcess(retval, s);
return retval;
}
/**
* Parse a generic capability header. For example<br>
* com.acme.myns;mylist:List<String>="nl,be,fr,uk";myver:Version=1.3;long:Long="1234";d:Double="3.14";myattr=xyz,
* com.acme.myns;myattr=abc
* @param s The header to be parsed
* @return A list of GenericMetadata objects each representing an individual capability. The values in the attribute map
* are of the specified datatype.
*/
public static List<GenericMetadata> parseCapabilityString(String s) {
return parseGenericMetadata(s);
}
/**
* Parse a generic capability header. For example<br>
* com.acme.myns;mylist:List<String>="nl,be,fr,uk";myver:Version=1.3;long:Long="1234";d:Double="3.14";myattr=xyz,
* com.acme.myns;myattr=abc
* @param s The header to be parsed
* @return A list of GenericMetadata objects each representing an individual capability. The values in the attribute map
* are of the specified datatype.
*/
public static List<GenericMetadata> parseRequirementString(String s) {
return parseGenericMetadata(s);
}
private static List<GenericMetadata> parseGenericMetadata(String s) {
List<GenericMetadata> capabilities = new ArrayList<GenericMetadata>();
List<String> entries = split(s, ",");
for(String e : entries){
List<NameValuePair> nvpList = genericNameWithNameValuePairProcess(e);
for(NameValuePair nvp : nvpList) {
String namespace = nvp.getName();
GenericMetadata cap = new GenericMetadata(namespace);
capabilities.add(cap);
Map<String, String> attrMap = nvp.getAttributes();
for (Map.Entry<String, String> entry : attrMap.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if (k.contains(":")) {
if (k.endsWith(":")) {
// a directive
cap.getDirectives().put(k.substring(0, k.length() - 1), v);
} else {
// an attribute with its datatype specified
parseTypedAttribute(k, v, cap);
}
} else {
// ordinary (String) attribute
cap.getAttributes().put(k, v);
}
}
}
}
return capabilities;
}
private static void parseTypedAttribute(String k, String v, GenericMetadata cap) {
int idx = k.indexOf(':');
String name = k.substring(0, idx);
String type = k.substring(idx + 1);
if (type.startsWith("List<") && type.endsWith(">")) {
String subtype = type.substring("List<".length(), type.length() - 1).trim();
List<Object> l = new ArrayList<Object>();
for (String s : v.split(",")) {
l.add(getTypedValue(k, subtype, s));
}
cap.getAttributes().put(name, l);
} else {
cap.getAttributes().put(name, getTypedValue(k, type.trim(), v));
}
}
private static Object getTypedValue(String k, String type, String v) {
if ("String".equals(type)) {
return v;
} else if ("Long".equals(type)) {
return Long.parseLong(v);
} else if ("Double".equals(type)) {
return Double.parseDouble(v);
} else if ("Version".equals(type)) {
return Version.parseVersion(v);
}
throw new IllegalArgumentException(k + "=" + v);
}
/**
* Parse a bundle symbolic name.<p>
* bundlesymbolicname;attrib=value;attrib=value
* <p>
*
* @param s The data to parse.
* @return NameValuePair with Name being the BundleSymbolicName,
* and Value being any attribs declared for the name.
*/
public static NameValuePair parseBundleSymbolicName(String s){
return genericNameWithNameValuePairProcess(s).get(0); // should just return the first one
}
/**
* Parse a version range..
*
* @param s
* @return VersionRange object.
* @throws IllegalArgumentException if the String could not be parsed as a VersionRange
*/
public static VersionRange parseVersionRange(String s) throws IllegalArgumentException{
return new VersionRange(s);
}
/**
* Parse a version range and indicate if the version is an exact version
*
* @param s
* @param exactVersion
* @return VersionRange object.
* @throws IllegalArgumentException if the String could not be parsed as a VersionRange
*/
public static VersionRange parseVersionRange(String s, boolean exactVersion) throws IllegalArgumentException{
return new VersionRange(s, exactVersion);
}
/**
* Generate a filter from a set of attributes. This filter will be suitable
* for presentation to OBR This means that, due to the way OBR works, it
* will include a stanza of the form, (mandatory:<*mandatoryAttribute)
* Filter strings generated by this method will therefore tend to break the
* standard OSGi Filter class. The OBR stanza can be stripped out later if
* required.
*
* @param attribs
* @return filter string
*/
public static String generateFilter(Map<String, String> attribs) {
StringBuilder filter = new StringBuilder("(&");
boolean realAttrib = false;
StringBuffer realAttribs = new StringBuffer();
if (attribs == null) {
attribs = new HashMap<String, String>();
}
for (Map.Entry<String, String> attrib : attribs.entrySet()) {
String attribName = attrib.getKey();
if (attribName.endsWith(":")) {
// skip all directives. It is used to affect the attribs on the
// filter xml.
} else if ((Constants.VERSION_ATTRIBUTE.equals(attribName))
|| (Constants.BUNDLE_VERSION_ATTRIBUTE.equals(attribName))) {
// version and bundle-version attrib requires special
// conversion.
realAttrib = true;
VersionRange vr = ManifestHeaderProcessor
.parseVersionRange(attrib.getValue());
filter.append("(" + attribName + ">=" + vr.getMinimumVersion());
if (vr.getMaximumVersion() != null) {
filter.append(")(" + attribName + "<=");
filter.append(vr.getMaximumVersion());
}
if (vr.getMaximumVersion() != null && vr.isMinimumExclusive()) {
filter.append(")(!(" + attribName + "=");
filter.append(vr.getMinimumVersion());
filter.append(")");
}
if (vr.getMaximumVersion() != null && vr.isMaximumExclusive()) {
filter.append(")(!(" + attribName + "=");
filter.append(vr.getMaximumVersion());
filter.append(")");
}
filter.append(")");
} else if (NESTED_FILTER_ATTRIBUTE.equals(attribName)) {
// Filters go in whole, no formatting needed
realAttrib = true;
filter.append(attrib.getValue());
} else if (Constants.OBJECTCLASS.equals(attribName)) {
realAttrib = true;
// objectClass has a "," separated list of interfaces
String[] values = attrib.getValue().split(",");
for (String s : values)
filter.append("(" + Constants.OBJECTCLASS + "=" + s + ")");
} else {
// attribName was not version..
realAttrib = true;
filter.append("(" + attribName + "=" + attrib.getValue() + ")");
// store all attributes in order to build up the mandatory
// filter and separate them with ", "
// skip bundle-symbolic-name in the mandatory directive query
if (!!!Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE
.equals(attribName)) {
realAttribs.append(attribName);
realAttribs.append(", ");
}
}
}
/*
* The following is how OBR makes mandatory attributes work, we require
* that the set of mandatory attributes on the export is a subset of (or
* equal to) the set of the attributes we supply.
*/
if (realAttribs.length() > 0) {
String attribStr = (realAttribs.toString()).trim();
// remove the final ,
if ((attribStr.length() > 0) && (attribStr.endsWith(","))) {
attribStr = attribStr.substring(0, attribStr.length() - 1);
}
// build the mandatory filter, e.g.(mandatory:<*company, local)
filter.append("(" + Constants.MANDATORY_DIRECTIVE + ":" + "<*"
+ attribStr + ")");
}
// Prune (& off the front and ) off end
String filterString = filter.toString();
int openBraces = 0;
for (int i = 0; openBraces < 3; i++) {
i = filterString.indexOf('(', i);
if (i == -1) {
break;
} else {
openBraces++;
}
}
if (openBraces < 3 && filterString.length() > 2) {
filter.delete(0, 2);
} else {
filter.append(")");
}
String result = "";
if (realAttrib != false) {
result = filter.toString();
}
return result;
}
/**
* Generate a filter from a set of attributes. This filter will be suitable
* for presentation to OBR. This means that, due to the way OBR works, it will
* include a stanza of the form, (mandatory:<*mandatoryAttribute) Filter
* strings generated by this method will therefore tend to break the standard
* OSGi Filter class. The OBR stanza can be stripped out later if required.
*
* We may wish to consider relocating this method since VersionRange has its
* own top level class.
*
* @param type
* @param name
* @param attribs
* @return filter string
*/
public static String generateFilter(String type, String name,
Map<String, String> attribs) {
StringBuffer filter = new StringBuffer();
String result;
// shortcut for the simple case with no attribs.
if (attribs == null || attribs.isEmpty())
filter.append("(" + type + "=" + name + ")");
else {
// process all the attribs passed.
// find out whether there are attributes on the filter
filter.append("(&(" + type + "=" + name + ")");
String filterString = generateFilter(attribs);
int start = 0;
int end = filterString.length();
if (filterString.startsWith("(&")) {
start = 2;
end--;
}
if ("".equals(filterString)) {
filter.delete(0, 2);
} else {
filter.append(filterString, start, end);
filter.append(")");
}
}
result = filter.toString();
return result;
}
private static Map<String, String> parseFilterList(String filter) {
Map<String, String> result = new HashMap<String, String>();
Set<String> negatedVersions = new HashSet<String>();
Set<String> negatedBundleVersions = new HashSet<String>();
String lowerVersion = null;
String upperVersion = null;
String lowerBundleVersion = null;
String upperBundleVersion = null;
Matcher m = FILTER_ATTR.matcher(filter);
while (m.find()) {
boolean negation = m.group(1) != null;
String attr = m.group(2);
String op = m.group(3);
String value = m.group(4);
if (Constants.VERSION_ATTRIBUTE.equals(attr)) {
if (negation) {
negatedVersions.add(value);
} else {
if (GREATER_EQ_OP.equals(op))
lowerVersion = value;
else if (LESS_EQ_OP.equals(op))
upperVersion = value;
else
throw new IllegalArgumentException();
}
} else if (Constants.BUNDLE_VERSION_ATTRIBUTE.equals(attr)) {
// bundle-version is like version, but may be specified at the
// same time
// therefore we have similar code with separate variables
if (negation) {
negatedBundleVersions.add(value);
} else {
if (GREATER_EQ_OP.equals(op))
lowerBundleVersion = value;
else if (LESS_EQ_OP.equals(op))
upperBundleVersion = value;
else
throw new IllegalArgumentException();
}
} else {
result.put(attr, value);
}
}
if (lowerVersion != null) {
StringBuilder versionAttr = new StringBuilder(lowerVersion);
if (upperVersion != null) {
versionAttr.append(",").append(upperVersion).insert(0,
negatedVersions.contains(lowerVersion) ? '(' : '[').append(
negatedVersions.contains(upperVersion) ? ')' : ']');
}
result.put(Constants.VERSION_ATTRIBUTE, versionAttr.toString());
}
// Do it again for bundle-version
if (lowerBundleVersion != null) {
StringBuilder versionAttr = new StringBuilder(lowerBundleVersion);
if (upperBundleVersion != null) {
versionAttr.append(",").append(upperBundleVersion).insert(0,
negatedBundleVersions.contains(lowerBundleVersion) ? '(' : '[')
.append(
negatedBundleVersions.contains(upperBundleVersion) ? ')' : ']');
}
result.put(Constants.BUNDLE_VERSION_ATTRIBUTE, versionAttr.toString());
}
return result;
}
public static Map<String,String> parseFilter(String filter)
{
Map<String,String> result;
if (filter.startsWith("(&")) {
result = parseFilterList(filter.substring(2, filter.length()-1));
} else {
result = parseFilterList(filter);
}
return result;
}
}
| 7,877 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/manifest/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 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.util.manifest;
public class Constants {
public static final String MANIFEST_VERSION="1.0";
}
| 7,878 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/io/IOUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.io;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.aries.util.filesystem.IFile;
import org.apache.aries.util.internal.MessageUtil;
public class IOUtils
{
/**
* Copy an InputStream to an OutputStream and close the InputStream afterwards.
*/
public static void copy(InputStream in, OutputStream out) throws IOException
{
try {
copyAndDoNotCloseInputStream(in, out);
}
finally {
close(in);
}
}
/**
* Copy an InputStream to an OutputStream and do not close the InputStream afterwards.
*/
public static void copyAndDoNotCloseInputStream(InputStream in, OutputStream out) throws IOException
{
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1)
out.write(b,0,len);
}
/**
* Close some xStream for good :)
*/
public static void close(Closeable c)
{
try {
if (c != null)
c.close();
}
catch (IOException e) {
c = null;
}
}
/**
* A special version of close() for ZipFiles, which don't implement Closeable.
* @param file the file to close. ZipFiles seem prone to file locking problems
* on Windows, so to aid diagnostics we throw, not swallow, any exceptions.
*/
public static void close(ZipFile file) throws IOException
{
if (file != null) file.close();
}
public static OutputStream getOutputStream(File outputDir, String relativePath) throws IOException
{
int lastSeparatorIndex = relativePath.replace(File.separatorChar,'/').lastIndexOf("/");
String dirName = null;
String fileName = null;
File outputDirectory;
if (lastSeparatorIndex != -1)
{
dirName = relativePath.substring(0, lastSeparatorIndex);
fileName = relativePath.substring(lastSeparatorIndex + 1);
outputDirectory = new File(outputDir, dirName);
if (!!!outputDirectory.exists() && !!!outputDirectory.mkdirs())
throw new IOException(MessageUtil.getMessage("UTIL0015E", relativePath));
}
else
{
outputDirectory = outputDir;
fileName = relativePath;
}
File outputFile = new File(outputDirectory, fileName);
return new FileOutputStream(outputFile);
}
/**
* Write the given InputStream to a file given by a root directory (outputDir) and a relative directory.
* Necessary subdirectories will be created. This method will close the supplied InputStream.
*/
public static void writeOut(File outputDir, String relativePath, InputStream content) throws IOException
{
OutputStream out = null;
try {
out = getOutputStream(outputDir, relativePath);
IOUtils.copy(content, out);
}
finally {
close(out);
}
}
/**
* Write the given InputStream to a file given by a root directory (outputDir) and a relative directory.
* Necessary subdirectories will be created. This method will not close the supplied InputStream.
*/
public static void writeOutAndDontCloseInputStream(File outputDir, String relativePath, InputStream content) throws IOException
{
OutputStream out = null;
try {
out = getOutputStream(outputDir, relativePath);
IOUtils.copyAndDoNotCloseInputStream(content, out);
}
finally {
close(out);
}
}
/**
* Zip up all contents of rootDir (recursively) into targetStream
*/
@SuppressWarnings("unchecked")
public static void zipUp (File rootDir, OutputStream targetStream) throws IOException
{
ZipOutputStream out = null;
try {
out = new ZipOutputStream (targetStream);
zipUpRecursive(out, "", rootDir, (Set<String>) Collections.EMPTY_SET);
} finally {
close(out);
}
}
/**
* Zip up all contents of rootDir (recursively) into targetFile
*/
@SuppressWarnings("unchecked")
public static void zipUp(File rootDir, File targetFile) throws IOException
{
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(targetFile));
zipUpRecursive(out, "", rootDir, (Set<String>) Collections.EMPTY_SET);
}
finally {
close(out);
}
}
/**
* Jar up all the contents of rootDir (recursively) into targetFile and add the manifest
*/
public static void jarUp(File rootDir, File targetFile, Manifest manifest) throws IOException
{
JarOutputStream out = null;
try {
out = new JarOutputStream(new FileOutputStream(targetFile), manifest);
zipUpRecursive(out, "", rootDir, new HashSet<String>(Arrays.asList("META-INF/MANIFEST.MF")));
}
finally {
close(out);
}
}
/**
* Helper method used by zipUp
*/
private static void zipUpRecursive(ZipOutputStream out, String prefix,
File directory, Set<String> filesToExclude) throws IOException
{
File[] files = directory.listFiles();
if (files != null)
{
for (File f : files)
{
String fileName;
if (f.isDirectory())
fileName = prefix + f.getName() + "/";
else
fileName = prefix + f.getName();
if (filesToExclude.contains(fileName))
continue;
ZipEntry ze = new ZipEntry(fileName);
ze.setSize(f.length());
ze.setTime(f.lastModified());
out.putNextEntry(ze);
if (f.isDirectory())
zipUpRecursive(out, fileName, f, filesToExclude);
else
{
IOUtils.copy(new FileInputStream(f), out);
}
}
}
}
/**
* Do rm -rf
*/
public static boolean deleteRecursive(File root)
{
if (!!!root.exists())
return false;
else if (root.isFile())
return root.delete();
else {
boolean result = true;
for (File f : root.listFiles())
{
result = deleteRecursive(f) && result;
}
return root.delete() && result;
}
}
/**
* Unpack the zip file into the outputDir
* @param zip
* @param outputDir
* @return true if the zip was expanded, false if the zip was found not to be a zip
* @throws IOException when there are unexpected issues handling the zip files.
*/
public static boolean unpackZip(IFile zip, File outputDir) throws IOException{
boolean success=true;
//unpack from fileOnDisk into bundleDir.
ZipInputStream zis = null;
try{
boolean isZip = false;
ZipEntry zipEntry = null;
try {
zis = new ZipInputStream (zip.open());
zipEntry = zis.getNextEntry();
isZip = zipEntry != null;
} catch (ZipException e) { // It's not a zip - that's ok, we'll return that below.
isZip = false;
} catch (UnsupportedOperationException e) { // This isn't declared, but is thrown in practice
isZip = false; // It's not a zip - that's ok, we'll return that below.
}
if(isZip){
do {
File outFile = new File(outputDir, zipEntry.getName());
String canonicalizedDir = outputDir.getCanonicalPath();
if (!canonicalizedDir.endsWith(File.separator)) {
canonicalizedDir += File.separator;
}
if (!outFile.getCanonicalPath().startsWith(canonicalizedDir)) {
throw new IOException("The output file is not contained in the destination directory");
}
if (!zipEntry.isDirectory()) {
writeOutAndDontCloseInputStream(outputDir, zipEntry.getName(), zis);
}
zis.closeEntry();
zipEntry = zis.getNextEntry();
} while (zipEntry != null);
}else{
success=false;
}
}finally{
IOUtils.close(zis);
}
return success;
}
}
| 7,879 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/io/RememberingInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.aries.util.internal.MessageUtil;
/**
* This class can be used to buffer an arbitrary amount of content from an input stream and be able to reset to
* the start.
*/
public class RememberingInputStream extends InputStream {
/** The size by which to grow our array */
private static final int bufferGrowthSize = 0x4000;
/** The bytes that have been read so far */
private byte[] bytes = new byte[bufferGrowthSize];
/** Index of the next empty entry in the array */
private int pos = 0;
/** The input stream that actually holds the data */
private final InputStream stream;
/** Index of the last valid byte in the byte array */
private int maxRead = -1;
/** The point to reset to */
private int markPoint = -1;
public RememberingInputStream(InputStream in) throws IOException{
stream = in;
// Pre fill with data that we know we're going to need - it's
// more efficient than the single byte reads are - hopefully
// someone reading a lot of data will do reads in bulk
maxRead = stream.read(bytes) - 1;
}
@Override
public int read() throws IOException {
if(pos <= maxRead)
{
//We can't return the byte directly, because it is signed
//We can pretend this is an unsigned byte by using boolean
//& to set the low end byte of an int.
return bytes[pos++] & 0xFF;
} else {
int i = stream.read();
if(i<0)
return i;
ensureCapacity(0);
bytes[pos++] = (byte) i;
return i;
}
}
/**
* Ensure our internal byte array can hold enough data
* @param i one less than the number of bytes that need
* to be held.
*/
private void ensureCapacity(int i) {
if((pos + i) >= bytes.length) {
byte[] tmp = bytes;
int newLength = bytes.length + bufferGrowthSize;
while(newLength < pos + i) {
newLength += bufferGrowthSize;
}
bytes = new byte[newLength];
System.arraycopy(tmp, 0, bytes, 0, (maxRead >= pos) ? maxRead + 1 : pos);
}
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if(pos <= maxRead) {
if(pos + len <= maxRead)
{
System.arraycopy(bytes, pos, b, off, len);
pos += len;
return len;
} else {
int lengthLeftOfBuffer = (maxRead - pos) + 1;
System.arraycopy(bytes, pos, b, off, lengthLeftOfBuffer);
int read = stream.read(b, off + lengthLeftOfBuffer, len - lengthLeftOfBuffer);
if(read < 0) {
pos += lengthLeftOfBuffer;
return lengthLeftOfBuffer;
}
ensureCapacity(lengthLeftOfBuffer + read - 1);
System.arraycopy(b, off + lengthLeftOfBuffer, bytes, maxRead + 1, read);
pos += (lengthLeftOfBuffer + read);
return lengthLeftOfBuffer + read;
}
} else {
int i = stream.read(b, off, len);
if(i<0)
return i;
ensureCapacity(i - 1);
System.arraycopy(b, off, bytes, pos, i);
pos += i;
return i;
}
}
@Override
public long skip(long n) throws IOException {
throw new IOException(MessageUtil.getMessage("UTIL0017E"));
}
@Override
public int available() throws IOException {
if(pos <= maxRead)
return (maxRead - pos) + 1;
else
return stream.available();
}
@Override
public synchronized void mark(int readlimit) {
markPoint = pos;
}
@Override
public synchronized void reset() throws IOException {
if(maxRead < pos)
maxRead = pos - 1;
pos = markPoint;
}
@Override
public boolean markSupported() {
return true;
}
/**
* Noop. Does not close the passed in archive, which is kept open for further reading.
*/
@Override
public void close() throws IOException {
//No op, don't close the parent.
}
/**
* Actually closes the underlying InputStream. Call this method instead of close, which is implemented as a no-op.
* Alternatively call close directly on the parent.
* @throws IOException
*/
public void closeUnderlying() throws IOException {
stream.close();
}
} | 7,880 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/internal/DefaultWorker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.internal;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.IdentityHashMap;
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.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.FrameworkUtil;
public class DefaultWorker implements FrameworkUtilWorker, BundleListener, FrameworkListener
{
private Map<Bundle, ClassLoader> classLoaders = new IdentityHashMap<Bundle, ClassLoader>();
private static final Bundle myFrameworkBundle;
static
{
Bundle bundle = FrameworkUtil.getBundle(DefaultWorker.class);
BundleContext myContext = bundle == null? null: bundle.getBundleContext();
// This may be created during framework shutdown when the bundle context is null.
// So we need to cope and not NPE during construction.
if (myContext != null) {
myFrameworkBundle = myContext.getBundle(0);
} else {
myFrameworkBundle = null;
}
}
public ClassLoader getClassLoader(final Bundle b)
{
ClassLoader cl = get(b);
if (cl != null) return cl;
// so first off try to get the real classloader. We can do this by loading a known class
// such as the bundle activator. There is no guarantee this will work, so we have a back door too.
String activator = (String) b.getHeaders().get(Constants.BUNDLE_ACTIVATOR);
if (activator != null) {
try {
Class<?> clazz = b.loadClass(activator);
// so we have the class, but it could have been imported, so we make sure the two bundles
// are the same. A reference check should work here because there will be one.
Bundle activatorBundle = FrameworkUtil.getBundle(clazz);
if (activatorBundle == b) {
cl = clazz.getClassLoader();
}
} catch (ClassNotFoundException e) {
}
}
if (cl == null) {
// ok so we haven't found a class loader yet, so we need to create a wapper class loader
cl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return new BundleToClassLoaderAdapter(b);
}
});
}
if (cl != null) {
setupListener(b);
cl = put(b, cl);
}
return cl;
}
private void setupListener(Bundle b)
{
// So we need to cope with multiple equinox frameworks, so we can't just listen to our
// BundleContext. Instead we add a listener to Bundle 0 of the framework bundle associated
// with the bundle passed in.
BundleContext ctx = b.getBundleContext().getBundle(0).getBundleContext();
ctx.addBundleListener(this);
ctx.addFrameworkListener(this);
}
private synchronized ClassLoader put(Bundle b, ClassLoader cl)
{
// If the bundle is uninstalled or installed then there is no classloader so we should
// just return null. This is a last second sanity check to avoid memory leaks that could
// occur if a bundle is uninstalled or unresolved while someone is calling getClassLoader
if (b.getState() == Bundle.UNINSTALLED || b.getState() == Bundle.INSTALLED) return null;
ClassLoader previous = classLoaders.put(b, cl);
// OK, so we could cause a replace to occur here, so we want to check to
// see if previous is not null. If it is not null we need to do a replace
// and return the previous classloader. This ensures we have one classloader
// in use for a bundle.
if (previous != null) {
cl = previous;
classLoaders.put(b, cl);
}
return cl;
}
private synchronized ClassLoader get(Bundle b)
{
return classLoaders.get(b);
}
private synchronized void remove(Bundle bundle)
{
classLoaders.remove(bundle);
}
public boolean isValid()
{
return true;
}
public void bundleChanged(BundleEvent event)
{
if (event.getType() == BundleEvent.UNINSTALLED || event.getType() == BundleEvent.UNRESOLVED) {
Bundle b = event.getBundle();
remove(b);
if (b.getBundleId() == 0) {
clearBundles(b);
}
}
}
private void clearBundles(Bundle b) {
// we have been told about the system bundle, so we need to clear up any state for this framework.
BundleContext ctx = b.getBundleContext();
ctx.removeBundleListener(this);
Bundle[] bundles = ctx.getBundles();
for (Bundle bundle : bundles) {
remove(bundle);
}
}
public void frameworkEvent(FrameworkEvent event)
{
if (event.getType() == FrameworkEvent.STOPPED) {
Bundle b = event.getBundle();
if (b == myFrameworkBundle) {
classLoaders.clear();
} else if (b != null) {
clearBundles(b);
}
b.getBundleContext().removeFrameworkListener(this);
}
}
} | 7,881 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/internal/R43Worker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.internal;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
/**
* @version $Rev$ $Date$
*/
public class R43Worker implements FrameworkUtilWorker {
static {
BundleWiring.class.getClassLoader();
}
public ClassLoader getClassLoader(Bundle b) {
return b.adapt(BundleWiring.class).getClassLoader();
}
public boolean isValid() {
return true;
}
}
| 7,882 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/internal/EquinoxWorker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.internal;
import java.lang.reflect.InvocationTargetException;
import org.osgi.framework.Bundle;
public class EquinoxWorker extends DefaultWorker implements FrameworkUtilWorker {
public ClassLoader getClassLoader(Bundle b)
{
ClassLoader result = null;
try {
Object bundleLoaderProxy = invoke(b, "getLoaderProxy");
if (bundleLoaderProxy != null) {
Object bundleLoader = invoke(bundleLoaderProxy, "getBasicBundleLoader");
if (bundleLoader != null) {
Object bundleClassLoader = invoke(bundleLoader, "createClassLoader");
if (bundleClassLoader instanceof ClassLoader) {
result = (ClassLoader)bundleClassLoader;
}
}
}
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
}
return result;
}
private Object invoke(Object targetObject, String method) throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException
{
return targetObject.getClass().getDeclaredMethod(method).invoke(targetObject);
}
}
| 7,883 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/internal/BundleToClassLoaderAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.internal;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleReference;
public class BundleToClassLoaderAdapter extends ClassLoader implements BundleReference
{
private final Bundle b;
public BundleToClassLoaderAdapter(Bundle bundle)
{
b = bundle;
}
@Override
public URL getResource(final String name)
{
return AccessController.doPrivileged(new PrivilegedAction<URL>() {
public URL run()
{
return b.getResource(name);
}
});
}
@Override
public InputStream getResourceAsStream(String name)
{
URL url = getResource(name);
InputStream result = null;
if (url != null) {
try {
result = url.openStream();
} catch (IOException e) {
}
}
return result;
}
@Override
public Enumeration<URL> getResources(final String name) throws IOException
{
Enumeration<URL> urls;
try {
urls = AccessController.doPrivileged(new PrivilegedExceptionAction<Enumeration<URL>>() {
public Enumeration<URL> run() throws IOException
{
return b.getResources(name);
}
});
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
if (cause instanceof IOException) throw (IOException)cause;
if (cause instanceof RuntimeException) throw (RuntimeException)cause;
IOException ioe = new IOException(name);
ioe.initCause(cause);
throw ioe;
}
if (urls == null) {
urls = Collections.enumeration(new ArrayList<URL>());
}
return urls;
}
/*
* Notes we overwrite loadClass rather than findClass because we don't want to delegate
* to the default classloader, only the bundle.
*
* Also note that ClassLoader#loadClass(String) by javadoc on ClassLoader delegates
* to this method, so we don't need to overwrite it separately.
*
* (non-Javadoc)
* @see java.lang.ClassLoader#loadClass(java.lang.String, boolean)
*/
@Override
public Class<?> loadClass(final String name, boolean resolve) throws ClassNotFoundException
{
try {
Class<?> result = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
public Class<?> run() throws ClassNotFoundException
{
return b.loadClass(name);
}
});
if (resolve) resolveClass(result);
return result;
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
if (cause instanceof ClassNotFoundException) throw (ClassNotFoundException)cause;
if (cause instanceof RuntimeException) throw (RuntimeException)cause;
throw new ClassNotFoundException(name, cause);
}
}
public Bundle getBundle()
{
return b;
}
} | 7,884 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/internal/FrameworkUtilWorker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.internal;
import org.osgi.framework.Bundle;
public interface FrameworkUtilWorker {
ClassLoader getClassLoader(Bundle b);
boolean isValid();
}
| 7,885 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/internal/MessageUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.internal;
import java.text.MessageFormat;
import java.util.ResourceBundle;
public class MessageUtil {
/** The resource bundle for blueprint messages */
private final static ResourceBundle messages =
ResourceBundle.getBundle("org.apache.aries.util.messages.UTILmessages");
/**
* Resolve a message from the bundle, including any necessary formatting.
*
* @param key
* the message key.
* @param inserts
* any required message inserts.
* @return the message translated into the server local.
*/
public static final String getMessage(String key, Object... inserts) {
String msg = messages.getString(key);
if (inserts.length > 0)
msg = MessageFormat.format(msg, inserts);
return msg;
}
}
| 7,886 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/internal/FelixWorker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.internal;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
public final class FelixWorker extends DefaultWorker implements FrameworkUtilWorker
{
private static Method getCurrentModuleMethod;
private static Method getClassLoader;
private static Class<?> moduleClass;
static {
Bundle b = FrameworkUtil.getBundle(FelixWorker.class);
try {
getCurrentModuleMethod = b.getClass().getDeclaredMethod("getCurrentModule");
moduleClass = b.getClass().getClassLoader().loadClass("org.apache.felix.framework.ModuleImpl");
getClassLoader = moduleClass.getDeclaredMethod("getClassLoader");
getCurrentModuleMethod.setAccessible(true);
getClassLoader.setAccessible(true);
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
} catch (ClassNotFoundException e) {
}
}
public ClassLoader getClassLoader(Bundle b)
{
if (getCurrentModuleMethod != null) {
try {
Object result = getCurrentModuleMethod.invoke(b);
if (result != null && moduleClass.isInstance(result)) {
Object cl = getClassLoader.invoke(result);
if (cl instanceof ClassLoader) return (ClassLoader) cl;
}
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return null;
}
public boolean isValid()
{
return getCurrentModuleMethod != null && moduleClass != null && getClassLoader != null;
}
}
| 7,887 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/tracker/BundleTrackerFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.tracker;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.osgi.framework.Version;
import org.osgi.util.tracker.BundleTracker;
/**
* This is the factory for BundleTracker
*/
@SuppressWarnings("rawtypes")
public class BundleTrackerFactory {
private static ConcurrentHashMap<String, List<BundleTracker>> btMap = new ConcurrentHashMap<String, List<BundleTracker>>();
/**
* get bundle tracker based on bundle name and version
*
* @param bundleScope
* composite bundle's - SymbolicName_Version
* @return the list of bundle tracker associated with the bundle scope
*/
public static List<BundleTracker> getBundleTrackerList(String bundleScope) {
return (List<BundleTracker>) btMap.get(bundleScope);
}
/**
* get bundle tracker based on composite bundle's symbolicName and version
*
* @param symbolicName
* composite bundle's symbolicName
* @param version
* composite bundle's version
* @return the list of bundle tracker associated with the bundle scope
*/
public static List<BundleTracker> getBundleTrackerList(String symbolicName,
Version version) {
return (List<BundleTracker>) btMap.get(symbolicName + "_"
+ version.toString());
}
/**
* get all bundle tracker registered in this factory
*
* @return all the trackers registered. The collection contains a list of BundleTracker for each bundle scope.
*/
public static Collection<List<BundleTracker>> getAllBundleTracker() {
return btMap.values();
}
/**
* register the bundle tracker
*
* @param bundleScope
* composite bundle's SymbolicName_Version
* @param bt
* the bundle tracker to be registered
*/
public static void registerBundleTracker(String bundleScope,
BundleTracker bt) {
List<BundleTracker> list = btMap.get(bundleScope);
if (list == null) {
list = new ArrayList<BundleTracker>();
}
list.add(bt);
btMap.putIfAbsent(bundleScope, list);
}
/**
* unregister and close the bundle tracker(s) associated with composite
* bundle's - SymbolicName_Version
*
* @param bundleScope
* composite bundle's - SymbolicName_Version
*/
public static void unregisterAndCloseBundleTracker(String bundleScope) {
List<BundleTracker> list = btMap.get(bundleScope);
if (list == null) {
return;
} else {
for (BundleTracker bt : list) {
bt.close();
}
}
btMap.remove(bundleScope);
}
} | 7,888 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/tracker/InternalRecursiveBundleTracker.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.tracker;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.service.framework.CompositeBundle;
import org.osgi.util.tracker.BundleTracker;
import org.osgi.util.tracker.BundleTrackerCustomizer;
/**
* A BundleTracker which will track bundles in the given context, and also
* bundles in any child contexts. This should be used instead of the
* normal non-recursive BundleTracker when registering bundle tracker
* customizers.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class InternalRecursiveBundleTracker extends BundleTracker
{
private final int mask;
private final ConcurrentMap<String,String> alreadyRecursedContexts = new ConcurrentHashMap<String, String>();
private final BundleTrackerCustomizer customizer;
private final boolean nested;
public InternalRecursiveBundleTracker(BundleContext context, int stateMask,
BundleTrackerCustomizer customizer, boolean nested)
{
super(context, stateMask, null);
mask = stateMask;
this.customizer = customizer;
this.nested = nested;
}
/*
* (non-Javadoc)
* @see org.osgi.util.tracker.BundleTracker#addingBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent)
*/
@Override
public Object addingBundle(Bundle b, BundleEvent event)
{
Object o = null;
if (b instanceof CompositeBundle) {
customizedProcessBundle(this, b, event, false);
o = b;
} else if (nested) {
// Delegate to our customizer for normal bundles
if (customizer != null) {
o = customizer.addingBundle(b, event);
}
}
return o;
}
/*
* (non-Javadoc)
* @see org.osgi.util.tracker.BundleTracker#modifiedBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent, java.lang.Object)
*/
@Override
public void modifiedBundle(Bundle b, BundleEvent event, Object object)
{
if (b instanceof CompositeBundle) {
customizedProcessBundle(this, b, event, false);
} else {
// Delegate to our customizer for normal bundles
if (customizer != null) {
customizer.modifiedBundle(b, event, object);
}
}
}
/*
* (non-Javadoc)
* @see org.osgi.util.tracker.BundleTracker#removedBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent, java.lang.Object)
*/
@Override
public void removedBundle(Bundle b, BundleEvent event, Object object)
{
if (b instanceof CompositeBundle) {
customizedProcessBundle(this, b, event, true);
} else {
if (customizer != null) {
customizer.removedBundle(b, event, object);
}
}
}
protected void customizedProcessBundle(BundleTrackerCustomizer btc, Bundle b, BundleEvent event, boolean removing)
{
if (b instanceof CompositeBundle) {
CompositeBundle cb = (CompositeBundle) b;
// check if the compositeBundle is already tracked in the
// BundleTrackerFactory
String bundleScope = cb.getSymbolicName() + "_" + cb.getVersion().toString();
List<BundleTracker> btList = BundleTrackerFactory.getBundleTrackerList(bundleScope);
// bundle is already active and there is no event associated
// this can happen when bundle is first time added to the tracker
// or when the tracker is being closed.
if (event == null && !!!removing) {
if (cb.getState() == Bundle.INSTALLED || cb.getState() == Bundle.RESOLVED || cb.getState() == Bundle.STARTING || cb.getState() == Bundle.ACTIVE) {
openTracker(btc, cb, bundleScope, mask);
}
} else {
// if we are removing, or the event is of the right type then we need to shutdown.
if (removing || event.getType() == BundleEvent.STOPPED || event.getType() == BundleEvent.UNRESOLVED || event.getType() == BundleEvent.UNINSTALLED) {
// if CompositeBundle is being stopped, let's remove the bundle
// tracker(s) associated with the composite bundle
String bundleId = b.getSymbolicName()+"/"+b.getVersion();
alreadyRecursedContexts.remove(bundleId);
if (btList != null) {
// unregister the bundlescope off the factory and close
// bundle trackers
BundleTrackerFactory.unregisterAndCloseBundleTracker(bundleScope);
}
} else if (event.getType() == BundleEvent.INSTALLED || event.getType() == BundleEvent.RESOLVED || event.getType() == BundleEvent.STARTING) {
openTracker(btc, cb, bundleScope, mask);
}
}
}
}
private synchronized void openTracker(BundleTrackerCustomizer btc, CompositeBundle cb,
String bundleScope, int stateMask)
{
// let's process each of the bundle in the CompositeBundle
BundleContext compositeBundleContext = cb.getCompositeFramework().getBundleContext();
String bundleId = cb.getSymbolicName()+"/"+cb.getVersion();
if (alreadyRecursedContexts.putIfAbsent(bundleId, bundleId) == null) {
// let's track each of the bundle in the CompositeBundle
BundleTracker bt = new InternalRecursiveBundleTracker(compositeBundleContext, stateMask,
customizer, true);
bt.open();
BundleTrackerFactory.registerBundleTracker(bundleScope, bt);
}
}
}
| 7,889 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/tracker/RecursiveBundleTracker.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.tracker;
import org.apache.aries.util.tracker.hook.BundleHookBundleTracker;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.BundleTracker;
import org.osgi.util.tracker.BundleTrackerCustomizer;
/**
* <p>This class supports the tracking of composite bundles. It allows clients to ignore any
* events related to framework bundles, as it will automatically handle these events. In
* order to use this class clients must create a subclass and implement the methods of the
* <code>BundleTrackerCustomizer</code> interface. In spite of this, instances of this class
* MUST NOT be passed as a parameter to any <code>BundleTracker</code>.</p>
* <p>
* The model for using this is that classes should instantiate it
* and pass it a 'vanilla' bundle tracker.
*
* @author pradine
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public final class RecursiveBundleTracker {
private static final int COMPOSITE_BUNDLE_MASK =
Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.ACTIVE | Bundle.STOPPING;
private final BundleTracker tracker;
private final BundleTracker compositeTracker;
/**
* Constructor
*
* @param context - The <code>BundleContext</code> against which the tracking is done.
* @param stateMask - The bit mask of the ORing of the bundle states to be tracked. The
* mask must contain the flags <code>Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.ACTIVE | Bundle.STOPPING</code>
* as a minimum.
* @throws IllegalArgumentException - If the provided bit mask does not contain required
* flags
*/
public RecursiveBundleTracker(BundleContext context, int stateMask, BundleTrackerCustomizer customizer) {
//This test only makes sense for composite bundles, but in the interests of more consistent behavior lets leave it.
// We always need INSTALLED events so we can recursively listen to the frameworks
if ((stateMask & COMPOSITE_BUNDLE_MASK) != COMPOSITE_BUNDLE_MASK)
throw new IllegalArgumentException();
BundleTracker tracker = null;
try {
//R43, equinox composite bundles seem to produce appropriate bundle event hook notifications
tracker = new BundleHookBundleTracker(context, stateMask, customizer);
} catch (Throwable e) {
}
if (areMultipleFrameworksAvailable(context)) {
compositeTracker = new InternalRecursiveBundleTracker(context, stateMask, customizer, tracker == null);
} else {
compositeTracker = null;
}
if (tracker == null && compositeTracker == null) {
//R42
tracker = new BundleTracker(context, stateMask, customizer);
}
this.tracker = tracker;
}
/*
* Checks whether or not the framework supports composite bundles. The only
* known supporting framework is Equinox. When the Equinox specific
* framework property osgi.resolverMode is set to "strict", the
* CompositeBundleFactory service is registered, but the x-internal
* org.osgi.service.framework package is not exported, thus the need for
* the additional Class.forName check.
*/
private static boolean areMultipleFrameworksAvailable(BundleContext context) {
String compositeBundleFactory = "org.osgi.service.framework.CompositeBundleFactory";
try {
Class.forName(compositeBundleFactory);
} catch (ClassNotFoundException e) {
return false;
}
ServiceReference sr = context.getServiceReference(compositeBundleFactory);
return sr != null;
}
/**
* Start tracking bundles that match the bit mask provided at creation time.
*
* @see BundleTracker#open()
*/
public void open() {
if (tracker != null) {
tracker.open();
}
if (compositeTracker != null) {
compositeTracker.open();
}
}
/**
* Stop the tracking of bundles
*
* @see BundleTracker#close()
*/
public void close() {
if (tracker != null) {
tracker.close();
}
if (compositeTracker != null) {
compositeTracker.close();
}
}
}
| 7,890 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/tracker/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.util.tracker;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
@SuppressWarnings({"rawtypes", "unchecked"})
public final class SingleServiceTracker<T>
{
public static interface SingleServiceListener
{
public void serviceFound();
public void serviceLost();
public void serviceReplaced();
}
private final BundleContext ctx;
private final String className;
private final AtomicReference<T> service = new AtomicReference<T>();
private final AtomicReference<ServiceReference> ref = new AtomicReference<ServiceReference>();
private final AtomicBoolean open = new AtomicBoolean(false);
private final SingleServiceListener serviceListener;
private String filterString;
private boolean isCustomFilter;
private final ServiceListener listener = new ServiceListener()
{
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);
}
}
}
};
public SingleServiceTracker(BundleContext context, Class<T> clazz, SingleServiceListener sl)
{
ctx = context;
this.className = clazz.getName();
serviceListener = sl;
this.filterString = '(' + Constants.OBJECTCLASS + '=' + className + ')';
}
public SingleServiceTracker(BundleContext context, Class<T> clazz, String filterString, SingleServiceListener sl) throws InvalidSyntaxException
{
this(context, clazz, sl);
if (filterString != null) {
this.filterString = "(&" + this.filterString + filterString + ')';
isCustomFilter = true;
}
FrameworkUtil.createFilter(this.filterString);
}
public T getService()
{
return service.get();
}
public ServiceReference getServiceReference()
{
return ref.get();
}
public void open()
{
if (open.compareAndSet(false, true)) {
try {
ctx.addServiceListener(listener, filterString);
findMatchingReference(null);
} catch (InvalidSyntaxException e) {
// this can never happen. (famous last words :)
}
}
}
private void findMatchingReference(ServiceReference original) {
boolean clear = true;
ServiceReference ref;
if(isCustomFilter) {
try {
ServiceReference[] refs = ctx.getServiceReferences(className, filterString);
if(refs == null || refs.length == 0) {
ref = null;
} else {
ref = refs[0];
}
} catch (InvalidSyntaxException e) {
//This can't happen, we'd have blown up in the constructor
ref = null;
}
} else {
ref = ctx.getServiceReference(className);
}
if (ref != null) {
T service = (T) ctx.getService(ref);
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, ref, service)) {
ctx.ungetService(ref);
}
}
} else if (original == null){
clear = false;
}
if (clear) {
update(original, null, null);
}
}
private boolean update(ServiceReference deadRef, ServiceReference newRef, T service)
{
boolean result = false;
int foundLostReplaced = -1;
// 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) {
this.service.set(service);
if (deadRef == null && newRef != null) foundLostReplaced = 0;
if (deadRef != null && newRef == null) foundLostReplaced = 1;
if (deadRef != null && newRef != null) foundLostReplaced = 2;
}
}
}
if (serviceListener != null) {
if (foundLostReplaced == 0) serviceListener.serviceFound();
else if (foundLostReplaced == 1) serviceListener.serviceLost();
else if (foundLostReplaced == 2) serviceListener.serviceReplaced();
}
return result;
}
public void close()
{
if (open.compareAndSet(true, false)) {
ctx.removeServiceListener(listener);
synchronized (this) {
ServiceReference deadRef = ref.getAndSet(null);
service.set(null);
if (deadRef != null) ctx.ungetService(deadRef);
}
}
}
} | 7,891 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util/tracker | Create_ds/aries/util/src/main/java/org/apache/aries/util/tracker/hook/BundleHookBundleTracker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.util.tracker.hook;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.framework.hooks.bundle.EventHook;
import org.osgi.util.tracker.BundleTracker;
import org.osgi.util.tracker.BundleTrackerCustomizer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* The Tracked and AbstractTracked inner classes are copied from felix framework 4.0.1.
*
* @version $Rev$ $Date$
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class BundleHookBundleTracker<T> extends BundleTracker {
static {
Class c = EventHook.class;
}
/* set this to true to compile in debug messages */
static final boolean DEBUG = false;
/**
* The Bundle Context used by this {@code BundleTracker}.
*/
protected final BundleContext context;
/**
* The {@code BundleTrackerCustomizer} object for this tracker.
*/
final BundleTrackerCustomizer customizer;
/**
* Tracked bundles: {@code Bundle} object -> customized Object and
* {@code BundleListener} object
*/
private volatile Tracked tracked;
/**
* Accessor method for the current Tracked object. This method is only
* intended to be used by the unsynchronized methods which do not modify the
* tracked field.
*
* @return The current Tracked object.
*/
private Tracked tracked() {
return tracked;
}
/**
* State mask for bundles being tracked. This field contains the ORed values
* of the bundle states being tracked.
*/
private final int mask;
/**
* BundleHook service registration
*/
private ServiceRegistration sr;
/**
* Create a {@code BundleTracker} for bundles whose state is present in the
* specified state mask.
*
* <p>
* Bundles whose state is present on the specified state mask will be
* tracked by this {@code BundleTracker}.
*
* @param context The {@code BundleContext} against which the tracking is
* done.
* @param stateMask The bit mask of the {@code OR}ing of the bundle states
* to be tracked.
* @param customizer The customizer object to call when bundles are added,
* modified, or removed in this {@code BundleTracker}. If customizer
* is {@code null}, then this {@code BundleTracker} will be used as
* the {@code BundleTrackerCustomizer} and this {@code BundleTracker}
* will call the {@code BundleTrackerCustomizer} methods on itself.
* @see Bundle#getState()
*/
public BundleHookBundleTracker(BundleContext context, int stateMask, BundleTrackerCustomizer customizer) {
super(context, stateMask, customizer);
this.context = context;
this.mask = stateMask;
this.customizer = customizer == null ? this : customizer;
}
/**
* Open this {@code BundleTracker} and begin tracking bundles.
*
* <p>
* Bundle which match the state criteria specified when this
* {@code BundleTracker} was created are now tracked by this
* {@code BundleTracker}.
*
* @throws java.lang.IllegalStateException If the {@code BundleContext} with
* which this {@code BundleTracker} was created is no longer valid.
* @throws java.lang.SecurityException If the caller and this class do not
* have the appropriate
* {@code AdminPermission[context bundle,LISTENER]}, and the Java
* Runtime Environment supports permissions.
*/
@Override
public void open() {
final Tracked t;
synchronized (this) {
if (tracked != null) {
return;
}
t = new Tracked();
synchronized (t) {
EventHook hook = new BundleEventHook(t);
sr = context.registerService(EventHook.class.getName(), hook, null);
Bundle[] bundles = context.getBundles();
if (bundles != null) {
int length = bundles.length;
for (int i = 0; i < length; i++) {
int state = bundles[i].getState();
if ((state & mask) == 0) {
/* null out bundles whose states are not interesting */
bundles[i] = null;
}
}
/* set tracked with the initial bundles */
t.setInitial(bundles);
}
}
tracked = t;
}
/* Call tracked outside of synchronized region */
tracked.trackInitial(); /* process the initial references */
}
/**
* Close this {@code BundleTracker}.
*
* <p>
* This method should be called when this {@code BundleTracker} should end
* the tracking of bundles.
*
* <p>
* This implementation calls {@link #getBundles()} to get the list of
* tracked bundles to remove.
*/
@Override
public void close() {
final Bundle[] bundles;
final Tracked outgoing;
synchronized (this) {
outgoing = tracked;
if (outgoing == null) {
return;
}
if (DEBUG) {
System.out.println("BundleTracker.close"); //$NON-NLS-1$
}
tracked.close();
bundles = getBundles();
tracked = null;
try {
sr.unregister();
} catch (IllegalStateException e) {
/* In case the context was stopped. */
}
}
if (bundles != null) {
for (int i = 0; i < bundles.length; i++) {
outgoing.untrack(bundles[i], null);
}
}
}
/**
* Default implementation of the
* {@code BundleTrackerCustomizer.addingBundle} method.
*
* <p>
* This method is only called when this {@code BundleTracker} has been
* constructed with a {@code null BundleTrackerCustomizer} argument.
*
* <p>
* This implementation simply returns the specified {@code Bundle}.
*
* <p>
* This method can be overridden in a subclass to customize the object to be
* tracked for the bundle being added.
*
* @param bundle The {@code Bundle} being added to this
* {@code BundleTracker} object.
* @param event The bundle event which caused this customizer method to be
* called or {@code null} if there is no bundle event associated with
* the call to this method.
* @return The specified bundle.
* @see BundleTrackerCustomizer#addingBundle(Bundle, BundleEvent)
*/
@Override
public Object addingBundle(Bundle bundle, BundleEvent event) {
T result = (T) bundle;
return result;
}
/**
* Default implementation of the
* {@code BundleTrackerCustomizer.modifiedBundle} method.
*
* <p>
* This method is only called when this {@code BundleTracker} has been
* constructed with a {@code null BundleTrackerCustomizer} argument.
*
* <p>
* This implementation does nothing.
*
* @param bundle The {@code Bundle} whose state has been modified.
* @param event The bundle event which caused this customizer method to be
* called or {@code null} if there is no bundle event associated with
* the call to this method.
* @param object The customized object for the specified Bundle.
* @see BundleTrackerCustomizer#modifiedBundle(Bundle, BundleEvent, Object)
*/
@Override
public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
/* do nothing */
}
/**
* Default implementation of the
* {@code BundleTrackerCustomizer.removedBundle} method.
*
* <p>
* This method is only called when this {@code BundleTracker} has been
* constructed with a {@code null BundleTrackerCustomizer} argument.
*
* <p>
* This implementation does nothing.
*
* @param bundle The {@code Bundle} being removed.
* @param event The bundle event which caused this customizer method to be
* called or {@code null} if there is no bundle event associated with
* the call to this method.
* @param object The customized object for the specified bundle.
* @see BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)
*/
@Override
public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
/* do nothing */
}
/**
* Return an array of {@code Bundle}s for all bundles being tracked by this
* {@code BundleTracker}.
*
* @return An array of {@code Bundle}s or {@code null} if no bundles are
* being tracked.
*/
public Bundle[] getBundles() {
final Tracked t = tracked();
if (t == null) { /* if BundleTracker is not open */
return null;
}
synchronized (t) {
int length = t.size();
if (length == 0) {
return null;
}
return t.copyKeys(new Bundle[length]);
}
}
/**
* Returns the customized object for the specified {@code Bundle} if the
* specified bundle is being tracked by this {@code BundleTracker}.
*
* @param bundle The {@code Bundle} being tracked.
* @return The customized object for the specified {@code Bundle} or
* {@code null} if the specified {@code Bundle} is not being
* tracked.
*/
public T getObject(Bundle bundle) {
final Tracked t = tracked();
if (t == null) { /* if BundleTracker is not open */
return null;
}
synchronized (t) {
return t.getCustomizedObject(bundle);
}
}
/**
* Remove a bundle from this {@code BundleTracker}.
*
* The specified bundle will be removed from this {@code BundleTracker} . If
* the specified bundle was being tracked then the
* {@code BundleTrackerCustomizer.removedBundle} method will be called for
* that bundle.
*
* @param bundle The {@code Bundle} to be removed.
*/
public void remove(Bundle bundle) {
final Tracked t = tracked();
if (t == null) { /* if BundleTracker is not open */
return;
}
t.untrack(bundle, null);
}
/**
* Return the number of bundles being tracked by this {@code BundleTracker}.
*
* @return The number of bundles being tracked.
*/
public int size() {
final Tracked t = tracked();
if (t == null) { /* if BundleTracker is not open */
return 0;
}
synchronized (t) {
return t.size();
}
}
/**
* Returns the tracking count for this {@code BundleTracker}.
*
* The tracking count is initialized to 0 when this {@code BundleTracker} is
* opened. Every time a bundle is added, modified or removed from this
* {@code BundleTracker} the tracking count is incremented.
*
* <p>
* The tracking count can be used to determine if this {@code BundleTracker}
* has added, modified or removed a bundle by comparing a tracking count
* value previously collected with the current tracking count value. If the
* value has not changed, then no bundle has been added, modified or removed
* from this {@code BundleTracker} since the previous tracking count was
* collected.
*
* @return The tracking count for this {@code BundleTracker} or -1 if this
* {@code BundleTracker} is not open.
*/
public int getTrackingCount() {
final Tracked t = tracked();
if (t == null) { /* if BundleTracker is not open */
return -1;
}
synchronized (t) {
return t.getTrackingCount();
}
}
/**
* Return a {@code Map} with the {@code Bundle}s and customized objects for
* all bundles being tracked by this {@code BundleTracker}.
*
* @return A {@code Map} with the {@code Bundle}s and customized objects for
* all services being tracked by this {@code BundleTracker}. If no
* bundles are being tracked, then the returned map is empty.
* @since 1.5
*/
public Map<Bundle, T> getTracked() {
Map<Bundle, T> map = new HashMap<Bundle, T>();
final Tracked t = tracked();
if (t == null) { /* if BundleTracker is not open */
return map;
}
synchronized (t) {
return t.copyEntries(map);
}
}
/**
* Return if this {@code BundleTracker} is empty.
*
* @return {@code true} if this {@code BundleTracker} is not tracking any
* bundles.
* @since 1.5
*/
public boolean isEmpty() {
final Tracked t = tracked();
if (t == null) { /* if BundleTracker is not open */
return true;
}
synchronized (t) {
return t.isEmpty();
}
}
private class BundleEventHook implements EventHook {
private final Tracked tracked;
private BundleEventHook(Tracked tracked) {
this.tracked = tracked;
}
public void event(BundleEvent bundleEvent, Collection bundleContexts) {
tracked.bundleChanged(bundleEvent);
}
}
/**
* Inner class which subclasses AbstractTracked. This class is the
* {@code SynchronousBundleListener} object for the tracker.
*
* @ThreadSafe
* @since 1.4
*/
private final class Tracked extends AbstractTracked<Bundle, T, BundleEvent> implements SynchronousBundleListener {
/**
* Tracked constructor.
*/
Tracked() {
super();
}
/**
* {@code BundleListener} method for the {@code BundleTracker}
* class. This method must NOT be synchronized to avoid deadlock
* potential.
*
* @param event {@code BundleEvent} object from the framework.
*/
public void bundleChanged(final BundleEvent event) {
/*
* Check if we had a delayed call (which could happen when we
* close).
*/
if (closed) {
return;
}
final Bundle bundle = event.getBundle();
final int state = bundle.getState();
if (DEBUG) {
System.out.println("BundleTracker.Tracked.bundleChanged[" + state + "]: " + bundle); //$NON-NLS-1$ //$NON-NLS-2$
}
if ((state & mask) != 0) {
track(bundle, event);
/*
* If the customizer throws an unchecked exception, it is safe
* to let it propagate
*/
} else {
untrack(bundle, event);
/*
* If the customizer throws an unchecked exception, it is safe
* to let it propagate
*/
}
}
/**
* Call the specific customizer adding method. This method must not be
* called while synchronized on this object.
*
* @param item Item to be tracked.
* @param related Action related object.
* @return Customized object for the tracked item or {@code null}
* if the item is not to be tracked.
*/
T customizerAdding(final Bundle item, final BundleEvent related) {
return (T) customizer.addingBundle(item, related);
}
/**
* Call the specific customizer modified method. This method must not be
* called while synchronized on this object.
*
* @param item Tracked item.
* @param related Action related object.
* @param object Customized object for the tracked item.
*/
void customizerModified(final Bundle item, final BundleEvent related,
final T object) {
customizer.modifiedBundle(item, related, object);
}
/**
* Call the specific customizer removed method. This method must not be
* called while synchronized on this object.
*
* @param item Tracked item.
* @param related Action related object.
* @param object Customized object for the tracked item.
*/
void customizerRemoved(final Bundle item, final BundleEvent related,
final T object) {
customizer.removedBundle(item, related, object);
}
}
/**
* Abstract class to track items. If a Tracker is reused (closed then reopened),
* then a new AbstractTracked object is used. This class acts a map of tracked
* item -> customized object. Subclasses of this class will act as the listener
* object for the tracker. This class is used to synchronize access to the
* tracked items. This is not a public class. It is only for use by the
* implementation of the Tracker class.
*
* @param <S> The tracked item. It is the key.
* @param <T> The value mapped to the tracked item.
* @param <R> The reason the tracked item is being tracked or untracked.
* @version $Id: 79452e6c28683021f2bcf11d3689ec75c6b5642f $
* @ThreadSafe
* @since 1.4
*/
private static abstract class AbstractTracked<S, T, R> {
/* set this to true to compile in debug messages */
static final boolean DEBUG = false;
/**
* Map of tracked items to customized objects.
*
* @GuardedBy this
*/
private final Map<S, T> tracked;
/**
* Modification count. This field is initialized to zero and incremented by
* modified.
*
* @GuardedBy this
*/
private int trackingCount;
/**
* List of items in the process of being added. This is used to deal with
* nesting of events. Since events may be synchronously delivered, events
* can be nested. For example, when processing the adding of a service and
* the customizer causes the service to be unregistered, notification to the
* nested call to untrack that the service was unregistered can be made to
* the track method.
* <p/>
* Since the ArrayList implementation is not synchronized, all access to
* this list must be protected by the same synchronized object for
* thread-safety.
*
* @GuardedBy this
*/
private final List<S> adding;
/**
* true if the tracked object is closed.
* <p/>
* This field is volatile because it is set by one thread and read by
* another.
*/
volatile boolean closed;
/**
* Initial list of items for the tracker. This is used to correctly process
* the initial items which could be modified before they are tracked. This
* is necessary since the initial set of tracked items are not "announced"
* by events and therefore the event which makes the item untracked could be
* delivered before we track the item.
* <p/>
* An item must not be in both the initial and adding lists at the same
* time. An item must be moved from the initial list to the adding list
* "atomically" before we begin tracking it.
* <p/>
* Since the LinkedList implementation is not synchronized, all access to
* this list must be protected by the same synchronized object for
* thread-safety.
*
* @GuardedBy this
*/
private final LinkedList<S> initial;
/**
* AbstractTracked constructor.
*/
AbstractTracked() {
tracked = new HashMap<S, T>();
trackingCount = 0;
adding = new ArrayList<S>(6);
initial = new LinkedList<S>();
closed = false;
}
/**
* Set initial list of items into tracker before events begin to be
* received.
* <p/>
* This method must be called from Tracker's open method while synchronized
* on this object in the same synchronized block as the add listener call.
*
* @param list The initial list of items to be tracked. {@code null}
* entries in the list are ignored.
* @GuardedBy this
*/
void setInitial(S[] list) {
if (list == null) {
return;
}
for (S item : list) {
if (item == null) {
continue;
}
if (DEBUG) {
System.out.println("AbstractTracked.setInitial: " + item); //$NON-NLS-1$
}
initial.add(item);
}
}
/**
* Track the initial list of items. This is called after events can begin to
* be received.
* <p/>
* This method must be called from Tracker's open method while not
* synchronized on this object after the add listener call.
*/
void trackInitial() {
while (true) {
S item;
synchronized (this) {
if (closed || (initial.size() == 0)) {
/*
* if there are no more initial items
*/
return; /* we are done */
}
/*
* move the first item from the initial list to the adding list
* within this synchronized block.
*/
item = initial.removeFirst();
if (tracked.get(item) != null) {
/* if we are already tracking this item */
if (DEBUG) {
System.out.println("AbstractTracked.trackInitial[already tracked]: " + item); //$NON-NLS-1$
}
continue; /* skip this item */
}
if (adding.contains(item)) {
/*
* if this item is already in the process of being added.
*/
if (DEBUG) {
System.out.println("AbstractTracked.trackInitial[already adding]: " + item); //$NON-NLS-1$
}
continue; /* skip this item */
}
adding.add(item);
}
if (DEBUG) {
System.out.println("AbstractTracked.trackInitial: " + item); //$NON-NLS-1$
}
trackAdding(item, null); /*
* Begin tracking it. We call trackAdding
* since we have already put the item in the
* adding list.
*/
}
}
/**
* Called by the owning Tracker object when it is closed.
*/
void close() {
closed = true;
}
/**
* Begin to track an item.
*
* @param item Item to be tracked.
* @param related Action related object.
*/
void track(final S item, final R related) {
final T object;
synchronized (this) {
if (closed) {
return;
}
object = tracked.get(item);
if (object == null) { /* we are not tracking the item */
if (adding.contains(item)) {
/* if this item is already in the process of being added. */
if (DEBUG) {
System.out
.println("AbstractTracked.track[already adding]: " + item); //$NON-NLS-1$
}
return;
}
adding.add(item); /* mark this item is being added */
} else { /* we are currently tracking this item */
if (DEBUG) {
System.out
.println("AbstractTracked.track[modified]: " + item); //$NON-NLS-1$
}
modified(); /* increment modification count */
}
}
if (object == null) { /* we are not tracking the item */
trackAdding(item, related);
} else {
/* Call customizer outside of synchronized region */
customizerModified(item, related, object);
/*
* If the customizer throws an unchecked exception, it is safe to
* let it propagate
*/
}
}
/**
* Common logic to add an item to the tracker used by track and
* trackInitial. The specified item must have been placed in the adding list
* before calling this method.
*
* @param item Item to be tracked.
* @param related Action related object.
*/
private void trackAdding(final S item, final R related) {
if (DEBUG) {
System.out.println("AbstractTracked.trackAdding: " + item); //$NON-NLS-1$
}
T object = null;
boolean becameUntracked = false;
/* Call customizer outside of synchronized region */
try {
object = customizerAdding(item, related);
/*
* If the customizer throws an unchecked exception, it will
* propagate after the finally
*/
} finally {
synchronized (this) {
if (adding.remove(item) && !closed) {
/*
* if the item was not untracked during the customizer
* callback
*/
if (object != null) {
tracked.put(item, object);
modified(); /* increment modification count */
notifyAll(); /* notify any waiters */
}
} else {
becameUntracked = true;
}
}
}
/*
* The item became untracked during the customizer callback.
*/
if (becameUntracked && (object != null)) {
if (DEBUG) {
System.out.println("AbstractTracked.trackAdding[removed]: " + item); //$NON-NLS-1$
}
/* Call customizer outside of synchronized region */
customizerRemoved(item, related, object);
/*
* If the customizer throws an unchecked exception, it is safe to
* let it propagate
*/
}
}
/**
* Discontinue tracking the item.
*
* @param item Item to be untracked.
* @param related Action related object.
*/
void untrack(final S item, final R related) {
final T object;
synchronized (this) {
if (initial.remove(item)) { /*
* if this item is already in the list
* of initial references to process
*/
if (DEBUG) {
System.out.println("AbstractTracked.untrack[removed from initial]: " + item); //$NON-NLS-1$
}
return; /*
* we have removed it from the list and it will not be
* processed
*/
}
if (adding.remove(item)) { /*
* if the item is in the process of
* being added
*/
if (DEBUG) {
System.out.println("AbstractTracked.untrack[being added]: " + item); //$NON-NLS-1$
}
return; /*
* in case the item is untracked while in the process of
* adding
*/
}
object = tracked.remove(item); /*
* must remove from tracker before
* calling customizer callback
*/
if (object == null) { /* are we actually tracking the item */
return;
}
modified(); /* increment modification count */
}
if (DEBUG) {
System.out.println("AbstractTracked.untrack[removed]: " + item); //$NON-NLS-1$
}
/* Call customizer outside of synchronized region */
customizerRemoved(item, related, object);
/*
* If the customizer throws an unchecked exception, it is safe to let it
* propagate
*/
}
/**
* Returns the number of tracked items.
*
* @return The number of tracked items.
* @GuardedBy this
*/
int size() {
return tracked.size();
}
/**
* Returns if the tracker is empty.
*
* @return Whether the tracker is empty.
* @GuardedBy this
* @since 1.5
*/
boolean isEmpty() {
return tracked.isEmpty();
}
/**
* Return the customized object for the specified item
*
* @param item The item to lookup in the map
* @return The customized object for the specified item.
* @GuardedBy this
*/
T getCustomizedObject(final S item) {
return tracked.get(item);
}
/**
* Copy the tracked items into an array.
*
* @param list An array to contain the tracked items.
* @return The specified list if it is large enough to hold the tracked
* items or a new array large enough to hold the tracked items.
* @GuardedBy this
*/
S[] copyKeys(final S[] list) {
return tracked.keySet().toArray(list);
}
/**
* Increment the modification count. If this method is overridden, the
* overriding method MUST call this method to increment the tracking count.
*
* @GuardedBy this
*/
void modified() {
trackingCount++;
}
/**
* Returns the tracking count for this {@code ServiceTracker} object.
* <p/>
* The tracking count is initialized to 0 when this object is opened. Every
* time an item is added, modified or removed from this object the tracking
* count is incremented.
*
* @return The tracking count for this object.
* @GuardedBy this
*/
int getTrackingCount() {
return trackingCount;
}
/**
* Copy the tracked items and associated values into the specified map.
*
* @param <M> Type of {@code Map} to hold the tracked items and
* associated values.
* @param map The map into which to copy the tracked items and associated
* values. This map must not be a user provided map so that user code
* is not executed while synchronized on this.
* @return The specified map.
* @GuardedBy this
* @since 1.5
*/
<M extends Map<? super S, ? super T>> M copyEntries(final M map) {
map.putAll(tracked);
return map;
}
/**
* Call the specific customizer adding method. This method must not be
* called while synchronized on this object.
*
* @param item Item to be tracked.
* @param related Action related object.
* @return Customized object for the tracked item or {@code null} if
* the item is not to be tracked.
*/
abstract T customizerAdding(final S item, final R related);
/**
* Call the specific customizer modified method. This method must not be
* called while synchronized on this object.
*
* @param item Tracked item.
* @param related Action related object.
* @param object Customized object for the tracked item.
*/
abstract void customizerModified(final S item, final R related,
final T object);
/**
* Call the specific customizer removed method. This method must not be
* called while synchronized on this object.
*
* @param item Tracked item.
* @param related Action related object.
* @param object Customized object for the tracked item.
*/
abstract void customizerRemoved(final S item, final R related,
final T object);
}
}
| 7,892 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/FileSystem.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem;
import java.io.File;
import java.io.InputStream;
import org.apache.aries.util.filesystem.impl.FileSystemImpl;
/**
* An abstraction of a file system. A file system can be a zip, or a directory.
*/
public class FileSystem {
/**
* This method gets the IDirectory that represents the root of a virtual file
* system. The provided file can either identify a directory, or a zip file.
*
* @param fs the zip file.
* @return the root of the virtual FS.
*/
public static IDirectory getFSRoot(File fs)
{
return FileSystemImpl.getFSRoot(fs, null);
}
/**
* This method gets an ICloseableDirectory that represents the root of a virtual file
* system. The provided InputStream should represent a zip file.
*
* When this {@link ICloseableDirectory} is closed then backing resources will be
* cleaned up.
*
* @param is An input stream to a zip file.
* @return the root of the virtual FS.
*/
public static ICloseableDirectory getFSRoot(InputStream is)
{
return FileSystemImpl.getFSRoot(is);
}
}
| 7,893 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/FileUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.util.filesystem;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.util.manifest.BundleManifest;
public class FileUtils {
/**
* Check whether a file is a bundle.
* @param file the file path
* @return true if the file is a bundle, false else
*/
public static boolean isBundle(File file) {
BundleManifest bm = BundleManifest.fromBundle(file);
return ((bm != null) && (bm.isValid()));
}
/**
* Get a list of URLs for the bundles under the parent URL
* @param sourceDir The parent URL
* @return the list of URLs for the bundles
* @throws IOException
*/
public static List<URI> getBundlesRecursive(URI sourceDir) throws IOException {
List<URI> filesFound = new ArrayList<URI>();
if (sourceDir == null) {
return filesFound;
} if (sourceDir != null) {
File sourceFile = new File(sourceDir);
if (sourceFile.isFile()) {
if (isBundle(sourceFile)) {
filesFound.add(sourceDir);
}
} else if (sourceFile.isDirectory()) {
File[] subFiles = sourceFile.listFiles();
if ((subFiles !=null) && (subFiles.length >0)) {
for (File file : subFiles) {
filesFound.addAll(getBundlesRecursive(file.toURI()));
}
}
}
}
return filesFound;
}
}
| 7,894 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/IDirectoryFinder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem;
import java.net.URI;
/**
* Provides a means by which a virtual directory can be cached and returned on
* demand.
* <p>
*
* A typical scenario for this interface is to implement it as a service which
* is used to hold virtual directories containing application installation
* artifacts, with this directory being retrieved when required during
* application installation (a URI identifying the virtual directory having been
* passed to the installation code).
* <p>
*
* Implementing classes should use URIs of the form
* <code>idirfinder://?finderID=xxx&directoryID=yyy</code> where the finder ID
* within the query part of the URI may be used to assist in determining the
* directory finder instance that can retrieve the virtual directory identified
* by the directory ID part (or alternatively, the URI as a whole). When
* implemented as a service, a directory finder should configure a corresponding
* service property of "finderID=xxx".
* <p>
*/
public interface IDirectoryFinder
{
/**
* The scheme for directory finder URI ids. Using this scheme enables code
* receiving such a URI to infer that it is intended for use with a
* IDirectoryFinder instance.
* <p>
*/
final static String IDIR_SCHEME = "idirfinder";
/**
* The key used in the query part of the URI whose corresponding value
* assists in identifying the directory finder to be used.
* <p>
*/
final static String IDIR_FINDERID_KEY = "finderID";
/**
* The key used in the query part of the URI whose corresponding value
* identifies the directory to be returned.
* <p>
*/
final static String IDIR_DIRECTORYID_KEY = "directoryID";
/**
* Get the directory that corresponds to the given identifier, and remove it
* from the cache, or return null if no corresponding directory is found.
* <p>
*
* As the found directory is removed, it is not subsequently retrievable by
* re-issuing the request.
* <p>
*
* @param id a URI that identifies the desired directory.
* @return IDirectory instance that corresponds to the given id URI, or null
* if unknown.
*/
IDirectory retrieveIDirectory(URI id);
}
| 7,895 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/IFile.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
/**
* A virtual file on the virtual file system. This may represent a file or a
* directory.
*/
public interface IFile
{
/**
* @return the name of the file relative to the root of the virtual FS. This will return a '/' separated path
* indepedent of underlying filesystem
*/
public String getName();
/**
* @return true iff this IFile is also an IDirectory
*/
public boolean isDirectory();
/**
* @return true iff this IFile is not an IDirectory
*/
public boolean isFile();
/**
* @return the last modified date of the file.
*/
public long getLastModified();
/**
* @return the size of the file.
*/
public long getSize();
/**
* @return if this is a directory return this as an IDirectory, otherwise return null.
*/
public IDirectory convert();
/**
* @return if this is a directory or an archive, returns the opened IDirectory
*/
public IDirectory convertNested();
/**
* @return returns the parent directory of this IFile, or null if this is the root.
*/
public IDirectory getParent();
/**
* The input stream returned by this method should always be closed after use.
*
* @return An InputStream to read the file from.
*
* @throws IOException
* @throws UnsupportedOperationException If the IFile is also an IDirectory.
*/
public InputStream open() throws IOException, UnsupportedOperationException;
/**
* @return the root of this file system.
*/
public IDirectory getRoot();
/**
* @return a URL that can be used to get at this file at a later date.
* @throws MalformedURLException
*/
public URL toURL() throws MalformedURLException ;
}
| 7,896 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/IDirectory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem;
import java.util.List;
/**
* A virtual directory in a file system. Widely used to present a common view of regular
* file systems, jar and zip files.
*/
public interface IDirectory extends Iterable<IFile>, IFile
{
/**
* @return the list of files in this directory. Files must be in this directory
* and not in sub-directories.
*/
public List<IFile> listFiles();
/**
*
* @return the list of files in all directories (including sub-directories). This is the complete list.
*/
public List<IFile> listAllFiles();
/**
* Gets the requested file under this directory. The file may be located any
* number of levels within this directory. The name is relative to this
* directory. If the file cannot be found it will return null.
*
* @param name the name of the file.
* @return the IFile, or null if no such file exists.
*/
public IFile getFile(String name);
/**
* @return true if this IDirectory is the root of the virtual file system.
*/
public boolean isRoot();
/**
* Open a more effective implementation with user regulated resource management. The implementation will be
* more efficient for batch operations. Make sure to call close when finished with the returned IDirectory.
*
* IFiles and IDirectories other than the returned closeable directory
* will stay valid after calling the close method but will no longer perform as efficiently. InputStreams that are
* open at the time of calling close may be invalidated.
*
* @return {@link ICloseableDirectory} or null if a batch aware version of this {@link IDirectory} is not supported
*/
public ICloseableDirectory toCloseable();
} | 7,897 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util | Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/ICloseableDirectory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem;
import java.io.Closeable;
/**
* Implementation of IDirectory that is more efficient for batch operations as it does not due
* automatic resource management. Instead the user has to explicitly call close to release resources.
* Resources are cached for the current IDirectory archive only. Nested archives should be converted to
* {@link ICloseableDirectory} separately.
*/
public interface ICloseableDirectory extends IDirectory, Closeable {
/**
* Checks whether the closeable directory has been closed
*/
boolean isClosed();
}
| 7,898 |
0 | Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem | Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/NestedCloseableDirectory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.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.util.filesystem.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipFile;
import org.apache.aries.util.filesystem.IFile;
import org.apache.aries.util.io.IOUtils;
public class NestedCloseableDirectory extends CloseableDirectory {
private final File tempFile;
private final ZipFile zip;
public NestedCloseableDirectory(IFile archive, NestedZipDirectory delegate) throws IOException {
super(delegate);
tempFile = File.createTempFile("archiveExtract", ".jar");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tempFile);
IOUtils.copy(archive.open(), fos);
this.delegate = new NestedZipDirectory(delegate, this);
zip = new ZipFile(tempFile);
} catch (IOException e) {
IOUtils.close(fos);
tempFile.delete();
throw e;
}
}
public ZipFile getZipFile() {
return zip;
}
@Override
protected void cleanup() {
try {
zip.close();
} catch (IOException e) {}
tempFile.delete();
}
}
| 7,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.