http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/ActivatorTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/ActivatorTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/ActivatorTest.java new file mode 100644 index 0000000..d9bc98d --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/ActivatorTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw; + +import java.util.Dictionary; +import java.util.Hashtable; + +import junit.framework.TestCase; + +import org.apache.aries.rsa.spi.DistributionProvider; +import org.easymock.EasyMock; +import org.easymock.IMocksControl; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Filter; +import org.osgi.framework.ServiceRegistration; + +public class ActivatorTest extends TestCase { + + private BundleContext getMockBundleContext(IMocksControl control) { + Bundle b = control.createMock(Bundle.class); + Dictionary<String, String> ht = new Hashtable<String, String>(); + EasyMock.expect(b.getHeaders()).andReturn(ht).anyTimes(); + BundleContext bc = control.createMock(BundleContext.class); + + EasyMock.expect(b.getBundleContext()).andReturn(bc).anyTimes(); + EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); + return bc; + } + + @SuppressWarnings({ + "rawtypes", "unchecked" + }) + public void testCreateAndShutdownRemoteServiceAdminService() throws Exception { + IMocksControl control = EasyMock.createNiceControl(); + BundleContext bc = getMockBundleContext(control); + Filter filter = control.createMock(Filter.class); + EasyMock.expect(bc.createFilter(EasyMock.<String>anyObject())).andReturn(filter); + EasyMock.expectLastCall().atLeastOnce(); + ServiceRegistration sr = control.createMock(ServiceRegistration.class); + EasyMock.expect(bc.registerService(EasyMock.eq(DistributionProvider.class.getName()), + EasyMock.anyObject(), (Dictionary<String, String>)EasyMock.anyObject())) + .andReturn(sr).atLeastOnce(); + + control.replay(); + Activator a = new Activator(); + a.start(bc); + control.verify(); + } +}
http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/TestUtils.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/TestUtils.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/TestUtils.java new file mode 100644 index 0000000..b81bf3e --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/TestUtils.java @@ -0,0 +1,37 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw; + +public final class TestUtils { + +// private TestUtils() { +// } +// +// public static ServiceEndpointDescription mockServiceDescription(String... interfaceNames) { +// List<String> iList = new ArrayList<String>(); +// for (String iName : interfaceNames) { +// iList.add(iName); +// } +// +// ServiceEndpointDescription sd = EasyMock.createNiceMock(ServiceEndpointDescription.class); +// sd.getProvidedInterfaces(); +// EasyMock.expectLastCall().andReturn(iList); +// return sd; +// } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/DecorationParserTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/DecorationParserTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/DecorationParserTest.java new file mode 100644 index 0000000..270c7fa --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/DecorationParserTest.java @@ -0,0 +1,63 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.decorator; + +import java.io.IOException; +import java.net.URL; +import java.util.List; + +import javax.xml.bind.JAXBException; + +import org.apache.cxf.xmlns.service_decoration._1_0.AddPropertyType; +import org.apache.cxf.xmlns.service_decoration._1_0.MatchPropertyType; +import org.apache.cxf.xmlns.service_decoration._1_0.MatchType; +import org.apache.cxf.xmlns.service_decoration._1_0.ServiceDecorationType; +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class DecorationParserTest { + + @Test + public void testGetDecoratorForSD() throws JAXBException, IOException { + URL resource = getClass().getResource("/test-resources/sd.xml"); + List<ServiceDecorationType> elements = new DecorationParser().getDecorations(resource); + assertEquals(1, elements.size()); + ServiceDecorationType decoration = elements.get(0); + assertEquals(1, decoration.getMatch().size()); + MatchType match = decoration.getMatch().get(0); + assertEquals("org.acme.foo.*", match.getInterface()); + assertEquals(1, match.getMatchProperty().size()); + MatchPropertyType matchProp = match.getMatchProperty().get(0); + assertEquals("test.prop", matchProp.getName()); + assertEquals("xyz", matchProp.getValue()); + assertEquals(1, match.getAddProperty().size()); + AddPropertyType addProp = match.getAddProperty().get(0); + assertEquals("test.too", addProp.getName()); + assertEquals("ahaha", addProp.getValue()); + assertEquals("java.lang.String", addProp.getType()); + } + + @Test + public void testGetDecorationForNull() throws JAXBException, IOException { + List<ServiceDecorationType> elements = new DecorationParser().getDecorations(null); + Assert.assertEquals(0, elements.size()); + } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/InterfaceRuleTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/InterfaceRuleTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/InterfaceRuleTest.java new file mode 100644 index 0000000..c66642b --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/InterfaceRuleTest.java @@ -0,0 +1,163 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.decorator; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; +import org.easymock.IAnswer; +import org.osgi.framework.Bundle; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; + +@SuppressWarnings("rawtypes") +public class InterfaceRuleTest extends TestCase { + + public void testDUMMY() { + assertTrue(true); + } + + public void testInterfaceRuleGetBundle() { + Bundle b = EasyMock.createMock(Bundle.class); + EasyMock.replay(b); + InterfaceRule ir = new InterfaceRule(b, "org.apache.Foo"); + assertSame(b, ir.getBundle()); + } + + public void testInterfaceRule1() { + InterfaceRule ir = new InterfaceRule(null, "org.apache.Foo"); + ir.addProperty("x", "y", String.class.getName()); + + final Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"a.b.C", "org.apache.Foo"}); + ServiceReference sref = mockServiceReference(serviceProps); + + Map<String, Object> m = new HashMap<String, Object>(); + m.put("a", "b"); + ir.apply(sref, m); + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("a", "b"); + expected.put("x", "y"); + assertEquals(expected, m); + } + + public void testInterfaceRule2() { + InterfaceRule ir = new InterfaceRule(null, "org.apache.F(.*)"); + ir.addPropMatch("boo", "baah"); + ir.addProperty("x", "1", Integer.class.getName()); + ir.addProperty("aaa.bbb", "true", Boolean.class.getName()); + + final Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put("boo", "baah"); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"a.b.C", "org.apache.Foo"}); + ServiceReference sref = mockServiceReference(serviceProps); + + Map<String, Object> m = new HashMap<String, Object>(); + ir.apply(sref, m); + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("x", 1); + expected.put("aaa.bbb", Boolean.TRUE); + assertEquals(expected, m); + } + + public void testInterfaceRule3() { + InterfaceRule ir = new InterfaceRule(null, "org.apache.F(.*)"); + ir.addProperty("x", "y", String.class.getName()); + + final Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put("boo", "baah"); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.apache.Boo"}); + ServiceReference sref = mockServiceReference(serviceProps); + + Map<String, Object> m = new HashMap<String, Object>(); + ir.apply(sref, m); + assertEquals(0, m.size()); + } + + public void testInterfaceRule4() { + InterfaceRule ir = new InterfaceRule(null, "org.apache.F(.*)"); + ir.addPropMatch("boo", "baah"); + ir.addProperty("x", "y", String.class.getName()); + + final Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.apache.Foo"}); + ServiceReference sref = mockServiceReference(serviceProps); + + Map<String, Object> m = new HashMap<String, Object>(); + ir.apply(sref, m); + assertEquals(0, m.size()); + } + + public void testInterfaceRule5() { + InterfaceRule ir = new InterfaceRule(null, "org.apache.Foo"); + ir.addPropMatch("test.int", "42"); + ir.addProperty("x", "1", Long.class.getName()); + + final Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put("test.int", 42); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.apache.Foo"}); + ServiceReference sref = mockServiceReference(serviceProps); + + Map<String, Object> m = new HashMap<String, Object>(); + m.put("x", "foo"); + m.put("aaa.bbb", Boolean.TRUE); + ir.apply(sref, m); + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("x", 1L); + expected.put("aaa.bbb", Boolean.TRUE); + assertEquals(expected, m); + } + + public void testInterfaceRule6() { + InterfaceRule ir = new InterfaceRule(null, "org.apache.Foo"); + ir.addPropMatch("test.int", "42"); + ir.addProperty("x", "1", Long.class.getName()); + + final Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put("test.int", 51); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.apache.Foo"}); + ServiceReference sref = mockServiceReference(serviceProps); + + Map<String, Object> m = new HashMap<String, Object>(); + m.put("x", "foo"); + m.put("aaa.bbb", Boolean.TRUE); + ir.apply(sref, m); + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("x", "foo"); + expected.put("aaa.bbb", Boolean.TRUE); + assertEquals(expected, m); + } + + private ServiceReference mockServiceReference(final Map<String, Object> serviceProps) { + ServiceReference sref = EasyMock.createMock(ServiceReference.class); + EasyMock.expect(sref.getProperty((String) EasyMock.anyObject())).andAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + return serviceProps.get(EasyMock.getCurrentArguments()[0]); + } + }).anyTimes(); + EasyMock.expect(sref.getPropertyKeys()) + .andReturn(serviceProps.keySet().toArray(new String[] {})).anyTimes(); + + EasyMock.replay(sref); + return sref; + } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorBundleListenerTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorBundleListenerTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorBundleListenerTest.java new file mode 100644 index 0000000..1ca33fc --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorBundleListenerTest.java @@ -0,0 +1,69 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.decorator; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.easymock.EasyMock; +import org.junit.Test; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; + +import static org.junit.Assert.assertEquals; + +public class ServiceDecoratorBundleListenerTest { + + @Test + public void testBundleListener() { + BundleContext bc = EasyMock.createMock(BundleContext.class); + EasyMock.replay(bc); + + final List<String> called = new ArrayList<String>(); + ServiceDecoratorImpl serviceDecorator = new ServiceDecoratorImpl() { + @Override + void addDecorations(Bundle bundle) { + called.add("addDecorations"); + } + + @Override + void removeDecorations(Bundle bundle) { + called.add("removeDecorations"); + } + }; + + Bundle b = EasyMock.createMock(Bundle.class); + EasyMock.replay(b); + + ServiceDecoratorBundleListener listener = new ServiceDecoratorBundleListener(serviceDecorator); + + assertEquals("Precondition failed", 0, called.size()); + listener.bundleChanged(new BundleEvent(BundleEvent.INSTALLED, b)); + assertEquals(0, called.size()); + + listener.bundleChanged(new BundleEvent(BundleEvent.STARTED, b)); + assertEquals(Arrays.asList("addDecorations"), called); + + listener.bundleChanged(new BundleEvent(BundleEvent.STOPPING, b)); + assertEquals(Arrays.asList("addDecorations", "removeDecorations"), called); + + } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorImplTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorImplTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorImplTest.java new file mode 100644 index 0000000..400d793 --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorImplTest.java @@ -0,0 +1,187 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.decorator; + +import java.net.URL; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; +import org.easymock.IAnswer; +import org.junit.Assert; +import org.osgi.framework.Bundle; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; + +public class ServiceDecoratorImplTest extends TestCase { + private static final Map<String, Object> EMPTY = new HashMap<String, Object>(); + private static final URL RES_SD = getResource("/test-resources/sd.xml"); + private static final URL RES_SD1 = getResource("/test-resources/sd1.xml"); + private static final URL RES_SD2 = getResource("/test-resources/sd2.xml"); + private static final URL RES_SD0 = getResource("/test-resources/sd0.xml"); + private static final URL RES_SD_1 = getResource("/test-resources/sd-1.xml"); + + @SuppressWarnings("rawtypes") + public void testAddRemoveDecorations() { + final Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.acme.foo.Bar"}); + serviceProps.put("test.prop", "xyz"); + + Bundle b = createBundleContaining(RES_SD); + ServiceDecoratorImpl sd = new ServiceDecoratorImpl(); + assertEquals("Precondition failed", 0, sd.decorations.size()); + sd.addDecorations(b); + assertEquals(1, sd.decorations.size()); + + Map<String, Object> target = new HashMap<String, Object>(); + ServiceReference sref = EasyMock.createMock(ServiceReference.class); + EasyMock.expect(sref.getProperty((String) EasyMock.anyObject())).andAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + return serviceProps.get(EasyMock.getCurrentArguments()[0]); + } + }).anyTimes(); + EasyMock.replay(sref); + sd.decorate(sref, target); + + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("test.too", "ahaha"); + assertEquals(expected, target); + + // remove it again + sd.removeDecorations(b); + assertEquals(0, sd.decorations.size()); + Map<String, Object> target2 = new HashMap<String, Object>(); + sd.decorate(sref, target2); + assertEquals(EMPTY, target2); + } + + public void testAddDecorations() { + final Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.acme.foo.Bar"}); + serviceProps.put("test.prop", "xyz"); + + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("test.too", "ahaha"); + assertDecorate(serviceProps, expected, RES_SD); + } + + public void testAddDecorations1() { + Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.A"}); + + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("A", "B"); + expected.put("C", 2); + assertDecorate(serviceProps, expected, RES_SD1, RES_SD2); + } + + public void testAddDecorations2() { + Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.D"}); + + assertDecorate(serviceProps, EMPTY, RES_SD1, RES_SD2); + } + + public void testAddDecorations3() { + Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.B"}); + serviceProps.put("x", "y"); + + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("bool", Boolean.TRUE); + assertDecorate(serviceProps, expected, RES_SD1, RES_SD2); + } + + public void testAddDecorations4() { + Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.C"}); + serviceProps.put("x", "z"); + + Map<String, Object> expected = new HashMap<String, Object>(); + expected.put("bool", Boolean.FALSE); + assertDecorate(serviceProps, expected, RES_SD1, RES_SD2); + } + + public void testAddDecorations5() { + Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.C"}); + serviceProps.put("x", "x"); + + assertDecorate(serviceProps, EMPTY, RES_SD1, RES_SD2); + } + + public void testAddDecorations6() { + Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.D"}); + + assertDecorate(serviceProps, EMPTY, RES_SD0); + } + + public void testAddDecorations7() { + Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.D"}); + + assertDecorate(serviceProps, EMPTY, RES_SD_1); + } + + private void assertDecorate(final Map<String, Object> serviceProps, + Map<String, Object> expected, URL ... resources) { + Map<String, Object> actual = testDecorate(serviceProps, resources); + assertEquals(expected, actual); + } + + @SuppressWarnings("rawtypes") + private Map<String, Object> testDecorate(final Map<String, Object> serviceProps, URL ... resources) { + Bundle b = createBundleContaining(resources); + + ServiceDecoratorImpl sd = new ServiceDecoratorImpl(); + sd.addDecorations(b); + + Map<String, Object> target = new HashMap<String, Object>(); + ServiceReference sref = EasyMock.createMock(ServiceReference.class); + EasyMock.expect(sref.getProperty((String) EasyMock.anyObject())).andAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + return serviceProps.get(EasyMock.getCurrentArguments()[0]); + } + }).anyTimes(); + EasyMock.replay(sref); + sd.decorate(sref, target); + return target; + } + + private Bundle createBundleContaining(URL... resources) { + Bundle b = EasyMock.createMock(Bundle.class); + EasyMock.expect(b.findEntries("OSGI-INF/remote-service", "*.xml", false)).andReturn( + Collections.enumeration(Arrays.asList(resources))).anyTimes(); + EasyMock.expect(b.getSymbolicName()).andReturn("bundlename"); + EasyMock.replay(b); + return b; + } + + private static URL getResource(String path) { + URL resource = ServiceDecoratorImplTest.class.getResource(path); + Assert.assertNotNull("Resource " + path + " not found!", resource); + return resource; + } + +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/CXFDistributionProviderTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/CXFDistributionProviderTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/CXFDistributionProviderTest.java new file mode 100644 index 0000000..dcf1f2d --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/CXFDistributionProviderTest.java @@ -0,0 +1,104 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.handlers; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.aries.rsa.spi.DistributionProvider; +import org.apache.cxf.dosgi.dsw.Constants; +import org.apache.cxf.dosgi.dsw.qos.DefaultIntentMapFactory; +import org.apache.cxf.dosgi.dsw.qos.IntentManager; +import org.apache.cxf.dosgi.dsw.qos.IntentManagerImpl; +import org.apache.cxf.dosgi.dsw.qos.IntentMap; +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Test; +import org.osgi.framework.BundleContext; +import org.osgi.service.remoteserviceadmin.RemoteConstants; + +import static org.junit.Assert.assertTrue; + +public class CXFDistributionProviderTest { + + @Test + public void testGetDefaultHandlerNoIntents() { + DistributionProvider handler = getHandlerWith(null, null); + assertTrue(handler instanceof PojoConfigurationTypeHandler); + } + + @Test + public void testGetJaxrsHandlerNoIntents() { + DistributionProvider handler = getHandlerWith(Constants.RS_CONFIG_TYPE, null); + assertTrue(handler instanceof JaxRSPojoConfigurationTypeHandler); + } + + @Test + public void testGetJaxrsHandlerHttpIntents() { + DistributionProvider handler = getHandlerWith(Constants.RS_CONFIG_TYPE, "HTTP"); + assertTrue(handler instanceof JaxRSPojoConfigurationTypeHandler); + } + + @Test + public void testJaxrsPropertyIgnored() { + DistributionProvider handler = getHandlerWith(Constants.RS_CONFIG_TYPE, "SOAP HTTP"); + assertTrue(handler instanceof PojoConfigurationTypeHandler); + assertTrue(!(handler instanceof JaxRSPojoConfigurationTypeHandler)); + } + + @Test + public void testJaxrsPropertyIgnored2() { + DistributionProvider handler = getHandlerWith(Constants.RS_CONFIG_TYPE, new String[] {"HTTP", "SOAP"}); + assertTrue(handler instanceof PojoConfigurationTypeHandler); + assertTrue(!(handler instanceof JaxRSPojoConfigurationTypeHandler)); + } + + @Test + public void testGetPojoHandler() { + DistributionProvider handler = getHandlerWith(Constants.WS_CONFIG_TYPE, null); + assertTrue(handler instanceof PojoConfigurationTypeHandler); + } + + @Test + public void testGetWSDLHandler() { + DistributionProvider handler = getHandlerWith(Constants.WSDL_CONFIG_TYPE, null); + assertTrue(handler instanceof WsdlConfigurationTypeHandler); + } + + @Test + public void testUnsupportedConfiguration() { + DistributionProvider handler = getHandlerWith("notSupportedConfig", null); + Assert.assertNull(handler); + } + + private DistributionProvider getHandlerWith(String configType, Object intents) { + BundleContext bc = EasyMock.createNiceMock(BundleContext.class); + EasyMock.replay(bc); + Map<String, Object> serviceProps = new HashMap<String, Object>(); + serviceProps.put(RemoteConstants.SERVICE_EXPORTED_CONFIGS, configType); + serviceProps.put(RemoteConstants.SERVICE_EXPORTED_INTENTS, intents); + IntentMap intentMap = new IntentMap(new DefaultIntentMapFactory().create()); + IntentManager intentManager = new IntentManagerImpl(intentMap); + HttpServiceManager httpServiceManager = new HttpServiceManager(bc, null, null); + CXFDistributionProvider f = new CXFDistributionProvider(bc, intentManager, httpServiceManager); + List<String> configurationTypes = f.determineConfigurationTypes(serviceProps); + return f.getHandler(configurationTypes, serviceProps); + } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/ClassUtilsTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/ClassUtilsTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/ClassUtilsTest.java new file mode 100644 index 0000000..a0774be --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/ClassUtilsTest.java @@ -0,0 +1,134 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.handlers; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.apache.cxf.dosgi.dsw.util.Provider; +import org.easymock.EasyMock; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +public class ClassUtilsTest extends TestCase { + + public void testGetInterfaceClass() { + assertEquals(String.class, + ClassUtils.getInterfaceClass("Hello", "java.lang.String")); + assertNull(ClassUtils.getInterfaceClass("Hello", "java.lang.Integer")); + assertEquals(List.class, ClassUtils.getInterfaceClass( + new ArrayList<String>(), "java.util.List")); + assertEquals(Collection.class, ClassUtils.getInterfaceClass( + new ArrayList<String>(), "java.util.Collection")); + } + + public void testGetInterfaceClassFromSubclass() { + assertEquals(Map.class, ClassUtils.getInterfaceClass( + new MySubclassFour(), "java.util.Map")); + assertNull(ClassUtils.getInterfaceClass(new MySubclassFour(), + "java.util.UnknownType")); + } + + public void testLoadProvidersAsString() throws Exception { + BundleContext bc = mockBundleContext(); + Map<String, Object> sd = Collections.<String, Object>singletonMap("providers", Provider.class.getName()); + List<Object> providers = ClassUtils.loadProviderClasses(bc, sd, "providers"); + assertEquals(1, providers.size()); + assertTrue(providers.get(0) instanceof Provider); + } + + public void testLoadProvidersAsStringArray() throws Exception { + BundleContext bc = mockBundleContext(); + Map<String, Object> sd = Collections.<String, Object>singletonMap("providers", + new String[]{Provider.class.getName()}); + List<Object> providers = ClassUtils.loadProviderClasses(bc, sd, "providers"); + assertEquals(1, providers.size()); + assertTrue(providers.get(0) instanceof Provider); + } + + public void testLoadProvidersAsObject() throws Exception { + Map<String, Object> sd = Collections.<String, Object>singletonMap("providers", new Provider()); + List<Object> providers = ClassUtils.loadProviderClasses(null, sd, "providers"); + assertEquals(1, providers.size()); + assertTrue(providers.get(0) instanceof Provider); + } + + public void testLoadProvidersAsObjectArray() throws Exception { + Map<String, Object> sd = Collections.<String, Object>singletonMap("providers", new Object[]{new Provider()}); + List<Object> providers = ClassUtils.loadProviderClasses(null, sd, "providers"); + assertEquals(1, providers.size()); + assertTrue(providers.get(0) instanceof Provider); + } + + public void testLoadProvidersAsObjectList() throws Exception { + List<Object> list = new LinkedList<Object>(); + list.add(new Provider()); + Map<String, Object> sd = Collections.<String, Object>singletonMap("providers", list); + List<Object> providers = ClassUtils.loadProviderClasses(null, sd, "providers"); + assertEquals(1, providers.size()); + assertTrue(providers.get(0) instanceof Provider); + } + + public void testLoadProvidersAsStringList() throws Exception { + List<Object> list = new LinkedList<Object>(); + list.add(Provider.class.getName()); + Map<String, Object> sd = Collections.<String, Object>singletonMap("providers", list); + List<Object> providers = ClassUtils.loadProviderClasses(mockBundleContext(), sd, "providers"); + assertEquals(1, providers.size()); + assertTrue(providers.get(0) instanceof Provider); + } + + private BundleContext mockBundleContext() throws Exception { + BundleContext bc = EasyMock.createMock(BundleContext.class); + Bundle bundle = EasyMock.createMock(Bundle.class); + bc.getBundle(); + EasyMock.expectLastCall().andReturn(bundle); + bundle.loadClass(Provider.class.getName()); + EasyMock.expectLastCall().andReturn(Provider.class); + EasyMock.replay(bc, bundle); + return bc; + } + + @SuppressWarnings({ "serial", "rawtypes" }) + private static class MyMapSubclass extends HashMap { + } + + @SuppressWarnings("serial") + static class MySubclassOne extends MyMapSubclass { + } + + @SuppressWarnings("serial") + static class MySubclassTwo extends MySubclassOne { + } + + @SuppressWarnings("serial") + static class MySubclassThree extends MySubclassTwo { + } + + @SuppressWarnings("serial") + static class MySubclassFour extends MySubclassThree { + } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/HttpServiceManagerTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/HttpServiceManagerTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/HttpServiceManagerTest.java new file mode 100644 index 0000000..10fba12 --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/HttpServiceManagerTest.java @@ -0,0 +1,125 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.handlers; + +import java.util.Dictionary; + +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import junit.framework.TestCase; + +import org.apache.cxf.Bus; +import org.apache.cxf.BusFactory; +import org.easymock.Capture; +import org.easymock.EasyMock; +import org.easymock.IMocksControl; +import org.junit.Assert; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Filter; +import org.osgi.framework.ServiceEvent; +import org.osgi.framework.ServiceListener; +import org.osgi.framework.ServiceReference; +import org.osgi.service.http.HttpContext; +import org.osgi.service.http.HttpService; +import org.osgi.service.http.NamespaceException; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; + +public class HttpServiceManagerTest extends TestCase { + + public void testGetAbsoluteAddress() { + IMocksControl c = EasyMock.createControl(); + BundleContext bundleContext = c.createMock(BundleContext.class); + c.replay(); + HttpServiceManager manager = new HttpServiceManager(bundleContext, null, null, null); + String localIp = LocalHostUtil.getLocalIp(); + + String address1 = manager.getAbsoluteAddress(null, "/myservice"); + assertEquals("http://" + localIp + ":8181/cxf/myservice", address1); + + String address2 = manager.getAbsoluteAddress("/mycontext", "/myservice"); + assertEquals("http://" + localIp + ":8181/mycontext/myservice", address2); + + c.verify(); + } + + public void testRegisterAndUnregisterServlet() throws Exception { + IMocksControl c = EasyMock.createControl(); + BundleContext dswContext = c.createMock(BundleContext.class); + Filter filter = c.createMock(Filter.class); + expect(dswContext.createFilter(EasyMock.eq("(service.id=12345)"))).andReturn(filter).once(); + Capture<ServiceListener> captured = EasyMock.newCapture(); + dswContext.addServiceListener(EasyMock.capture(captured), EasyMock.<String>anyObject()); + expectLastCall().atLeastOnce(); + expect(dswContext.getProperty("org.apache.cxf.httpservice.requirefilter")).andReturn(null).atLeastOnce(); + ServletConfig config = c.createMock(ServletConfig.class); + expect(config.getInitParameter(EasyMock.<String>anyObject())).andReturn(null).atLeastOnce(); + ServletContext servletContext = c.createMock(ServletContext.class); + expect(config.getServletContext()).andReturn(servletContext); + final HttpService httpService = new DummyHttpService(config); + ServiceReference<?> sr = c.createMock(ServiceReference.class); + expect(sr.getProperty(EasyMock.eq("service.id"))).andReturn(12345L).atLeastOnce(); + expect(servletContext.getResourceAsStream((String)EasyMock.anyObject())).andReturn(null).anyTimes(); + c.replay(); + + HttpServiceManager h = new HttpServiceManager(dswContext, null, null, null) { + @Override + protected HttpService getHttpService() { + return httpService; + } + }; + Bus bus = BusFactory.newInstance().createBus(); + h.registerServlet(bus, "/myService", dswContext, 12345L); + + ServiceEvent event = new ServiceEvent(ServiceEvent.UNREGISTERING, sr); + captured.getValue().serviceChanged(event); + c.verify(); + } + + static class DummyHttpService implements HttpService { + + private ServletConfig config; + + DummyHttpService(ServletConfig config) { + this.config = config; + } + + @SuppressWarnings("rawtypes") + public void registerServlet(String alias, Servlet servlet, Dictionary initparams, HttpContext context) + throws ServletException, NamespaceException { + Assert.assertEquals("/myService", alias); + servlet.init(config); + } + + public void registerResources(String alias, String name, HttpContext context) throws NamespaceException { + throw new RuntimeException("This method should not be called"); + } + + public void unregister(String alias) { + } + + public HttpContext createDefaultHttpContext() { + return EasyMock.createNiceMock(HttpContext.class); + } + } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/JaxRSUtilsTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/JaxRSUtilsTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/JaxRSUtilsTest.java new file mode 100644 index 0000000..6c8e35a --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/JaxRSUtilsTest.java @@ -0,0 +1,195 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.handlers; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.apache.cxf.dosgi.dsw.Constants; +import org.apache.cxf.jaxrs.provider.JAXBElementProvider; +import org.apache.cxf.jaxrs.provider.aegis.AegisElementProvider; +import org.easymock.EasyMock; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.service.remoteserviceadmin.RemoteConstants; + +public class JaxRSUtilsTest extends TestCase { + + private void addRequiredProps(Map<String, Object> props) { + props.put(RemoteConstants.ENDPOINT_ID, "http://google.de"); + props.put(RemoteConstants.SERVICE_IMPORTED_CONFIGS, "myGreatConfiguration"); + props.put(org.osgi.framework.Constants.OBJECTCLASS, new String[] {"my.class"}); + } + + public void testNoGlobalProviders() { + Map<String, Object> props = new HashMap<String, Object>(); + addRequiredProps(props); + props.put(Constants.RS_PROVIDER_GLOBAL_PROP_KEY, "false"); + + assertEquals(0, JaxRSUtils.getProviders(null, props).size()); + } + + public void testAegisProvider() { + Map<String, Object> props = new HashMap<String, Object>(); + props.put(Constants.RS_DATABINDING_PROP_KEY, "aegis"); + props.put(Constants.RS_PROVIDER_GLOBAL_PROP_KEY, "false"); + + addRequiredProps(props); + + List<Object> providers = JaxRSUtils.getProviders(null, props); + assertEquals(1, providers.size()); + assertEquals(AegisElementProvider.class.getName(), providers.get(0).getClass().getName()); + } + + @SuppressWarnings("rawtypes") + public void testServiceProviders() { + Map<String, Object> props = new HashMap<String, Object>(); + props.put(Constants.RS_PROVIDER_PROP_KEY, new Object[] { + new AegisElementProvider() + }); + props.put(Constants.RS_PROVIDER_GLOBAL_PROP_KEY, "false"); + addRequiredProps(props); + + List<Object> providers = JaxRSUtils.getProviders(null, props); + assertEquals(1, providers.size()); + assertEquals(AegisElementProvider.class.getName(), providers.get(0).getClass().getName()); + } + + public void testServiceProviderProperty() throws Exception { + BundleContext bc = EasyMock.createMock(BundleContext.class); + Bundle bundle = EasyMock.createMock(Bundle.class); + bc.getBundle(); + EasyMock.expectLastCall().andReturn(bundle).times(2); + bundle.loadClass(AegisElementProvider.class.getName()); + EasyMock.expectLastCall().andReturn(AegisElementProvider.class); + bundle.loadClass(JAXBElementProvider.class.getName()); + EasyMock.expectLastCall().andReturn(JAXBElementProvider.class); + EasyMock.replay(bc, bundle); + + Map<String, Object> props = new HashMap<String, Object>(); + props.put(Constants.RS_PROVIDER_PROP_KEY, + "\r\n " + AegisElementProvider.class.getName() + " , \r\n" + + JAXBElementProvider.class.getName() + "\r\n"); + + props.put(Constants.RS_PROVIDER_GLOBAL_PROP_KEY, "false"); + addRequiredProps(props); + + List<Object> providers = JaxRSUtils.getProviders(bc, props); + assertEquals(2, providers.size()); + assertEquals(AegisElementProvider.class.getName(), providers.get(0).getClass().getName()); + assertEquals(JAXBElementProvider.class.getName(), providers.get(1).getClass().getName()); + } + + public void testServiceProviderStrings() throws Exception { + BundleContext bc = EasyMock.createMock(BundleContext.class); + Bundle bundle = EasyMock.createMock(Bundle.class); + bc.getBundle(); + EasyMock.expectLastCall().andReturn(bundle).times(2); + bundle.loadClass(AegisElementProvider.class.getName()); + EasyMock.expectLastCall().andReturn(AegisElementProvider.class); + bundle.loadClass(JAXBElementProvider.class.getName()); + EasyMock.expectLastCall().andReturn(JAXBElementProvider.class); + EasyMock.replay(bc, bundle); + + Map<String, Object> props = new HashMap<String, Object>(); + props.put(Constants.RS_PROVIDER_PROP_KEY, new String[] { + "\r\n " + AegisElementProvider.class.getName(), + JAXBElementProvider.class.getName() + "\r\n" + }); + + props.put(Constants.RS_PROVIDER_GLOBAL_PROP_KEY, "false"); + addRequiredProps(props); + + List<Object> providers = JaxRSUtils.getProviders(bc, props); + assertEquals(2, providers.size()); + assertEquals(AegisElementProvider.class.getName(), providers.get(0).getClass().getName()); + assertEquals(JAXBElementProvider.class.getName(), providers.get(1).getClass().getName()); + } + + @SuppressWarnings({ + "rawtypes", "unchecked" + }) + public void testCustomGlobalProvider() throws Exception { + ServiceReference sref = EasyMock.createNiceMock(ServiceReference.class); + BundleContext bc = EasyMock.createNiceMock(BundleContext.class); + bc.getServiceReferences((String)null, JaxRSUtils.PROVIDERS_FILTER); + EasyMock.expectLastCall().andReturn(new ServiceReference[] {sref}); + sref.getProperty(Constants.RS_PROVIDER_EXPECTED_PROP_KEY); + EasyMock.expectLastCall().andReturn(false); + bc.getService(sref); + AegisElementProvider<?> p = new AegisElementProvider(); + EasyMock.expectLastCall().andReturn(p); + EasyMock.replay(bc, sref); + Map<String, Object> props = new HashMap<String, Object>(); + addRequiredProps(props); + + List<Object> providers = JaxRSUtils.getProviders(bc, props); + assertEquals(1, providers.size()); + assertSame(p, providers.get(0)); + } + + @SuppressWarnings({ + "rawtypes", "unchecked" + }) + public void testNoCustomGlobalProvider() throws Exception { + ServiceReference sref = EasyMock.createNiceMock(ServiceReference.class); + BundleContext bc = EasyMock.createNiceMock(BundleContext.class); + bc.getServiceReferences((String)null, JaxRSUtils.PROVIDERS_FILTER); + EasyMock.expectLastCall().andReturn(new ServiceReference[] {sref}); + sref.getProperty(Constants.RS_PROVIDER_PROP_KEY); + EasyMock.expectLastCall().andReturn(false); + bc.getService(sref); + AegisElementProvider<?> p = new AegisElementProvider(); + EasyMock.expectLastCall().andReturn(p); + EasyMock.replay(bc); + Map<String, Object> props = new HashMap<String, Object>(); + props.put(Constants.RS_PROVIDER_EXPECTED_PROP_KEY, "true"); + addRequiredProps(props); + + List<Object> providers = JaxRSUtils.getProviders(bc, props); + assertEquals(0, providers.size()); + } + + @SuppressWarnings({ + "rawtypes", "unchecked" + }) + public void testCustomGlobalProviderExpected() throws Exception { + ServiceReference sref = EasyMock.createNiceMock(ServiceReference.class); + BundleContext bc = EasyMock.createNiceMock(BundleContext.class); + bc.getServiceReferences((String)null, JaxRSUtils.PROVIDERS_FILTER); + EasyMock.expectLastCall().andReturn(new ServiceReference[] {sref}); + sref.getProperty(Constants.RS_PROVIDER_PROP_KEY); + EasyMock.expectLastCall().andReturn(true); + bc.getService(sref); + AegisElementProvider<?> p = new AegisElementProvider(); + EasyMock.expectLastCall().andReturn(p); + EasyMock.replay(bc, sref); + Map<String, Object> props = new HashMap<String, Object>(); + props.put(Constants.RS_PROVIDER_EXPECTED_PROP_KEY, "true"); + addRequiredProps(props); + + List<Object> providers = JaxRSUtils.getProviders(bc, props); + assertEquals(1, providers.size()); + assertSame(p, providers.get(0)); + } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/PojoConfigurationTypeHandlerTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/PojoConfigurationTypeHandlerTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/PojoConfigurationTypeHandlerTest.java new file mode 100644 index 0000000..b6b05ea --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/PojoConfigurationTypeHandlerTest.java @@ -0,0 +1,422 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.handlers; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.aries.rsa.spi.Endpoint; +import org.apache.aries.rsa.util.EndpointHelper; +import org.apache.cxf.dosgi.dsw.Constants; +import org.apache.cxf.dosgi.dsw.handlers.jaxws.MyJaxWsEchoService; +import org.apache.cxf.dosgi.dsw.handlers.simple.MySimpleEchoService; +import org.apache.cxf.dosgi.dsw.qos.IntentManager; +import org.apache.cxf.dosgi.dsw.qos.IntentManagerImpl; +import org.apache.cxf.dosgi.dsw.qos.IntentMap; +import org.apache.cxf.endpoint.AbstractEndpointFactory; +import org.apache.cxf.endpoint.EndpointImpl; +import org.apache.cxf.endpoint.Server; +import org.apache.cxf.feature.Feature; +import org.apache.cxf.frontend.ClientProxyFactoryBean; +import org.apache.cxf.frontend.ServerFactoryBean; +import org.apache.cxf.jaxws.support.JaxWsEndpointImpl; +import org.apache.cxf.transport.Destination; +import org.apache.cxf.ws.addressing.AttributedURIType; +import org.apache.cxf.ws.addressing.EndpointReferenceType; +import org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean; +import org.easymock.EasyMock; +import org.easymock.IAnswer; +import org.easymock.IMocksControl; +import org.junit.Assert; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Version; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.RemoteConstants; + +public class PojoConfigurationTypeHandlerTest extends TestCase { + + public void testGetPojoAddressEndpointURI() { + IntentManager intentManager = new IntentManagerImpl(new IntentMap()); + PojoConfigurationTypeHandler handler = new PojoConfigurationTypeHandler(null, + intentManager, + dummyHttpServiceManager()); + Map<String, Object> sd = new HashMap<String, Object>(); + String url = "http://somewhere:1234/blah"; + sd.put(RemoteConstants.ENDPOINT_ID, url); + assertEquals(url, handler.getServerAddress(sd, String.class)); + } + + private HttpServiceManager dummyHttpServiceManager() { + return new HttpServiceManager(null, null, null, null); + } + + public void testGetPojoAddressEndpointCxf() { + IntentManager intentManager = new IntentManagerImpl(new IntentMap()); + PojoConfigurationTypeHandler handler = new PojoConfigurationTypeHandler(null, + intentManager, + dummyHttpServiceManager()); + Map<String, Object> sd = new HashMap<String, Object>(); + String url = "http://somewhere:29/boo"; + sd.put("org.apache.cxf.ws.address", url); + assertEquals(url, handler.getServerAddress(sd, String.class)); + } + + public void testGetPojoAddressEndpointPojo() { + IntentManager intentManager = new IntentManagerImpl(new IntentMap()); + PojoConfigurationTypeHandler handler = new PojoConfigurationTypeHandler(null, + intentManager, + dummyHttpServiceManager()); + Map<String, Object> sd = new HashMap<String, Object>(); + String url = "http://somewhere:32768/foo"; + sd.put("osgi.remote.configuration.pojo.address", url); + assertEquals(url, handler.getServerAddress(sd, String.class)); + } + + public void testGetDefaultPojoAddress() { + IntentManager intentManager = new IntentManagerImpl(new IntentMap()); + PojoConfigurationTypeHandler handler = new PojoConfigurationTypeHandler(null, + intentManager, + dummyHttpServiceManager()); + Map<String, Object> sd = new HashMap<String, Object>(); + assertEquals("/java/lang/String", handler.getServerAddress(sd, String.class)); + } + + // todo: add test for data bindings + public void testCreateProxy() { + IMocksControl c = EasyMock.createNiceControl(); + BundleContext bc1 = c.createMock(BundleContext.class); + + BundleContext requestingContext = c.createMock(BundleContext.class); + + final ClientProxyFactoryBean cpfb = c.createMock(ClientProxyFactoryBean.class); + ReflectionServiceFactoryBean sf = c.createMock(ReflectionServiceFactoryBean.class); + EasyMock.expect(cpfb.getServiceFactory()).andReturn(sf).anyTimes(); + IntentManager intentManager = new IntentManagerImpl(new IntentMap()) { + @Override + public String[] applyIntents(List<Feature> features, + AbstractEndpointFactory factory, + Map<String, Object> sd) { + return new String[0]; + } + }; + PojoConfigurationTypeHandler p = new PojoConfigurationTypeHandler(bc1, + intentManager, + dummyHttpServiceManager()) { + @Override + protected ClientProxyFactoryBean createClientProxyFactoryBean(Map<String, Object> sd, Class<?> iClass) { + return cpfb; + } + }; + + Class<?>[] exportedInterfaces = new Class[]{Runnable.class}; + + Map<String, Object> props = new HashMap<String, Object>(); + props.put(RemoteConstants.ENDPOINT_ID, "http://google.de/"); + EndpointHelper.addObjectClass(props, exportedInterfaces); + props.put(RemoteConstants.SERVICE_IMPORTED_CONFIGS, new String[]{"my.config"}); + EndpointDescription endpoint = new EndpointDescription(props); + + cpfb.setAddress((String)EasyMock.eq(props.get(RemoteConstants.ENDPOINT_ID))); + EasyMock.expectLastCall().atLeastOnce(); + + cpfb.setServiceClass(EasyMock.eq(Runnable.class)); + EasyMock.expectLastCall().atLeastOnce(); + + c.replay(); + ClassLoader cl = null; + Object proxy = p.importEndpoint(cl, requestingContext, exportedInterfaces, endpoint); + assertNotNull(proxy); + assertTrue("Proxy is not of the requested type! ", proxy instanceof Runnable); + c.verify(); + } + + public void testCreateServerWithAddressProperty() throws Exception { + BundleContext dswContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.replay(dswContext); + + String myService = "Hi"; + final ServerFactoryBean sfb = createMockServerFactoryBean(); + + IntentMap intentMap = new IntentMap(); + IntentManager intentManager = new IntentManagerImpl(intentMap) { + @Override + public String[] applyIntents(List<Feature> features, AbstractEndpointFactory factory, + Map<String, Object> sd) { + return new String[]{}; + } + }; + PojoConfigurationTypeHandler p = new PojoConfigurationTypeHandler(dswContext, intentManager, + dummyHttpServiceManager()) { + @Override + protected ServerFactoryBean createServerFactoryBean(Map<String, Object> sd, Class<?> iClass) { + return sfb; + } + }; + BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.replay(bundleContext); + + Class<?>[] exportedInterface = new Class[]{String.class}; + Map<String, Object> props = new HashMap<String, Object>(); + EndpointHelper.addObjectClass(props, exportedInterface); + props.put(Constants.WS_ADDRESS_PROPERTY, "http://alternate_host:80/myString"); + + Endpoint exportResult = p.exportService(myService, bundleContext, props, exportedInterface); + Map<String, Object> edProps = exportResult.description().getProperties(); + + assertNotNull(edProps.get(RemoteConstants.SERVICE_IMPORTED_CONFIGS)); + assertEquals(1, ((String[])edProps.get(RemoteConstants.SERVICE_IMPORTED_CONFIGS)).length); + assertEquals(Constants.WS_CONFIG_TYPE, ((String[])edProps.get(RemoteConstants.SERVICE_IMPORTED_CONFIGS))[0]); + assertEquals("http://alternate_host:80/myString", edProps.get(RemoteConstants.ENDPOINT_ID)); + } + + public void testAddressing() throws Exception { + runAddressingTest(new HashMap<String, Object>(), "http://localhost:9000/java/lang/Runnable"); + + Map<String, Object> p1 = new HashMap<String, Object>(); + p1.put("org.apache.cxf.ws.address", "http://somewhere"); + runAddressingTest(p1, "http://somewhere"); + + Map<String, Object> p2 = new HashMap<String, Object>(); + p2.put("org.apache.cxf.rs.address", "https://somewhereelse"); + runAddressingTest(p2, "https://somewhereelse"); + + Map<String, Object> p3 = new HashMap<String, Object>(); + p3.put("org.apache.cxf.ws.port", 65535); + runAddressingTest(p3, "http://localhost:65535/java/lang/Runnable"); + + Map<String, Object> p4 = new HashMap<String, Object>(); + p4.put("org.apache.cxf.ws.port", "8181"); + runAddressingTest(p4, "http://localhost:8181/java/lang/Runnable"); + } + + private void runAddressingTest(Map<String, Object> properties, String expectedAddress) throws Exception { + Class<?>[] exportedInterface = new Class[]{Runnable.class}; + EndpointHelper.addObjectClass(properties, exportedInterface); + BundleContext dswContext = EasyMock.createNiceMock(BundleContext.class); + String expectedUUID = UUID.randomUUID().toString(); + EasyMock.expect(dswContext.getProperty(org.osgi.framework.Constants.FRAMEWORK_UUID)).andReturn(expectedUUID); + EasyMock.replay(dswContext); + + IntentManager intentManager = EasyMock.createNiceMock(IntentManager.class); + EasyMock.replay(intentManager); + + PojoConfigurationTypeHandler handler = new PojoConfigurationTypeHandler(dswContext, + intentManager, + dummyHttpServiceManager()) { + @Override + protected Endpoint createServerFromFactory(ServerFactoryBean factory, + EndpointDescription epd) { + return new ServerWrapper(epd, null); + } + }; + Runnable myService = EasyMock.createMock(Runnable.class); + EasyMock.replay(myService); + + BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.replay(bundleContext); + + Endpoint result = handler.exportService(myService, bundleContext, properties, exportedInterface); + Map<String, Object> props = result.description().getProperties(); + assertEquals(expectedAddress, props.get("org.apache.cxf.ws.address")); + Assert.assertArrayEquals(new String[] {"org.apache.cxf.ws"}, + (String[]) props.get(RemoteConstants.SERVICE_IMPORTED_CONFIGS)); + Assert.assertArrayEquals(new String[] {"java.lang.Runnable"}, + (String[]) props.get(org.osgi.framework.Constants.OBJECTCLASS)); + } + + public void t2estCreateServerException() { + BundleContext dswContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.replay(dswContext); + + IntentManager intentManager = EasyMock.createNiceMock(IntentManager.class); + EasyMock.replay(intentManager); + + PojoConfigurationTypeHandler handler = new PojoConfigurationTypeHandler(dswContext, + intentManager, + dummyHttpServiceManager()) { + @Override + protected Endpoint createServerFromFactory(ServerFactoryBean factory, + EndpointDescription epd) { + throw new TestException(); + } + }; + + Map<String, Object> props = new HashMap<String, Object>(); + + Runnable myService = EasyMock.createMock(Runnable.class); + EasyMock.replay(myService); + try { + handler.exportService(myService, null, props, new Class[]{Runnable.class}); + fail("Expected TestException"); + } catch (TestException e) { + // Expected + } + } + + private ServerFactoryBean createMockServerFactoryBean() { + ReflectionServiceFactoryBean sf = EasyMock.createNiceMock(ReflectionServiceFactoryBean.class); + EasyMock.replay(sf); + + final StringBuilder serverURI = new StringBuilder(); + + ServerFactoryBean sfb = EasyMock.createNiceMock(ServerFactoryBean.class); + Server server = createMockServer(sfb); + + EasyMock.expect(sfb.getServiceFactory()).andReturn(sf).anyTimes(); + EasyMock.expect(sfb.create()).andReturn(server); + sfb.setAddress((String) EasyMock.anyObject()); + EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + serverURI.setLength(0); + serverURI.append(EasyMock.getCurrentArguments()[0]); + return null; + } + }); + EasyMock.expect(sfb.getAddress()).andAnswer(new IAnswer<String>() { + public String answer() throws Throwable { + return serverURI.toString(); + } + }); + EasyMock.replay(sfb); + return sfb; + } + + private Server createMockServer(final ServerFactoryBean sfb) { + AttributedURIType addr = EasyMock.createMock(AttributedURIType.class); + EasyMock.expect(addr.getValue()).andAnswer(new IAnswer<String>() { + public String answer() throws Throwable { + return sfb.getAddress(); + } + }); + EasyMock.replay(addr); + + EndpointReferenceType er = EasyMock.createMock(EndpointReferenceType.class); + EasyMock.expect(er.getAddress()).andReturn(addr); + EasyMock.replay(er); + + Destination destination = EasyMock.createMock(Destination.class); + EasyMock.expect(destination.getAddress()).andReturn(er); + EasyMock.replay(destination); + + Server server = EasyMock.createNiceMock(Server.class); + EasyMock.expect(server.getDestination()).andReturn(destination); + EasyMock.replay(server); + return server; + } + + public void testCreateEndpointProps() { + BundleContext bc = EasyMock.createNiceMock(BundleContext.class); + EasyMock.expect(bc.getProperty("org.osgi.framework.uuid")).andReturn("some_uuid1"); + EasyMock.replay(bc); + + IntentManager intentManager = new IntentManagerImpl(new IntentMap()); + PojoConfigurationTypeHandler pch = new PojoConfigurationTypeHandler(bc, + intentManager, + dummyHttpServiceManager()); + Class<?>[] exportedInterfaces = new Class[] {String.class}; + Map<String, Object> sd = new HashMap<String, Object>(); + sd.put(org.osgi.framework.Constants.SERVICE_ID, 42); + EndpointHelper.addObjectClass(sd, exportedInterfaces); + EndpointDescription epd = pch.createEndpointDesc(sd, new String[] {"org.apache.cxf.ws"}, + "http://localhost:12345", new String[] {"my_intent", "your_intent"}); + + assertEquals("http://localhost:12345", epd.getId()); + assertEquals(Arrays.asList("java.lang.String"), epd.getInterfaces()); + assertEquals(Arrays.asList("org.apache.cxf.ws"), epd.getConfigurationTypes()); + assertEquals(Arrays.asList("my_intent", "your_intent"), epd.getIntents()); + assertEquals(new Version("0.0.0"), epd.getPackageVersion("java.lang")); + } + + public void t2estCreateJaxWsEndpointWithoutIntents() { + IMocksControl c = EasyMock.createNiceControl(); + BundleContext dswBC = c.createMock(BundleContext.class); + + IntentManager intentManager = new DummyIntentManager(); + PojoConfigurationTypeHandler handler = new PojoConfigurationTypeHandler(dswBC, + intentManager, + dummyHttpServiceManager()); + + Map<String, Object> sd = new HashMap<String, Object>(); + sd.put(Constants.WS_ADDRESS_PROPERTY, "/somewhere"); + BundleContext serviceBC = c.createMock(BundleContext.class); + Object myService = null; + c.replay(); + + ServerWrapper serverWrapper = (ServerWrapper)handler.exportService(myService, + serviceBC, + sd, + new Class[]{MyJaxWsEchoService.class}); + c.verify(); + + org.apache.cxf.endpoint.Endpoint ep = serverWrapper.getServer().getEndpoint(); + QName bindingName = ep.getEndpointInfo().getBinding().getName(); + Assert.assertEquals(JaxWsEndpointImpl.class, ep.getClass()); + Assert.assertEquals(new QName("http://jaxws.handlers.dsw.dosgi.cxf.apache.org/", + "MyJaxWsEchoServiceServiceSoapBinding"), + bindingName); + } + + public void t2estCreateSimpleEndpointWithoutIntents() { + IMocksControl c = EasyMock.createNiceControl(); + BundleContext dswBC = c.createMock(BundleContext.class); + + IntentManager intentManager = new DummyIntentManager(); + PojoConfigurationTypeHandler handler + = new PojoConfigurationTypeHandler(dswBC, intentManager, dummyHttpServiceManager()); + Map<String, Object> sd = new HashMap<String, Object>(); + sd.put(Constants.WS_ADDRESS_PROPERTY, "/somewhere_else"); + BundleContext serviceBC = c.createMock(BundleContext.class); + c.replay(); + ServerWrapper serverWrapper = (ServerWrapper)handler.exportService(null, serviceBC, sd, + new Class[]{MySimpleEchoService.class}); + c.verify(); + + org.apache.cxf.endpoint.Endpoint ep = serverWrapper.getServer().getEndpoint(); + QName bindingName = ep.getEndpointInfo().getBinding().getName(); + Assert.assertEquals(EndpointImpl.class, ep.getClass()); + Assert.assertEquals(new QName("http://simple.handlers.dsw.dosgi.cxf.apache.org/", + "MySimpleEchoServiceSoapBinding"), + bindingName); + } + + public static class DummyIntentManager implements IntentManager { + + @Override + public String[] applyIntents(List<Feature> features, + AbstractEndpointFactory factory, + Map<String, Object> props) { + return new String[]{}; + } + + @Override + public void assertAllIntentsSupported(Map<String, Object> serviceProperties) { + } + } + + @SuppressWarnings("serial") + public static class TestException extends RuntimeException { + } +} http://git-wip-us.apache.org/repos/asf/cxf-dosgi/blob/1425743f/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/SecurityDelegatingHttpContextTest.java ---------------------------------------------------------------------- diff --git a/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/SecurityDelegatingHttpContextTest.java b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/SecurityDelegatingHttpContextTest.java new file mode 100644 index 0000000..58b5f58 --- /dev/null +++ b/cxf-dsw/src/test/java/org/apache/cxf/dosgi/dsw/handlers/SecurityDelegatingHttpContextTest.java @@ -0,0 +1,267 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cxf.dosgi.dsw.handlers; + +import java.io.PrintWriter; +import java.net.URL; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; +import org.junit.Assert; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.service.http.HttpContext; + +@SuppressWarnings({ + "unchecked", "rawtypes" + }) +public class SecurityDelegatingHttpContextTest extends TestCase { + + protected HttpContext defaultHttpContext; + protected SecurityDelegatingHttpContext httpContext; + protected CommitResponseFilter commitFilter; + protected DoNothingFilter doNothingFilter; + protected AccessDeniedFilter accessDeniedFilter; + protected String mimeType; + protected URL url; // does not need to exist + + public void setUp() throws Exception { + mimeType = "text/xml"; + url = new URL("file:test.xml"); // does not need to exist + + // Sample filters + commitFilter = new CommitResponseFilter(); + doNothingFilter = new DoNothingFilter(); + accessDeniedFilter = new AccessDeniedFilter(); + + // Mock up the default http context + defaultHttpContext = EasyMock.createNiceMock(HttpContext.class); + EasyMock.expect(defaultHttpContext.getMimeType((String)EasyMock.anyObject())).andReturn(mimeType); + EasyMock.expect(defaultHttpContext.getResource((String)EasyMock.anyObject())).andReturn(url); + EasyMock.replay(defaultHttpContext); + } + + public void testFilterRequired() throws Exception { + // Mock up the service references + ServiceReference[] serviceReferences = new ServiceReference[] {}; + + // Mock up the bundle context + BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.expect(bundleContext.getServiceReferences(Filter.class.getName(), + "(org.apache.cxf.httpservice.filter=true)")) + .andReturn(serviceReferences); + EasyMock.replay(bundleContext); + + // Set up the secure http context + httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext); + httpContext.requireFilter = true; + + // Ensure that the httpContext doesn't allow the request to be processed, since there are no registered servlet + // filters + HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); + EasyMock.replay(request); + HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); + EasyMock.replay(response); + boolean requestAllowed = httpContext.handleSecurity(request, response); + Assert.assertFalse(requestAllowed); + + // Ensure that the httpContext returns true if there is no requirement for registered servlet filters + httpContext.requireFilter = false; + requestAllowed = httpContext.handleSecurity(request, response); + Assert.assertTrue(requestAllowed); + } + + public void testSingleCommitFilter() throws Exception { + // Mock up the service references + ServiceReference filterReference = EasyMock.createNiceMock(ServiceReference.class); + EasyMock.replay(filterReference); + ServiceReference[] serviceReferences = new ServiceReference[] { + filterReference + }; + + // Mock up the bundle context + BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.expect(bundleContext.getServiceReferences((String)EasyMock.anyObject(), (String)EasyMock.anyObject())) + .andReturn(serviceReferences); + EasyMock.expect(bundleContext.getService((ServiceReference)EasyMock.anyObject())).andReturn(commitFilter); + EasyMock.replay(bundleContext); + + // Set up the secure http context + httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext); + + // Ensure that the httpContext returns false, since the filter has committed the response + HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); + EasyMock.replay(request); + HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); + EasyMock.expect(response.isCommitted()).andReturn(false); // the first call checks to see whether to invoke the + // filter + EasyMock.expect(response.isCommitted()).andReturn(true); // the second is called to determine the handleSecurity + // return value + EasyMock.expect(response.getWriter()).andReturn(new PrintWriter(System.out)); + EasyMock.replay(response); + Assert.assertFalse(httpContext.handleSecurity(request, response)); + + // Ensure that the appropriate filters were called + Assert.assertTrue(commitFilter.called); + Assert.assertFalse(doNothingFilter.called); + Assert.assertFalse(accessDeniedFilter.called); + } + + public void testFilterChain() throws Exception { + // Mock up the service references + ServiceReference filterReference = EasyMock.createNiceMock(ServiceReference.class); + EasyMock.replay(filterReference); + ServiceReference[] serviceReferences = new ServiceReference[] { + filterReference, filterReference + }; + + // Mock up the bundle context + BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.expect(bundleContext.getServiceReferences((String)EasyMock.anyObject(), (String)EasyMock.anyObject())) + .andReturn(serviceReferences); + EasyMock.expect(bundleContext.getService((ServiceReference)EasyMock.anyObject())).andReturn(doNothingFilter); + EasyMock.expect(bundleContext.getService((ServiceReference)EasyMock.anyObject())).andReturn(commitFilter); + EasyMock.replay(bundleContext); + + // Set up the secure http context + httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext); + + // Ensure that the httpContext returns false, since the filter has committed the response + HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); + EasyMock.replay(request); + HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); + EasyMock.expect(response.isCommitted()).andReturn(false); // doNothingFilter should not commit the response + EasyMock.expect(response.getWriter()).andReturn(new PrintWriter(System.out)); + EasyMock.expect(response.isCommitted()).andReturn(false); + EasyMock.expect(response.isCommitted()).andReturn(true); // the commit filter indicating that it committed the + // response + EasyMock.replay(response); + Assert.assertFalse(httpContext.handleSecurity(request, response)); + + // Ensure that the appropriate filters were called + Assert.assertTrue(doNothingFilter.called); + Assert.assertTrue(commitFilter.called); + Assert.assertFalse(accessDeniedFilter.called); + } + + public void testAllowRequest() throws Exception { + // Mock up the service references + ServiceReference filterReference = EasyMock.createNiceMock(ServiceReference.class); + EasyMock.replay(filterReference); + ServiceReference[] serviceReferences = new ServiceReference[] { + filterReference + }; + + // Mock up the bundle context + BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.expect(bundleContext.getServiceReferences((String)EasyMock.anyObject(), (String)EasyMock.anyObject())) + .andReturn(serviceReferences); + EasyMock.expect(bundleContext.getService((ServiceReference)EasyMock.anyObject())).andReturn(doNothingFilter); + EasyMock.replay(bundleContext); + + // Set up the secure http context + httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext); + + // Ensure that the httpContext returns true, since the filter has not committed the response + HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); + EasyMock.replay(request); + HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); + EasyMock.expect(response.isCommitted()).andReturn(false); + EasyMock.replay(response); + Assert.assertTrue(httpContext.handleSecurity(request, response)); + + // Ensure that the appropriate filters were called + Assert.assertTrue(doNothingFilter.called); + Assert.assertFalse(commitFilter.called); + Assert.assertFalse(accessDeniedFilter.called); + } + + public void testDelegation() throws Exception { + BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class); + EasyMock.replay(bundleContext); + + // Set up the secure http context + httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext); + + // Ensure that it delegates non-security calls to the wrapped implementation (in this case, the mock) + Assert.assertEquals(mimeType, httpContext.getMimeType("")); + Assert.assertEquals(url, httpContext.getResource("")); + } +} + +class CommitResponseFilter implements Filter { + + boolean called; + + public void init(FilterConfig filterConfig) throws ServletException { + } + + public void destroy() { + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws java.io.IOException, javax.servlet.ServletException { + called = true; + response.getWriter().write("committing the response"); + } +} + +class DoNothingFilter implements Filter { + + boolean called; + + public void init(FilterConfig filterConfig) throws ServletException { + } + + public void destroy() { + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws java.io.IOException, javax.servlet.ServletException { + called = true; + chain.doFilter(request, response); + } +} + +class AccessDeniedFilter implements Filter { + + boolean called; + + public void init(FilterConfig filterConfig) throws ServletException { + } + + public void destroy() { + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws java.io.IOException, javax.servlet.ServletException { + called = true; + ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN); + } +}
