http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/pom.xml ---------------------------------------------------------------------- diff --git a/pom.xml b/pom.xml index 192a372..bb54458 100644 --- a/pom.xml +++ b/pom.xml @@ -70,6 +70,7 @@ <skipPerformanceTests>true</skipPerformanceTests> <skipConcurrentTests>true</skipConcurrentTests> <skipRestTests>true</skipRestTests> + <skipActiveMQ5Tests>true</skipActiveMQ5Tests> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> @@ -949,6 +950,12 @@ <exclude>**/org/apache/activemq/artemis/utils/json/**</exclude> <exclude>**/org/apache/activemq/artemis/utils/Base64.java</exclude> <exclude>ratReport.txt</exclude> + <!-- activemq5 unit tests exclude --> + <exclude>**/*.data</exclude> + <exclude>**/*.bin</exclude> + <exclude>**/src/test/resources/keystore</exclude> + <exclude>**/*.log</exclude> + <exclude>**/*.redo</exclude> </excludes> </configuration> <executions>
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/README.md ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/README.md b/tests/activemq5-unit-tests/README.md new file mode 100644 index 0000000..99e17b8 --- /dev/null +++ b/tests/activemq5-unit-tests/README.md @@ -0,0 +1,15 @@ +# ActiveMQ 5 unit tests against ActiveMQ Artemis wrapper + + +This maven module is used to run ActiveMQ5 unit tests against +ActiveMQ Artemis broker. + +The Artemis broker is 'wrapped' in BrokerService and the unit +tests are slightly modified. + +Then run the tests simply do + +```mvn -DskipActiveMQTests=false clean test``` + +It will kickoff the whole test suite. + http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/pom.xml ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/pom.xml b/tests/activemq5-unit-tests/pom.xml new file mode 100644 index 0000000..d6d87e8 --- /dev/null +++ b/tests/activemq5-unit-tests/pom.xml @@ -0,0 +1,387 @@ +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.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. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.activemq.tests</groupId> + <artifactId>artemis-tests-pom</artifactId> + <version>1.0.0-SNAPSHOT</version> + </parent> + + <artifactId>activemq5-unit-tests</artifactId> + <packaging>jar</packaging> + <name>ActiveMQ5.x unit tests</name> + + <properties> + <activemq.basedir>${project.basedir}/../..</activemq.basedir> + <activemq5.project.version>5.11.1</activemq5.project.version> + <jmdns-version>3.4.1</jmdns-version> + <ftpserver-version>1.0.6</ftpserver-version> + <jmock-version>2.5.1</jmock-version> + <spring-version>3.2.11.RELEASE</spring-version> + <org-apache-derby-version>10.11.1.1</org-apache-derby-version> + <commons-io-version>2.4</commons-io-version> + <commons-net-version>3.3</commons-net-version> + <qpid-jms-version>0.30</qpid-jms-version> + <xbean-version>3.18</xbean-version> + <hamcrest-version>1.3</hamcrest-version> + <slf4j-version>1.7.10</slf4j-version> + <jasypt-version>1.9.2</jasypt-version> + <directory-version>2.0.0-M6</directory-version> + <activeio-core-version>3.1.4</activeio-core-version> + + </properties> + + <dependencies> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-client</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-jaas</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-broker</artifactId> + <version>${activemq5.project.version}</version> + <type>test-jar</type> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-jdbc-store</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-kahadb-store</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-leveldb-store</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-pool</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-spring</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-partition</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-stomp</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-console</artifactId> + <version>${activemq5.project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activeio-core</artifactId> + <version>${activeio-core-version}</version> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.11</version> + <scope>compile</scope> + </dependency> + + <dependency> + <groupId>org.osgi</groupId> + <artifactId>org.osgi.core</artifactId> + <version>4.3.1</version> + </dependency> + + <dependency> + <groupId>javax.jmdns</groupId> + <artifactId>jmdns</artifactId> + <version>${jmdns-version}</version> + </dependency> + + <dependency> + <groupId>org.apache.ftpserver</groupId> + <artifactId>ftpserver-core</artifactId> + <version>${ftpserver-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jmock</groupId> + <artifactId>jmock-junit4</artifactId> + <version>${jmock-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jmock</groupId> + <artifactId>jmock-legacy</artifactId> + <version>${jmock-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-jms</artifactId> + <version>${spring-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.derby</groupId> + <artifactId>derby</artifactId> + <version>${org-apache-derby-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>${commons-io-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>commons-net</groupId> + <artifactId>commons-net</artifactId> + <version>${commons-net-version}</version> + </dependency> + + <dependency> + <groupId>org.apache.qpid</groupId> + <artifactId>qpid-amqp-1-0-client-jms</artifactId> + <version>${qpid-jms-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.xbean</groupId> + <artifactId>xbean-spring</artifactId> + <version>${xbean-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-all</artifactId> + <version>${hamcrest-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + <version>${slf4j-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> + <version>${spring-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jasypt</groupId> + <artifactId>jasypt</artifactId> + <version>${jasypt-version}</version> + </dependency> + + <dependency> + <groupId>org.jasypt</groupId> + <artifactId>jasypt-spring31</artifactId> + <version>${jasypt-version}</version> + <optional>true</optional> + </dependency> + + <dependency> + <groupId>org.apache.directory.server</groupId> + <artifactId>apacheds-core-integ</artifactId> + <version>${directory-version}</version> + <scope>test</scope> + <exclusions> + <exclusion> + <groupId>bouncycastle</groupId> + <artifactId>bcprov-jdk15</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcprov-jdk15</artifactId> + <version>1.46</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.directory.server</groupId> + <artifactId>apacheds-server-integ</artifactId> + <version>${directory-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.fusesource.joram-jms-tests</groupId> + <artifactId>joram-jms-tests</artifactId> + <version>1.0</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.easymock</groupId> + <artifactId>easymock</artifactId> + <version>3.2</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.fusesource.mqtt-client</groupId> + <artifactId>mqtt-client</artifactId> + <version>1.10</version> + <scope>test</scope> + </dependency> + + <!-- artemis modules --> + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>artemis-commons</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>artemis-server</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>artemis-openwire-protocol</artifactId> + <version>${project.version}</version> + </dependency> + + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.rat</groupId> + <artifactId>apache-rat-plugin</artifactId> + <version>0.11</version> + <configuration> + <reportFile>${activemq.basedir}/ratReport.txt</reportFile> + <skip>${skipLicenseCheck}</skip> + <excludes> + <exclude>**/*.data</exclude> + <exclude>**/*.bin</exclude> + <exclude>**/*.log</exclude> + <exclude>**/*.redo</exclude> + <exclude>**/src/test/resources/keystore</exclude> + <exclude>**/META-INF/services/*</exclude> + <exclude>**/*/*.txt</exclude> + <exclude>**/*.md</exclude> + </excludes> + </configuration> + <executions> + <execution> + <phase>compile</phase> + <goals> + <goal>check</goal> + </goals> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-checkstyle-plugin</artifactId> + <version>2.12</version> + <configuration> + <skip>true</skip> + </configuration> + <executions> + <execution> + <phase>compile</phase> + <goals> + <goal>check</goal> + </goals> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-bundle-plugin</artifactId> + <version>2.5.3</version> + <inherited>true</inherited> + <extensions>true</extensions> + <configuration> + <instructions> + <Bundle-Activator>org.apache.activemq.util.osgi.Activator</Bundle-Activator> + </instructions> + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <configuration> + <skipTests>${skipActiveMQ5Tests}</skipTests> + </configuration> + </plugin> + + </plugins> + </build> + +</project> + http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/artemiswrapper/ArtemisBrokerHelper.java ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/artemiswrapper/ArtemisBrokerHelper.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/artemiswrapper/ArtemisBrokerHelper.java new file mode 100644 index 0000000..8d5cdab --- /dev/null +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/artemiswrapper/ArtemisBrokerHelper.java @@ -0,0 +1,76 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.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.activemq.artemiswrapper; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URI; + +import org.apache.activemq.command.ActiveMQDestination; + +public class ArtemisBrokerHelper { + + private static volatile Object service = null; + private static Class<?> serviceClass; + + static { + try { + serviceClass = Class.forName("org.apache.activemq.broker.BrokerService"); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + + } + // start a tcp transport artemis broker, the broker need to + // be invm with client. + public static void startArtemisBroker(URI location) throws IOException { + if (service != null) { + return; + } + try { + service = serviceClass.newInstance(); + Method startMethod = serviceClass.getMethod("start"); + startMethod.invoke(service, (Object[]) null); + } catch (InstantiationException e) { + throw new IOException("Inst exception", e); + } catch (IllegalAccessException e) { + throw new IOException("IllegalAccess exception ", e); + } catch (NoSuchMethodException e) { + throw new IOException("Nosuchmethod", e); + } catch (SecurityException e) { + throw new IOException("Security exception", e); + } catch (IllegalArgumentException e) { + throw new IOException("IllegalArgumentException exception", e); + } catch (InvocationTargetException e) { + throw new IOException("InvocationTargetException exception", e); + } + } + + public static void makeSureDestinationExists(ActiveMQDestination activemqDestination) throws Exception { + Method startMethod = serviceClass.getMethod("makeSureDestinationExists", ActiveMQDestination.class); + startMethod.invoke(service, activemqDestination); + } + + //some tests run broker in setUp(). This need be called + //to prevent auto broker creation. + public static void setBroker(Object startedBroker) { + service = startedBroker; + } + +} + http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/BrokerService.java ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/BrokerService.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/BrokerService.java new file mode 100644 index 0000000..cf9c939 --- /dev/null +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/BrokerService.java @@ -0,0 +1,811 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.activemq.broker; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; +import java.security.Provider; +import java.security.Security; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; + +import org.apache.activemq.ActiveMQConnectionMetaData; +import org.apache.activemq.ConfigurationException; +import org.apache.activemq.Service; +import org.apache.activemq.advisory.AdvisoryBroker; +import org.apache.activemq.broker.artemiswrapper.ArtemisBrokerWrapper; +import org.apache.activemq.broker.cluster.ConnectionSplitBroker; +import org.apache.activemq.broker.jmx.AnnotatedMBean; +import org.apache.activemq.broker.jmx.BrokerMBeanSupport; +import org.apache.activemq.broker.jmx.BrokerView; +import org.apache.activemq.broker.jmx.ConnectorView; +import org.apache.activemq.broker.jmx.ConnectorViewMBean; +import org.apache.activemq.broker.jmx.HealthView; +import org.apache.activemq.broker.jmx.HealthViewMBean; +import org.apache.activemq.broker.jmx.JmsConnectorView; +import org.apache.activemq.broker.jmx.JobSchedulerView; +import org.apache.activemq.broker.jmx.JobSchedulerViewMBean; +import org.apache.activemq.broker.jmx.Log4JConfigView; +import org.apache.activemq.broker.jmx.ManagedRegionBroker; +import org.apache.activemq.broker.jmx.ManagementContext; +import org.apache.activemq.broker.jmx.NetworkConnectorView; +import org.apache.activemq.broker.jmx.NetworkConnectorViewMBean; +import org.apache.activemq.broker.jmx.ProxyConnectorView; +import org.apache.activemq.broker.region.CompositeDestinationInterceptor; +import org.apache.activemq.broker.region.Destination; +import org.apache.activemq.broker.region.DestinationFactory; +import org.apache.activemq.broker.region.DestinationFactoryImpl; +import org.apache.activemq.broker.region.DestinationInterceptor; +import org.apache.activemq.broker.region.RegionBroker; +import org.apache.activemq.broker.region.policy.PolicyMap; +import org.apache.activemq.broker.region.virtual.MirroredQueue; +import org.apache.activemq.broker.region.virtual.VirtualDestination; +import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor; +import org.apache.activemq.broker.region.virtual.VirtualTopic; +import org.apache.activemq.broker.scheduler.JobSchedulerStore; +import org.apache.activemq.broker.scheduler.SchedulerBroker; +import org.apache.activemq.broker.scheduler.memory.InMemoryJobSchedulerStore; +import org.apache.activemq.command.ActiveMQDestination; +import org.apache.activemq.command.ActiveMQQueue; +import org.apache.activemq.command.BrokerId; +import org.apache.activemq.command.ProducerInfo; +import org.apache.activemq.filter.DestinationFilter; +import org.apache.activemq.network.ConnectionFilter; +import org.apache.activemq.network.DiscoveryNetworkConnector; +import org.apache.activemq.network.NetworkConnector; +import org.apache.activemq.network.jms.JmsConnector; +import org.apache.activemq.openwire.OpenWireFormat; +import org.apache.activemq.proxy.ProxyConnector; +import org.apache.activemq.security.MessageAuthorizationPolicy; +import org.apache.activemq.selector.SelectorParser; +import org.apache.activemq.store.JournaledStore; +import org.apache.activemq.store.PListStore; +import org.apache.activemq.store.PersistenceAdapter; +import org.apache.activemq.store.PersistenceAdapterFactory; +import org.apache.activemq.store.memory.MemoryPersistenceAdapter; +import org.apache.activemq.thread.Scheduler; +import org.apache.activemq.thread.TaskRunnerFactory; +import org.apache.activemq.transport.TransportFactorySupport; +import org.apache.activemq.transport.TransportServer; +import org.apache.activemq.transport.vm.VMTransportFactory; +import org.apache.activemq.usage.SystemUsage; +import org.apache.activemq.util.BrokerSupport; +import org.apache.activemq.util.DefaultIOExceptionHandler; +import org.apache.activemq.util.IOExceptionHandler; +import org.apache.activemq.util.IOExceptionSupport; +import org.apache.activemq.util.IOHelper; +import org.apache.activemq.util.InetAddressUtil; +import org.apache.activemq.util.ServiceStopper; +import org.apache.activemq.util.ThreadPoolUtils; +import org.apache.activemq.util.TimeUtils; +import org.apache.activemq.util.URISupport; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +/** + * Manages the life-cycle of an ActiveMQ Broker. A BrokerService consists of a + * number of transport connectors, network connectors and a bunch of properties + * which can be used to configure the broker as its lazily created. + * + * @org.apache.xbean.XBean + */ +public class BrokerService implements Service +{ + public static final String DEFAULT_PORT = "61616"; + public static final String DEFAULT_BROKER_NAME = "localhost"; + public static final String BROKER_VERSION; + public static final int DEFAULT_MAX_FILE_LENGTH = 1024 * 1024 * 32; + public static final long DEFAULT_START_TIMEOUT = 600000L; + + public String SERVER_SIDE_KEYSTORE; + public String KEYSTORE_PASSWORD; + public String SERVER_SIDE_TRUSTSTORE; + public String TRUSTSTORE_PASSWORD; + public String storeType; + + private static final Logger LOG = LoggerFactory.getLogger(BrokerService.class); + + @SuppressWarnings("unused") + private static final long serialVersionUID = 7353129142305630237L; + + private String brokerName = DEFAULT_BROKER_NAME; + private Broker broker; + private BrokerId brokerId; + private Throwable startException = null; + private boolean startAsync = false; + public Set<Integer> extraConnectors = new HashSet<Integer>(); + private File dataDirectoryFile; + + static + { + InputStream in; + String version = null; + if ((in = BrokerService.class.getResourceAsStream("/org/apache/activemq/version.txt")) != null) + { + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + try + { + version = reader.readLine(); + } + catch (Exception e) + { + } + } + BROKER_VERSION = version; + } + + @Override + public String toString() + { + return "BrokerService[" + getBrokerName() + "]"; + } + + private String getBrokerVersion() + { + String version = ActiveMQConnectionMetaData.PROVIDER_VERSION; + if (version == null) + { + version = BROKER_VERSION; + } + + return version; + } + + + @Override + public void start() throws Exception + { + startBroker(startAsync); + } + + private void startBroker(boolean async) throws Exception + { + if (async) + { + new Thread("Broker Starting Thread") + { + @Override + public void run() + { + try + { + doStartBroker(); + } + catch (Throwable t) + { + startException = t; + } + } + }.start(); + } + else + { + doStartBroker(); + } + } + + private void doStartBroker() throws Exception + { + if (startException != null) + { + return; + } + + broker = getBroker(); + brokerId = broker.getBrokerId(); + + LOG.info("Apache ActiveMQ Artemis Wrapper {} ({}, {}) is starting", new Object[]{getBrokerVersion(), getBrokerName(), brokerId}); + + try + { + broker.start(); + } + catch (Exception e) + { + throw e; + } + catch (Throwable t) + { + throw new Exception(t); + } + + LOG.info("Apache ActiveMQ Artemis Wrapper {} ({}, {}) started", new Object[]{getBrokerVersion(), getBrokerName(), brokerId}); + LOG.info("For help or more information please see: http://activemq.apache.org"); + + } + + + /** + * @throws Exception + * @org.apache .xbean.DestroyMethod + */ + @Override + public void stop() throws Exception + { + + LOG.info("Apache ActiveMQ Artemis{} ({}, {}) is shutting down", new Object[]{getBrokerVersion(), getBrokerName(), brokerId}); + + if (broker != null) + { + broker.stop(); + broker = null; + } + LOG.info("Apache ActiveMQ Artemis {} ({}, {}) is shutdown", new Object[]{getBrokerVersion(), getBrokerName(), brokerId}); + } + + // Properties + // ------------------------------------------------------------------------- + + /** + * Returns the message broker + */ + public Broker getBroker() throws Exception + { + if (broker == null) + { + broker = createBroker(); + } + return broker; + } + + public String getBrokerName() + { + return brokerName; + } + + /** + * Sets the name of this broker; which must be unique in the network + * + * @param brokerName + */ + public void setBrokerName(String brokerName) + { + if (brokerName == null) + { + throw new NullPointerException("The broker name cannot be null"); + } + String str = brokerName.replaceAll("[^a-zA-Z0-9\\.\\_\\-\\:]", "_"); + if (!str.equals(brokerName)) + { + LOG.error("Broker Name: {} contained illegal characters - replaced with {}", brokerName, str); + } + this.brokerName = str.trim(); + } + + /** + * Factory method to create a new broker + * + * @throws Exception + * @throws + * @throws + */ + protected Broker createBroker() throws Exception + { + broker = createBrokerWrapper(); + return broker; + } + + private Broker createBrokerWrapper() + { + return new ArtemisBrokerWrapper(this); + } + + public void makeSureDestinationExists(ActiveMQDestination activemqDestination) throws Exception + { + System.out.println(">>>> making sure dest exits: " + activemqDestination); + ArtemisBrokerWrapper hqBroker = (ArtemisBrokerWrapper) this.broker; + //it can be null + if (activemqDestination == null) + { + return; + } + if (activemqDestination.isQueue()) + { + String qname = activemqDestination.getPhysicalName(); + System.out.println("physical name: " + qname); + hqBroker.makeSureQueueExists(qname); + } + } + + public boolean enableSsl() + { + return this.SERVER_SIDE_KEYSTORE != null; + } + + //below are methods called directly by tests + //we don't actually implement any of these for now, + //just to make test compile pass. + + //we may get class cast exception as in TestSupport it + //casts the broker to RegionBroker, which we didn't + //implement (wrap) yet. Consider solving it later. + public Broker getRegionBroker() + { + return broker; + } + + public void setPersistenceAdapter(PersistenceAdapter persistenceAdapter) throws IOException + { + } + + public File getDataDirectoryFile() + { + if (dataDirectoryFile == null) + { + dataDirectoryFile = new File(IOHelper.getDefaultDataDirectory()); + } + return dataDirectoryFile; + } + + public File getBrokerDataDirectory() + { + String brokerDir = getBrokerName(); + return new File(getDataDirectoryFile(), brokerDir); + } + + public PersistenceAdapter getPersistenceAdapter() throws IOException + { + return null; + } + + public void waitUntilStopped() + { + } + + public boolean waitUntilStarted() + { + return true; + } + + public void setDestinationPolicy(PolicyMap policyMap) + { + } + + public void setDeleteAllMessagesOnStartup(boolean deletePersistentMessagesOnStartup) + { + } + + public void setUseJmx(boolean useJmx) + { + } + + public ManagementContext getManagementContext() + { + return null; + } + + public BrokerView getAdminView() throws Exception + { + return null; + } + + public List<TransportConnector> getTransportConnectors() + { + return new ArrayList<>(); + } + + public TransportConnector addConnector(String bindAddress) throws Exception + { + return null; + } + + public void setIoExceptionHandler(IOExceptionHandler ioExceptionHandler) + { + } + + public void setPersistent(boolean persistent) + { + } + + public boolean isSlave() + { + return false; + } + + public Destination getDestination(ActiveMQDestination destination) throws Exception + { + return null; + } + + public void setAllowTempAutoCreationOnSend(boolean allowTempAutoCreationOnSend) + { + } + + public void setDedicatedTaskRunner(boolean dedicatedTaskRunner) + { + } + + public void setAdvisorySupport(boolean advisorySupport) + { + } + + public void setUseShutdownHook(boolean useShutdownHook) + { + } + + public void deleteAllMessages() throws IOException + { + } + + public Service[] getServices() + { + return null; + } + + public void setPopulateUserNameInMBeans(boolean value) + { + } + + public void setDestinations(ActiveMQDestination[] destinations) + { + } + + public URI getVmConnectorURI() + { + return null; + } + + public SystemUsage getSystemUsage() + { + return null; + } + + public synchronized PListStore getTempDataStore() + { + return null; + } + + public void setJmsBridgeConnectors(JmsConnector[] jmsConnectors) + { + } + + public void setDestinationInterceptors(DestinationInterceptor[] destinationInterceptors) + { + } + + public SslContext getSslContext() + { + return null; + } + + public void setDataDirectory(String dataDirectory) + { + } + + public void setPlugins(BrokerPlugin[] plugins) + { + } + + public void setKeepDurableSubsActive(boolean keepDurableSubsActive) + { + } + + public NetworkConnector addNetworkConnector(String discoveryAddress) throws Exception + { + return null; + } + + public TransportConnector getConnectorByName(String connectorName) + { + return null; + } + + public TransportConnector addConnector(TransportConnector connector) throws Exception + { + return connector; + } + + public void setEnableStatistics(boolean enableStatistics) + { + } + + public void setSystemUsage(SystemUsage memoryManager) + { + } + + public void setManagementContext(ManagementContext managementContext) + { + } + + public void setSchedulerDirectoryFile(File schedulerDirectory) + { + } + + public List<NetworkConnector> getNetworkConnectors() + { + return new ArrayList<>(); + } + + public void setSchedulerSupport(boolean schedulerSupport) + { + } + + public void setPopulateJMSXUserID(boolean populateJMSXUserID) + { + } + + public boolean isUseJmx() + { + return false; + } + + public boolean isPersistent() + { + return false; + } + + public TransportConnector getTransportConnectorByScheme(String scheme) + { + return null; + } + + public TaskRunnerFactory getTaskRunnerFactory() + { + return null; + } + + public boolean isStarted() + { + if (broker == null) return false; + return !broker.isStopped(); + } + + public ProxyConnector addProxyConnector(ProxyConnector connector) throws Exception + { + return connector; + } + + public void setDataDirectoryFile(File dataDirectoryFile) + { + this.dataDirectoryFile = dataDirectoryFile; + } + + public PolicyMap getDestinationPolicy() + { + return null; + } + + public void setTransportConnectorURIs(String[] transportConnectorURIs) + { + } + + public boolean isPopulateJMSXUserID() + { + return false; + } + + public NetworkConnector getNetworkConnectorByName(String connectorName) + { + return null; + } + + public boolean removeNetworkConnector(NetworkConnector connector) + { + return true; + } + + public void setTransportConnectors(List<TransportConnector> transportConnectors) throws Exception + { + } + + public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception + { + return connector; + } + + public void setTempDataStore(PListStore tempDataStore) + { + } + + public void setJobSchedulerStore(JobSchedulerStore jobSchedulerStore) + { + } + + public ObjectName getBrokerObjectName() throws MalformedObjectNameException + { + return null; + } + + public TransportConnector addConnector(URI bindAddress) throws Exception + { + return null; + } + + public void setCacheTempDestinations(boolean cacheTempDestinations) + { + } + + public void setOfflineDurableSubscriberTimeout(long offlineDurableSubscriberTimeout) + { + } + + public void setOfflineDurableSubscriberTaskSchedule(long offlineDurableSubscriberTaskSchedule) + { + } + + public boolean isStopped() + { + return broker.isStopped(); + } + + public void setBrokerId(String brokerId) + { + } + + public BrokerPlugin[] getPlugins() + { + return null; + } + + public void stopAllConnectors(ServiceStopper stopper) + { + } + + public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) + { + } + + public void setNetworkConnectorStartAsync(boolean networkConnectorStartAsync) + { + } + + public boolean isRestartAllowed() + { + return true; + } + + public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) + { + } + + public void start(boolean force) throws Exception + { + this.start(); + } + + public void setMonitorConnectionSplits(boolean monitorConnectionSplits) + { + } + + public void setUseMirroredQueues(boolean useMirroredQueues) + { + } + + public File getTmpDataDirectory() + { + return null; + } + + public boolean isUseShutdownHook() + { + return true; + } + + public boolean isDeleteAllMessagesOnStartup() + { + return false; + } + + public void setUseVirtualTopics(boolean useVirtualTopics) + { + } + + public boolean isUseLoggingForShutdownErrors() + { + return true; + } + + public TransportConnector addConnector(TransportServer transport) throws Exception + { + return null; + } + + public synchronized JobSchedulerStore getJobSchedulerStore() + { + return null; + } + + public boolean removeConnector(TransportConnector connector) throws Exception + { + return true; + } + + public ConnectionContext getAdminConnectionContext() throws Exception { + return null; + } + + public void setUseAuthenticatedPrincipalForJMSXUserID(boolean useAuthenticatedPrincipalForJMSXUserID) + { + } + + public void setSchedulePeriodForDestinationPurge(int schedulePeriodForDestinationPurge) + { + } + + public void setMbeanInvocationTimeout(long mbeanInvocationTimeout) + { + } + + public void setNetworkConnectors(List<?> networkConnectors) throws Exception + { + } + + public void removeDestination(ActiveMQDestination destination) throws Exception + { + } + + public void setMaxPurgedDestinationsPerSweep(int maxPurgedDestinationsPerSweep) + { + } + + public void setBrokerObjectName(ObjectName brokerObjectName) + { + } + + public Map<String, String> getTransportConnectorURIsAsMap() + { + return null; + } + + public void setSslContext(SslContext sslContext) + { + } + + public void setPersistenceFactory(PersistenceAdapterFactory persistenceFactory) + { + } + + protected TransportConnector createTransportConnector(URI brokerURI) throws Exception + { + return null; + } + +} + + + http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/SslBrokerService.java ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/SslBrokerService.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/SslBrokerService.java new file mode 100644 index 0000000..9699cf3 --- /dev/null +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/SslBrokerService.java @@ -0,0 +1,61 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.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.activemq.broker; + +import org.apache.activemq.transport.TransportFactorySupport; +import org.apache.activemq.transport.TransportServer; +import org.apache.activemq.transport.tcp.SslTransportFactory; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.TrustManager; +import java.io.IOException; +import java.net.URI; +import java.security.KeyManagementException; +import java.security.SecureRandom; + +/** + * A BrokerService that allows access to the key and trust managers used by SSL + * connections. There is no reason to use this class unless SSL is being used + * AND the key and trust managers need to be specified from within code. In + * fact, if the URI passed to this class does not have an "ssl" scheme, this + * class will pass all work on to its superclass. + * + * @author [email protected] (Sepand) + */ +public class SslBrokerService extends BrokerService +{ + + public TransportConnector addSslConnector(String bindAddress, KeyManager[] km, TrustManager[] tm, SecureRandom random) throws Exception { + return null; + } + + public TransportConnector addSslConnector(URI bindAddress, KeyManager[] km, TrustManager[] tm, SecureRandom random) throws Exception { + return null; + } + + protected TransportServer createSslTransportServer(URI brokerURI, KeyManager[] km, TrustManager[] tm, SecureRandom random) throws IOException, KeyManagementException { + return null; + } + + //one way + public void setupSsl(String keystoreType, String password, String serverKeystore) { + this.SERVER_SIDE_KEYSTORE = serverKeystore; + this.KEYSTORE_PASSWORD = password; + this.storeType = keystoreType; + } +} http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerBase.java ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerBase.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerBase.java new file mode 100644 index 0000000..227ad1b --- /dev/null +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerBase.java @@ -0,0 +1,674 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.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.activemq.broker.artemiswrapper; + + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ThreadPoolExecutor; + +import org.apache.activemq.artemis.api.core.TransportConfiguration; +import org.apache.activemq.artemis.core.asyncio.impl.AsynchronousFileImpl; +import org.apache.activemq.artemis.core.config.Configuration; +import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; +import org.apache.activemq.artemis.core.remoting.impl.invm.InVMAcceptorFactory; +import org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptorFactory; +import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory; +import org.apache.activemq.artemis.core.server.ActiveMQServer; +import org.apache.activemq.artemis.core.server.ActiveMQServers; +import org.apache.activemq.artemis.core.server.JournalType; +import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy; +import org.apache.activemq.artemis.core.settings.impl.AddressSettings; +import org.apache.activemq.broker.Broker; +import org.apache.activemq.broker.BrokerService; +import org.apache.activemq.broker.Connection; +import org.apache.activemq.broker.ConnectionContext; +import org.apache.activemq.broker.ConsumerBrokerExchange; +import org.apache.activemq.broker.ProducerBrokerExchange; +import org.apache.activemq.broker.region.Destination; +import org.apache.activemq.broker.region.MessageReference; +import org.apache.activemq.broker.region.Subscription; +import org.apache.activemq.command.ActiveMQDestination; +import org.apache.activemq.command.BrokerId; +import org.apache.activemq.command.BrokerInfo; +import org.apache.activemq.command.ConnectionInfo; +import org.apache.activemq.command.ConsumerControl; +import org.apache.activemq.command.ConsumerInfo; +import org.apache.activemq.command.DestinationInfo; +import org.apache.activemq.command.Message; +import org.apache.activemq.command.MessageAck; +import org.apache.activemq.command.MessageDispatch; +import org.apache.activemq.command.MessageDispatchNotification; +import org.apache.activemq.command.MessagePull; +import org.apache.activemq.command.ProducerInfo; +import org.apache.activemq.command.RemoveSubscriptionInfo; +import org.apache.activemq.command.Response; +import org.apache.activemq.command.SessionInfo; +import org.apache.activemq.command.TransactionId; +import org.apache.activemq.store.PListStore; +import org.apache.activemq.thread.Scheduler; +import org.apache.activemq.usage.Usage; +import org.junit.rules.TemporaryFolder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class ArtemisBrokerBase implements Broker { + + private static final Logger LOG = LoggerFactory + .getLogger(ArtemisBrokerBase.class); + public static final String INVM_ACCEPTOR_FACTORY = InVMAcceptorFactory.class + .getCanonicalName(); + + public static final String NETTY_ACCEPTOR_FACTORY = NettyAcceptorFactory.class + .getCanonicalName(); + + public static final String NETTY_CONNECTOR_FACTORY = NettyConnectorFactory.class + .getCanonicalName(); + + protected static final String CLUSTER_PASSWORD = "UnitTestsClusterPassword"; + + protected volatile boolean stopped; + protected BrokerId brokerId = new BrokerId("Artemis Broker"); + protected BrokerService bservice; + protected TemporaryFolder temporaryFolder = new TemporaryFolder(); + protected String testDir; + protected boolean realStore = false; + + protected ActiveMQServer server; + + protected boolean enableSecurity = false; + + public ArtemisBrokerBase() { + try { + this.temporaryFolder.create(); + } catch (IOException e) { + } + } + @Override + public Destination addDestination(ConnectionContext context, + ActiveMQDestination destination, boolean createIfTemporary) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeDestination(ConnectionContext context, + ActiveMQDestination destination, long timeout) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Map<ActiveMQDestination, Destination> getDestinationMap() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeConsumer(ConnectionContext context, ConsumerInfo info) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeSubscription(ConnectionContext context, + RemoveSubscriptionInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void send(ProducerBrokerExchange producerExchange, Message message) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void acknowledge(ConsumerBrokerExchange consumerExchange, + MessageAck ack) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Response messagePull(ConnectionContext context, MessagePull pull) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void processDispatchNotification( + MessageDispatchNotification messageDispatchNotification) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void gc() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Set<Destination> getDestinations(ActiveMQDestination destination) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void processConsumerControl(ConsumerBrokerExchange consumerExchange, + ConsumerControl control) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void reapplyInterceptor() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Broker getAdaptor(Class type) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public BrokerId getBrokerId() { + return brokerId; + } + + @Override + public String getBrokerName() { + return "Artemis Broker"; + } + + @Override + public void addBroker(Connection connection, BrokerInfo info) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeBroker(Connection connection, BrokerInfo info) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void addConnection(ConnectionContext context, ConnectionInfo info) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeConnection(ConnectionContext context, + ConnectionInfo info, Throwable error) throws Exception { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public void addSession(ConnectionContext context, SessionInfo info) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeSession(ConnectionContext context, SessionInfo info) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void addProducer(ConnectionContext context, ProducerInfo info) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void removeProducer(ConnectionContext context, ProducerInfo info) + throws Exception { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public Connection[] getClients() throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public ActiveMQDestination[] getDestinations() throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public Map<ActiveMQDestination, Destination> getDestinationMap( + ActiveMQDestination destination) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public TransactionId[] getPreparedTransactions(ConnectionContext context) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void beginTransaction(ConnectionContext context, TransactionId xid) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public int prepareTransaction(ConnectionContext context, TransactionId xid) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void rollbackTransaction(ConnectionContext context, TransactionId xid) + throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void commitTransaction(ConnectionContext context, TransactionId xid, + boolean onePhase) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void forgetTransaction(ConnectionContext context, + TransactionId transactionId) throws Exception { + throw new RuntimeException("Don't call me!"); + } + + @Override + public BrokerInfo[] getPeerBrokerInfos() { + return null; + } + + @Override + public void preProcessDispatch(MessageDispatch messageDispatch) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void postProcessDispatch(MessageDispatch messageDispatch) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public boolean isStopped() { + return stopped; + } + + @Override + public Set<ActiveMQDestination> getDurableDestinations() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void addDestinationInfo(ConnectionContext context, + DestinationInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public void removeDestinationInfo(ConnectionContext context, + DestinationInfo info) throws Exception { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public boolean isFaultTolerantConfiguration() { + return false; + } + + @Override + public ConnectionContext getAdminConnectionContext() { + return null; + } + + @Override + public void setAdminConnectionContext( + ConnectionContext adminConnectionContext) { + // + } + + @Override + public PListStore getTempDataStore() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public URI getVmConnectorURI() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void brokerServiceStarted() { + stopped = false; + } + + @Override + public BrokerService getBrokerService() { + return this.bservice; + } + + @Override + public Broker getRoot() { + return this; + } + + @Override + public boolean isExpired(MessageReference messageReference) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void messageExpired(ConnectionContext context, + MessageReference messageReference, Subscription subscription) { + throw new RuntimeException("Don't call me!"); + + } + + @Override + public boolean sendToDeadLetterQueue(ConnectionContext context, + MessageReference messageReference, Subscription subscription, + Throwable poisonCause) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public long getBrokerSequenceId() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void messageConsumed(ConnectionContext context, + MessageReference messageReference) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void messageDelivered(ConnectionContext context, + MessageReference messageReference) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void messageDiscarded(ConnectionContext context, Subscription sub, + MessageReference messageReference) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void slowConsumer(ConnectionContext context, + Destination destination, Subscription subs) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void fastProducer(ConnectionContext context, + ProducerInfo producerInfo, ActiveMQDestination destination) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void isFull(ConnectionContext context, Destination destination, + Usage usage) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void nowMasterBroker() { + } + + @Override + public Scheduler getScheduler() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public ThreadPoolExecutor getExecutor() { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void networkBridgeStarted(BrokerInfo brokerInfo, + boolean createdByDuplex, String remoteIp) { + throw new RuntimeException("Don't call me!"); + } + + @Override + public void networkBridgeStopped(BrokerInfo brokerInfo) { + throw new RuntimeException("Don't call me!"); + } + + protected final ActiveMQServer createServer(final boolean realFiles, + final boolean netty) throws Exception { + return createServer(realFiles, createDefaultConfig(netty), -1, -1, + new HashMap<String, AddressSettings>()); + } + + protected final ActiveMQServer createServer(final boolean realFiles, + final Configuration configuration, final int pageSize, + final int maxAddressSize, + final Map<String, AddressSettings> settings) { + return createServer(realFiles, configuration, pageSize, maxAddressSize, + AddressFullMessagePolicy.PAGE, settings); + } + + protected final ActiveMQServer createServer(final boolean realFiles, + final Configuration configuration, final int pageSize, + final int maxAddressSize, + final AddressFullMessagePolicy fullPolicy, + final Map<String, AddressSettings> settings) { + ActiveMQServer server = ActiveMQServers.newActiveMQServer(configuration, + realFiles); + if (settings != null) { + for (Map.Entry<String, AddressSettings> setting : settings + .entrySet()) { + server.getAddressSettingsRepository().addMatch( + setting.getKey(), setting.getValue()); + } + } + + AddressSettings defaultSetting = new AddressSettings(); + defaultSetting.setPageSizeBytes(pageSize); + defaultSetting.setMaxSizeBytes(maxAddressSize); + defaultSetting.setAddressFullMessagePolicy(fullPolicy); + + server.getAddressSettingsRepository().addMatch("#", defaultSetting); + + return server; + } + + protected Configuration createDefaultConfig(final boolean netty) + throws Exception { + if (netty) { + return createDefaultConfig(new HashMap<String, Object>(), + INVM_ACCEPTOR_FACTORY, NETTY_ACCEPTOR_FACTORY); + } else { + return createDefaultConfig(new HashMap<String, Object>(), + INVM_ACCEPTOR_FACTORY); + } + } + + protected Configuration createDefaultConfig( + final Map<String, Object> params, final String... acceptors) + throws Exception { + ConfigurationImpl configuration = createBasicConfig(-1) + .setJMXManagementEnabled(false) + .clearAcceptorConfigurations(); + + for (String acceptor : acceptors) { + TransportConfiguration transportConfig = new TransportConfiguration( + acceptor, params); + configuration.addAcceptorConfiguration(transportConfig); + } + + return configuration; + } + + protected final ConfigurationImpl createBasicConfig(final int serverID) { + ConfigurationImpl configuration = new ConfigurationImpl() + .setSecurityEnabled(false) + .setJournalMinFiles(2) + .setJournalFileSize(100 * 1024) + .setJournalType(getDefaultJournalType()) + .setJournalDirectory(getJournalDir(serverID, false)) + .setBindingsDirectory(getBindingsDir(serverID, false)) + .setPagingDirectory(getPageDir(serverID, false)) + .setLargeMessagesDirectory(getLargeMessagesDir(serverID, false)) + .setJournalCompactMinFiles(0).setJournalCompactPercentage(0) + .setClusterPassword(CLUSTER_PASSWORD); + + return configuration; + } + + protected String getLargeMessagesDir(final int index, final boolean backup) { + return getLargeMessagesDir(testDir, index, backup); + } + + protected static String getLargeMessagesDir(final String testDir, + final int index, final boolean backup) { + return getLargeMessagesDir(testDir) + + directoryNameSuffix(index, backup); + } + + protected String getPageDir(final int index, final boolean backup) { + return getPageDir(testDir, index, backup); + } + + protected static String getPageDir(final String testDir, final int index, + final boolean backup) { + return getPageDir(testDir) + directoryNameSuffix(index, backup); + } + + protected String getBindingsDir(final int index, final boolean backup) { + return getBindingsDir(testDir, index, backup); + } + + protected static String getBindingsDir(final String testDir, + final int index, final boolean backup) { + return getBindingsDir(testDir) + directoryNameSuffix(index, backup); + } + + protected String getJournalDir(final int index, final boolean backup) { + return getJournalDir(testDir, index, backup); + } + + protected static String getJournalDir(final String testDir, + final int index, final boolean backup) { + return getJournalDir(testDir) + directoryNameSuffix(index, backup); + } + + private static String directoryNameSuffix(int index, boolean backup) { + if (index == -1) + return ""; + return index + "-" + (backup ? "B" : "L"); + } + + protected static JournalType getDefaultJournalType() { + if (AsynchronousFileImpl.isLoaded()) { + return JournalType.ASYNCIO; + } else { + return JournalType.NIO; + } + } + + protected final void clearDataRecreateServerDirs() { + clearDataRecreateServerDirs(testDir); + } + + protected void clearDataRecreateServerDirs(final String testDir1) { + // Need to delete the root + + File file = new File(testDir1); + deleteDirectory(file); + file.mkdirs(); + + recreateDirectory(getJournalDir(testDir1)); + recreateDirectory(getBindingsDir(testDir1)); + recreateDirectory(getPageDir(testDir1)); + recreateDirectory(getLargeMessagesDir(testDir1)); + recreateDirectory(getClientLargeMessagesDir(testDir1)); + recreateDirectory(getTemporaryDir(testDir1)); + } + + protected String getTemporaryDir(final String testDir1) { + return testDir1 + "/temp"; + } + + protected String getClientLargeMessagesDir(final String testDir1) { + return testDir1 + "/client-large-msg"; + } + + protected static String getLargeMessagesDir(final String testDir1) { + return testDir1 + "/large-msg"; + } + + protected static String getPageDir(final String testDir1) { + return testDir1 + "/page"; + } + + protected static String getBindingsDir(final String testDir1) { + return testDir1 + "/bindings"; + } + + protected static String getJournalDir(final String testDir1) { + return testDir1 + "/journal"; + } + + protected static final void recreateDirectory(final String directory) { + File file = new File(directory); + deleteDirectory(file); + file.mkdirs(); + } + + protected static final boolean deleteDirectory(final File directory) { + if (directory.isDirectory()) { + String[] files = directory.list(); + int num = 5; + int attempts = 0; + while (files == null && (attempts < num)) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + files = directory.list(); + attempts++; + } + + for (String file : files) { + File f = new File(directory, file); + if (!deleteDirectory(f)) { + LOG.warn("Failed to clean up file: " + f.getAbsolutePath()); + } + } + } + + return directory.delete(); + } + +} http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerWrapper.java ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerWrapper.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerWrapper.java new file mode 100644 index 0000000..86580e1 --- /dev/null +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/ArtemisBrokerWrapper.java @@ -0,0 +1,209 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.activemq.broker.artemiswrapper; + +import java.net.URI; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.apache.activemq.artemis.api.core.ActiveMQQueueExistsException; +import org.apache.activemq.artemis.api.core.SimpleString; +import org.apache.activemq.artemis.api.core.TransportConfiguration; +import org.apache.activemq.artemis.core.config.Configuration; +import org.apache.activemq.artemis.core.config.impl.SecurityConfiguration; +import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; +import org.apache.activemq.artemis.core.security.Role; +import org.apache.activemq.artemis.core.settings.impl.AddressSettings; +import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManagerImpl; +import org.apache.activemq.artemiswrapper.ArtemisBrokerHelper; +import org.apache.activemq.broker.BrokerService; + +public class ArtemisBrokerWrapper extends ArtemisBrokerBase +{ + + protected Map<String, SimpleString> testQueues = new HashMap<String, SimpleString>(); + + public ArtemisBrokerWrapper(BrokerService brokerService) + { + this.bservice = brokerService; + } + + @Override + public void start() throws Exception + { + testDir = temporaryFolder.getRoot().getAbsolutePath(); + clearDataRecreateServerDirs(); + server = createServer(realStore, false); + HashMap<String, Object> params = new HashMap<String, Object>(); + params.put(TransportConstants.PORT_PROP_NAME, "61616"); + params.put(TransportConstants.PROTOCOLS_PROP_NAME, "OPENWIRE"); + TransportConfiguration transportConfiguration = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); + + Configuration serverConfig = server.getConfiguration(); + + Set<TransportConfiguration> acceptors0 = serverConfig.getAcceptorConfigurations(); + Iterator<TransportConfiguration> iter0 = acceptors0.iterator(); + + while (iter0.hasNext()) + { + System.out.println("===>: " + iter0.next()); + } + + Map<String, AddressSettings> addressSettings = serverConfig.getAddressesSettings(); + String match = "jms.queue.#"; + AddressSettings dlaSettings = new AddressSettings(); + SimpleString dla = new SimpleString("jms.queue.ActiveMQ.DLQ"); + dlaSettings.setDeadLetterAddress(dla); + addressSettings.put(match, dlaSettings); + + serverConfig.getAcceptorConfigurations().add(transportConfiguration); + if (this.bservice.enableSsl()) + { + params = new HashMap<String, Object>(); + params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); + params.put(TransportConstants.PORT_PROP_NAME, 61611); + params.put(TransportConstants.PROTOCOLS_PROP_NAME, "OPENWIRE"); + params.put(TransportConstants.KEYSTORE_PATH_PROP_NAME, bservice.SERVER_SIDE_KEYSTORE); + params.put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, bservice.KEYSTORE_PASSWORD); + params.put(TransportConstants.KEYSTORE_PROVIDER_PROP_NAME, bservice.storeType); + if (bservice.SERVER_SIDE_TRUSTSTORE != null) + { + params.put(TransportConstants.NEED_CLIENT_AUTH_PROP_NAME, true); + params.put(TransportConstants.TRUSTSTORE_PATH_PROP_NAME, bservice.SERVER_SIDE_TRUSTSTORE); + params.put(TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME, bservice.TRUSTSTORE_PASSWORD); + params.put(TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME, bservice.storeType); + } + TransportConfiguration sslTransportConfig = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); + serverConfig.getAcceptorConfigurations().add(sslTransportConfig); + } + + for (Integer port : bservice.extraConnectors) + { + if (port.intValue() != 61616) + { + //extra port + params = new HashMap<String, Object>(); + params.put(TransportConstants.PORT_PROP_NAME, port.intValue()); + params.put(TransportConstants.PROTOCOLS_PROP_NAME, "OPENWIRE"); + TransportConfiguration extraTransportConfiguration = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params); + serverConfig.getAcceptorConfigurations().add(extraTransportConfiguration); + } + } + + serverConfig.setSecurityEnabled(enableSecurity); + + //extraServerConfig(serverConfig); + + if (enableSecurity) + { + ActiveMQSecurityManagerImpl sm = (ActiveMQSecurityManagerImpl) server.getSecurityManager(); + SecurityConfiguration securityConfig = sm.getConfiguration(); + securityConfig.addRole("openwireSender", "sender"); + securityConfig.addUser("openwireSender", "SeNdEr"); + //sender cannot receive + Role senderRole = new Role("sender", true, false, false, false, true, true, false); + + securityConfig.addRole("openwireReceiver", "receiver"); + securityConfig.addUser("openwireReceiver", "ReCeIvEr"); + //receiver cannot send + Role receiverRole = new Role("receiver", false, true, false, false, true, true, false); + + securityConfig.addRole("openwireGuest", "guest"); + securityConfig.addUser("openwireGuest", "GuEsT"); + + //guest cannot do anything + Role guestRole = new Role("guest", false, false, false, false, false, false, false); + + securityConfig.addRole("openwireDestinationManager", "manager"); + securityConfig.addUser("openwireDestinationManager", "DeStInAtIoN"); + + //guest cannot do anything + Role destRole = new Role("manager", false, false, false, false, true, true, false); + + Map<String, Set<Role>> settings = server.getConfiguration().getSecurityRoles(); + if (settings == null) + { + settings = new HashMap<String, Set<Role>>(); + server.getConfiguration().setSecurityRoles(settings); + } + Set<Role> anySet = settings.get("#"); + if (anySet == null) + { + anySet = new HashSet<Role>(); + settings.put("#", anySet); + } + anySet.add(senderRole); + anySet.add(receiverRole); + anySet.add(guestRole); + anySet.add(destRole); + } +/* no need to start jms server here + jmsServer = new JMSServerManagerImpl(server); + jmsServer.setContext(new InVMNamingContext()); + jmsServer.start(); +*/ + Set<TransportConfiguration> acceptors = serverConfig.getAcceptorConfigurations(); + Iterator<TransportConfiguration> iter = acceptors.iterator(); + + while (iter.hasNext()) + { + System.out.println(">: " + iter.next()); + } + server.start(); + +/* + registerConnectionFactory(); + mbeanServer = MBeanServerFactory.createMBeanServer(); +*/ + + ArtemisBrokerHelper.setBroker(this.bservice); + stopped = false; + + } + + @Override + public void stop() throws Exception + { + server.stop(); + testQueues.clear(); + stopped = true; + } + + public void makeSureQueueExists(String qname) throws Exception + { + synchronized (testQueues) + { + SimpleString coreQ = testQueues.get(qname); + if (coreQ == null) + { + coreQ = new SimpleString("jms.queue." + qname); + try + { + this.server.createQueue(coreQ, coreQ, null, false, false); + testQueues.put(qname, coreQ); + } + catch (ActiveMQQueueExistsException e) + { + //ignore + } + } + } + } +} http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNameParser.java ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNameParser.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNameParser.java new file mode 100644 index 0000000..293cdb0 --- /dev/null +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNameParser.java @@ -0,0 +1,74 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.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.activemq.broker.artemiswrapper; + +import java.io.Serializable; +import java.util.Properties; + +import javax.naming.CompoundName; +import javax.naming.Name; +import javax.naming.NameParser; +import javax.naming.NamingException; + +/** + * @author <a href="mailto:[email protected]">Ovidiu Feodorov</a> + * @version <tt>$Revision: 2868 $</tt> + * + */ +public class InVMNameParser implements NameParser, Serializable +{ + // Constants ----------------------------------------------------- + + private static final long serialVersionUID = 2925203703371001031L; + + // Static -------------------------------------------------------- + + static Properties syntax; + + static + { + InVMNameParser.syntax = new Properties(); + InVMNameParser.syntax.put("jndi.syntax.direction", "left_to_right"); + InVMNameParser.syntax.put("jndi.syntax.ignorecase", "false"); + InVMNameParser.syntax.put("jndi.syntax.separator", "/"); + } + + // Attributes ---------------------------------------------------- + + // Constructors -------------------------------------------------- + + // Public -------------------------------------------------------- + + public static Properties getSyntax() + { + return InVMNameParser.syntax; + } + + public Name parse(final String name) throws NamingException + { + return new CompoundName(name, InVMNameParser.syntax); + } + + // Package protected --------------------------------------------- + + // Protected ----------------------------------------------------- + + // Private ------------------------------------------------------- + + // Inner classes ------------------------------------------------- + +} http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/60979268/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNamingContext.java ---------------------------------------------------------------------- diff --git a/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNamingContext.java b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNamingContext.java new file mode 100644 index 0000000..017fa17 --- /dev/null +++ b/tests/activemq5-unit-tests/src/main/java/org/apache/activemq/broker/artemiswrapper/InVMNamingContext.java @@ -0,0 +1,370 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.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.activemq.broker.artemiswrapper; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NameAlreadyBoundException; +import javax.naming.NameClassPair; +import javax.naming.NameNotFoundException; +import javax.naming.NameParser; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.RefAddr; +import javax.naming.Reference; + +public class InVMNamingContext implements Context, Serializable +{ + // Constants ----------------------------------------------------- + + private static final long serialVersionUID = 385743957345L; + + // Static -------------------------------------------------------- + + // Attributes ---------------------------------------------------- + + protected Map<String, Object> map; + + protected NameParser parser = new InVMNameParser(); + + private String nameInNamespace = ""; + + // Constructors -------------------------------------------------- + + public InVMNamingContext() + { + map = Collections.synchronizedMap(new HashMap<String, Object>()); + } + + public InVMNamingContext(final String nameInNamespace) + { + this(); + this.nameInNamespace = nameInNamespace; + } + + // Context implementation ---------------------------------------- + + public Object lookup(final Name name) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public Object lookup(String name) throws NamingException + { + name = trimSlashes(name); + int i = name.indexOf("/"); + String tok = i == -1 ? name : name.substring(0, i); + Object value = map.get(tok); + if (value == null) + { + throw new NameNotFoundException("Name not found: " + tok); + } + if (value instanceof InVMNamingContext && i != -1) + { + return ((InVMNamingContext)value).lookup(name.substring(i)); + } + if (value instanceof Reference) + { + Reference ref = (Reference)value; + RefAddr refAddr = ref.get("nns"); + + // we only deal with references create by NonSerializableFactory + String key = (String)refAddr.getContent(); + return NonSerializableFactory.lookup(key); + } + else + { + return value; + } + } + + public void bind(final Name name, final Object obj) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public void bind(final String name, final Object obj) throws NamingException + { + internalBind(name, obj, false); + } + + public void rebind(final Name name, final Object obj) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public void rebind(final String name, final Object obj) throws NamingException + { + internalBind(name, obj, true); + } + + public void unbind(final Name name) throws NamingException + { + unbind(name.toString()); + } + + public void unbind(String name) throws NamingException + { + name = trimSlashes(name); + int i = name.indexOf("/"); + boolean terminal = i == -1; + if (terminal) + { + map.remove(name); + } + else + { + String tok = name.substring(0, i); + InVMNamingContext c = (InVMNamingContext)map.get(tok); + if (c == null) + { + throw new NameNotFoundException("Context not found: " + tok); + } + c.unbind(name.substring(i)); + } + } + + public void rename(final Name oldName, final Name newName) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public void rename(final String oldName, final String newName) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public NamingEnumeration<NameClassPair> list(final Name name) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public NamingEnumeration<NameClassPair> list(final String name) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public NamingEnumeration<Binding> listBindings(final Name name) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public NamingEnumeration<Binding> listBindings(String contextName) throws NamingException + { + contextName = trimSlashes(contextName); + if (!"".equals(contextName) && !".".equals(contextName)) + { + try + { + return ((InVMNamingContext)lookup(contextName)).listBindings(""); + } + catch (Throwable t) + { + throw new NamingException(t.getMessage()); + } + } + + List<Binding> l = new ArrayList<Binding>(); + for (Object element : map.keySet()) + { + String name = (String)element; + Object object = map.get(name); + l.add(new Binding(name, object)); + } + return new NamingEnumerationImpl<Binding>(l.iterator()); + } + + public void destroySubcontext(final Name name) throws NamingException + { + destroySubcontext(name.toString()); + } + + public void destroySubcontext(final String name) throws NamingException + { + map.remove(trimSlashes(name)); + } + + public Context createSubcontext(final Name name) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public Context createSubcontext(String name) throws NamingException + { + name = trimSlashes(name); + if (map.get(name) != null) + { + throw new NameAlreadyBoundException(name); + } + InVMNamingContext c = new InVMNamingContext(getNameInNamespace()); + map.put(name, c); + return c; + } + + public Object lookupLink(final Name name) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public Object lookupLink(final String name) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public NameParser getNameParser(final Name name) throws NamingException + { + return getNameParser(name.toString()); + } + + public NameParser getNameParser(final String name) throws NamingException + { + return parser; + } + + public Name composeName(final Name name, final Name prefix) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public String composeName(final String name, final String prefix) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public Object addToEnvironment(final String propName, final Object propVal) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public Object removeFromEnvironment(final String propName) throws NamingException + { + throw new UnsupportedOperationException(); + } + + public Hashtable<String, String> getEnvironment() throws NamingException + { + Hashtable<String, String> env = new Hashtable<String, String>(); + env.put("java.naming.factory.initial", "org.apache.activemq.artemis.jms.tests.tools.container.InVMInitialContextFactory"); + return env; + } + + public void close() throws NamingException + { + } + + public String getNameInNamespace() throws NamingException + { + return nameInNamespace; + } + + // Public -------------------------------------------------------- + + // Package protected --------------------------------------------- + + // Protected ----------------------------------------------------- + + // Private ------------------------------------------------------- + + private String trimSlashes(String s) + { + int i = 0; + while (true) + { + if (i == s.length() || s.charAt(i) != '/') + { + break; + } + i++; + } + s = s.substring(i); + i = s.length() - 1; + while (true) + { + if (i == -1 || s.charAt(i) != '/') + { + break; + } + i--; + } + return s.substring(0, i + 1); + } + + private void internalBind(String name, final Object obj, final boolean rebind) throws NamingException + { + name = trimSlashes(name); + int i = name.lastIndexOf("/"); + InVMNamingContext c = this; + if (i != -1) + { + String path = name.substring(0, i); + c = (InVMNamingContext)lookup(path); + } + name = name.substring(i + 1); + if (!rebind && c.map.get(name) != null) + { + throw new NameAlreadyBoundException(name); + } + c.map.put(name, obj); + } + + // Inner classes ------------------------------------------------- + + private class NamingEnumerationImpl<T> implements NamingEnumeration<T> + { + private final Iterator<T> iterator; + + NamingEnumerationImpl(final Iterator<T> bindingIterator) + { + iterator = bindingIterator; + } + + public void close() throws NamingException + { + throw new UnsupportedOperationException(); + } + + public boolean hasMore() throws NamingException + { + return iterator.hasNext(); + } + + public T next() throws NamingException + { + return iterator.next(); + } + + public boolean hasMoreElements() + { + return iterator.hasNext(); + } + + public T nextElement() + { + return iterator.next(); + } + } +}
