Java tutorial
/*************************************************************************** * Copyright 2012 TXT e-solutions SpA * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work was performed within the IoT_at_Work Project * and partially funded by the European Commission's * 7th Framework Programme under the research area ICT-2009.1.3 * Internet of Things and enterprise environments. * * Authors: * Salvatore Piccione (TXT e-solutions SpA) * * Contributors: * Domenico Rotondi (TXT e-solutions SpA) **************************************************************************/ package it.txt.ens.client.publisher.impl.osgi.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.ops4j.pax.exam.CoreOptions.frameworkProperty; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.repositories; import static org.ops4j.pax.exam.CoreOptions.systemPackage; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.OptionUtils.expand; import it.txt.ens.client.core.ENSEvent; import it.txt.ens.client.publisher.ENSPublisher; import it.txt.ens.client.publisher.ENSPublishingException; import it.txt.ens.client.publisher.factory.ENSEventFactory; import it.txt.ens.client.publisher.impl.osgi.BasicENSPublisherMSF; import it.txt.ens.client.publisher.osgi.FilterAttributes; import it.txt.ens.client.publisher.osgi.RegisteredServices; import it.txt.ens.core.util.converter.MapConverter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.util.Collection; import java.util.Date; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.ExamReactorStrategy; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.springframework.ldap.filter.AndFilter; import org.springframework.ldap.filter.EqualsFilter; /** * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT txtgroup.com) * @contributor Domenico Rotondi (TXT e-solutions SpA - domenico.rotondi AT txtgroup.com) * */ @RunWith(JUnit4TestRunner.class) @ExamReactorStrategy(AllConfinedStagedReactorFactory.class) public class BasicENSPublisherTest { @Inject private BundleContext context; private static final String PROPERTIES_RELATIVE_PATH = "D:\\IoT@Work_DEV\\ENS\\ens-publisher-impl\\src\\test\\resources\\publisher.properties"; private static final Logger LOGGER = Logger.getLogger(BasicENSPublisherTest.class.getName()); private static final long TIMEOUT = 5000; private ENSPublisher publisher; private ENSEventFactory eventFactory; @org.ops4j.pax.exam.junit.Configuration public static Option[] configure() throws MalformedURLException { return expand(mavenBundle("org.osgi", "org.osgi.compendium", "4.3.0"), mavenBundle("org.apache.felix", "org.apache.felix.configadmin", "1.6.0"), mavenBundle("javax.xml.stream", "com.springsource.javax.xml.stream", "1.0.1"), mavenBundle("org.apache.xmlcommons", "com.springsource.org.apache.xmlcommons", "1.3.4"), mavenBundle("com.sun.xml", "com.springsource.com.sun.xml.fastinfoset", "1.2.2"), mavenBundle("javax.activation", "com.springsource.javax.activation", "1.1.1"), mavenBundle("javax.xml.bind", "com.springsource.javax.xml.bind", "2.2.0"), mavenBundle("org.jvnet.staxex", "com.springsource.org.jvnet.staxex", "1.0.0"), mavenBundle("org.apache.xml", "com.springsource.org.apache.xml.resolver", "1.2.0"), mavenBundle("javax.xml.crypto", "com.springsource.javax.xml.crypto", "1.4.3"), mavenBundle("org.apache.xalan", "com.springsource.org.apache.xalan", "2.7.1"), mavenBundle("org.apache.xalan", "com.springsource.org.apache.xml.serializer", "2.7.1"), mavenBundle("org.bouncycastle", "com.springsource.org.bouncycastle.jce", "1.39.0"), mavenBundle("com.sun.xml", "com.springsource.com.sun.xml.bind", "2.2.0"), mavenBundle("org.apache.commons", "com.springsource.org.apache.commons.lang", "2.6.0"), mavenBundle("org.apache.commons", "com.springsource.org.apache.commons.io", "1.4.0"), mavenBundle("com.rabbitmq", "amqp-client", "2.8.7"), mavenBundle("org.apache.xerces", "com.springsource.org.apache.xerces", "2.9.1").noStart(), mavenBundle("org.apache.commons", "com.springsource.org.apache.commons.logging", "1.1.1"), mavenBundle("org.apache.commons", "com.springsource.org.apache.commons.codec", "1.6.0"), mavenBundle("org.apache.httpcomponents", "com.springsource.org.apache.httpcomponents.httpcore", "4.2.1"), mavenBundle("org.apache.httpcomponents", "com.springsource.org.apache.httpcomponents.httpclient", "4.2.1"), mavenBundle("org.springframework", "org.springframework.beans", "3.0.7.RELEASE"), mavenBundle("org.springframework", "org.springframework.core", "3.0.7.RELEASE"), mavenBundle("org.springframework.ldap", "org.springframework.ldap", "1.3.1.RELEASE"), mavenBundle("org.springframework", "org.springframework.transaction", "3.0.7.RELEASE"), mavenBundle("it.txt.access.capability", "capability-commons", "2.0.1"), mavenBundle("it.txt.access.capability.schema", "capability-schema-commons", "1.0.0"), mavenBundle("it.txt.access.capability.schema", "capability-schema-creator", "1.0.1"), mavenBundle("it.txt.access.capability.schema", "capability-schema-verifier", "1.0.1"), mavenBundle("it.txt.access.capability.schema", "capability-schema-library", "1.0.1"), mavenBundle("it.txt.access.capability.libraries", "capability-libs-finder", "1.0.1"), mavenBundle("it.txt.ens", "ens-schema", "2.0.0"), mavenBundle("it.txt.ens", "ens-core", "1.0.0"), mavenBundle("it.txt.ens", "ens-core-util", "1.0.0"), mavenBundle("it.txt.ens", "ens-core-impl", "1.0.0"), mavenBundle("it.txt.ens.client", "ens-client-core", "1.0.0"), mavenBundle("it.txt.ens.client", "ens-client-core-impl", "1.0.0"), mavenBundle("it.txt.ens.client.publisher", "ens-publisher", "1.0.0"), mavenBundle("it.txt.ens.client.publisher", "ens-publisher-impl", "1.0.0"), frameworkProperty("platform").value("felix"), frameworkProperty("ens.authz.request.schemas.dir") .value("D:\\IoT@Work_DEV\\ENS\\ens-schemas\\src\\main\\resources\\xsd"), frameworkProperty("ens.authz.response.schemas.dir") .value("D:\\IoT@Work_DEV\\ENS\\ens-schemas\\src\\main\\resources\\xsd"), systemProperty("java.util.logging.config.file").value( "D:\\IoT@Work_DEV\\ENS\\ens-publisher-impl\\src\\test\\resources\\logging-config.properties"), systemPackage("com.sun.jndi.ldap"), repositories("http://repository.springsource.com/maven/bundles/release", "http://repository.springsource.com/maven/bundles/external", "http://repo1.maven.org/maven2"), junitBundles()); } @Test public void testUseOfBasicENSSubscriber() throws Exception { Thread.currentThread().setContextClassLoader(BasicENSPublisherTest.class.getClassLoader()); assertNotNull("The bundle context is null", context); File propertiesFile = new File(PROPERTIES_RELATIVE_PATH); FileReader reader = null; Properties properties = new Properties(); try { reader = new FileReader(propertiesFile); properties.load(reader); reader.close(); } catch (FileNotFoundException e) { // if (LOGGER.isLoggable(Level.SEVERE)) // LOGGER.log(Level.SEVERE, MessageFormat.format(LOG_MESSAGES.getString("propertyFile.notFound"), // propertiesFile.getAbsolutePath()), e); System.out.println("Properties file not found. File: " + propertiesFile.getAbsolutePath()); e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } } //add implementation ID properties.setProperty(FilterAttributes.PUBLISHER_IMPLEMENTATION_KEY, BasicENSPublisherMSF.IMPLEMENTATION_ID); //add ownership id properties.setProperty(FilterAttributes.PUBLISHER_OWNER_KEY, String.valueOf(context.getBundle().getBundleId())); //retrieve the configuration admin service ServiceReference<ConfigurationAdmin> configAdminSR = context.getServiceReference(ConfigurationAdmin.class); ConfigurationAdmin configAdmin = context.getService(configAdminSR); Configuration config = configAdmin .createFactoryConfiguration(RegisteredServices.PUBLISHER_MANAGED_SERVICE_FACTORY_PID, null); config.update(MapConverter.convert(properties)); context.ungetService(configAdminSR); // Collection<ServiceReference<ENSPublisher>> references = null; EqualsFilter implementationFilter = new EqualsFilter(FilterAttributes.PUBLISHER_IMPLEMENTATION_KEY, BasicENSPublisherMSF.IMPLEMENTATION_ID); EqualsFilter ownershipFilter = new EqualsFilter(FilterAttributes.PUBLISHER_OWNER_KEY, String.valueOf(context.getBundle().getBundleId())); AndFilter and = new AndFilter().and(implementationFilter).and(ownershipFilter); String serviceRegistryFilter = and.toString(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Filtering OSGi service registry with query " + serviceRegistryFilter + ". Class: " + ENSPublisher.class.getName()); } int i = 0; //FIXME add a timeout otherwise we could wait forever! (aspitt semb!) long startTime = System.currentTimeMillis(); do { i++; references = context.getServiceReferences(ENSPublisher.class, serviceRegistryFilter); Thread.sleep(100); } while (references.isEmpty() && (System.currentTimeMillis() - startTime) <= TIMEOUT); System.out.println("Cycle counter " + i); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Count of services found: " + references.size()); } assertEquals("Bad count of " + ENSPublisher.class.getName() + " found.", 1, references.size()); ServiceReference<ENSPublisher> serviceRef = references.iterator().next(); // ServiceReference<ENSSubscriber> serviceRef = context.getServiceReference(ENSSubscriber.class); assertNotNull("The service reference is null", serviceRef); // System.out.println("SERVICE REFERENCE PROPERTIES"); // for (String key : serviceRef.getPropertyKeys()) // System.out.println(key + ": " + serviceRef.getProperty(key)); publisher = context.getService(serviceRef); assertNotNull("The publisher is null", publisher); ServiceReference<ENSEventFactory> eventFactorySR = context.getServiceReference(ENSEventFactory.class); assertNotNull("The service reference for the event factory is null", eventFactorySR); eventFactory = context.getService(eventFactorySR); assertNotNull("The the event factory is null", eventFactory); publisher.connect(); for (int j = 0; j < 100; j++) { publishEvent("Message " + (j + 1)); Thread.sleep(100); } publisher.disconnect(); context.ungetService(serviceRef); } private void publishEvent(String message) { try { ENSEvent event = eventFactory.create(null, message.getBytes(ENSEvent.DEFAULT_CONTENT_ENCODING), new Date(), true); publisher.publish(event); LOGGER.info("Published event:: " + event.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IllegalArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IllegalStateException e) { e.printStackTrace(); fail(e.getMessage()); } catch (ENSPublishingException e) { fail(e.getMessage()); e.printStackTrace(); } } }