You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by an...@apache.org on 2015/11/24 18:19:46 UTC
[01/12] tomee git commit: Overrides & format
Repository: tomee
Updated Branches:
refs/heads/tomee-1.7.3-prepare 029dd395f -> ba185f5e4
Overrides & format
Project: http://git-wip-us.apache.org/repos/asf/tomee/repo
Commit: http://git-wip-us.apache.org/repos/asf/tomee/commit/a9ca7de3
Tree: http://git-wip-us.apache.org/repos/asf/tomee/tree/a9ca7de3
Diff: http://git-wip-us.apache.org/repos/asf/tomee/diff/a9ca7de3
Branch: refs/heads/tomee-1.7.3-prepare
Commit: a9ca7de3316983811c6797e32c9739d5870a2729
Parents: cac067d
Author: AndyGee <an...@gmx.de>
Authored: Fri Nov 20 10:41:58 2015 +0100
Committer: AndyGee <an...@gmx.de>
Committed: Fri Nov 20 10:41:58 2015 +0100
----------------------------------------------------------------------
...impleTransactionSynchronizationRegistry.java | 9 +
...ansactionSynchronizationRegistryWrapper.java | 7 +
.../core/transaction/JtaTransactionPolicy.java | 11 +
.../superbiz/injection/secure/MovieTest.java | 26 +-
.../apache/tomee/RemoteTomEEEJBContainer.java | 322 +++++++++----------
5 files changed, 201 insertions(+), 174 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/tomee/blob/a9ca7de3/container/openejb-core/src/main/java/org/apache/openejb/core/SimpleTransactionSynchronizationRegistry.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/core/SimpleTransactionSynchronizationRegistry.java b/container/openejb-core/src/main/java/org/apache/openejb/core/SimpleTransactionSynchronizationRegistry.java
index 541684b..853e4cb 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/core/SimpleTransactionSynchronizationRegistry.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/core/SimpleTransactionSynchronizationRegistry.java
@@ -34,6 +34,7 @@ public class SimpleTransactionSynchronizationRegistry implements TransactionSync
this.transactionManager = transactionManager;
}
+ @Override
public Transaction getTransactionKey() {
try {
return transactionManager.getTransaction();
@@ -42,6 +43,7 @@ public class SimpleTransactionSynchronizationRegistry implements TransactionSync
}
}
+ @Override
public Object getResource(final Object key) {
final Transaction transaction = getActiveTransaction();
final Map<Object, Object> resources = transactionResources.get(transaction);
@@ -51,6 +53,7 @@ public class SimpleTransactionSynchronizationRegistry implements TransactionSync
return resources.get(key);
}
+ @Override
public void putResource(final Object key, final Object value) {
final Transaction transaction = getActiveTransaction();
@@ -69,6 +72,7 @@ public class SimpleTransactionSynchronizationRegistry implements TransactionSync
resources.put(key, value);
}
+ @Override
public int getTransactionStatus() {
try {
return transactionManager.getStatus();
@@ -77,6 +81,7 @@ public class SimpleTransactionSynchronizationRegistry implements TransactionSync
}
}
+ @Override
public void registerInterposedSynchronization(final Synchronization synchronization) {
if (synchronization == null) {
throw new NullPointerException("synchronization is null");
@@ -91,6 +96,7 @@ public class SimpleTransactionSynchronizationRegistry implements TransactionSync
}
+ @Override
public boolean getRollbackOnly() {
final Transaction transaction = getActiveTransaction();
try {
@@ -100,6 +106,7 @@ public class SimpleTransactionSynchronizationRegistry implements TransactionSync
}
}
+ @Override
public void setRollbackOnly() {
final Transaction transaction = getActiveTransaction();
try {
@@ -132,9 +139,11 @@ public class SimpleTransactionSynchronizationRegistry implements TransactionSync
this.transaction = transaction;
}
+ @Override
public void beforeCompletion() {
}
+ @Override
public void afterCompletion(final int i) {
transactionResources.remove(transaction);
}
http://git-wip-us.apache.org/repos/asf/tomee/blob/a9ca7de3/container/openejb-core/src/main/java/org/apache/openejb/core/TransactionSynchronizationRegistryWrapper.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/core/TransactionSynchronizationRegistryWrapper.java b/container/openejb-core/src/main/java/org/apache/openejb/core/TransactionSynchronizationRegistryWrapper.java
index c16b56f..ab448b2 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/core/TransactionSynchronizationRegistryWrapper.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/core/TransactionSynchronizationRegistryWrapper.java
@@ -44,30 +44,37 @@ public class TransactionSynchronizationRegistryWrapper implements TransactionSyn
return registry;
}
+ @Override
public Object getResource(final Object o) {
return getRegistry().getResource(o);
}
+ @Override
public boolean getRollbackOnly() {
return getRegistry().getRollbackOnly();
}
+ @Override
public Object getTransactionKey() {
return getRegistry().getTransactionKey();
}
+ @Override
public int getTransactionStatus() {
return getRegistry().getTransactionStatus();
}
+ @Override
public void putResource(final Object o, final Object o1) {
getRegistry().putResource(o, o1);
}
+ @Override
public void registerInterposedSynchronization(final Synchronization synchronization) {
getRegistry().registerInterposedSynchronization(synchronization);
}
+ @Override
public void setRollbackOnly() {
getRegistry().setRollbackOnly();
}
http://git-wip-us.apache.org/repos/asf/tomee/blob/a9ca7de3/container/openejb-core/src/main/java/org/apache/openejb/core/transaction/JtaTransactionPolicy.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/core/transaction/JtaTransactionPolicy.java b/container/openejb-core/src/main/java/org/apache/openejb/core/transaction/JtaTransactionPolicy.java
index 4755037..2609991 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/core/transaction/JtaTransactionPolicy.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/core/transaction/JtaTransactionPolicy.java
@@ -59,12 +59,14 @@ public abstract class JtaTransactionPolicy implements TransactionPolicy {
synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
}
+ @Override
public TransactionType getTransactionType() {
return transactionType;
}
public abstract Transaction getCurrentTransaction();
+ @Override
public boolean isTransactionActive() {
final Transaction trasaction = getCurrentTransaction();
if (trasaction == null) {
@@ -79,6 +81,7 @@ public abstract class JtaTransactionPolicy implements TransactionPolicy {
}
}
+ @Override
public boolean isRollbackOnly() {
final Transaction trasaction = getCurrentTransaction();
if (trasaction != null) {
@@ -93,6 +96,7 @@ public abstract class JtaTransactionPolicy implements TransactionPolicy {
}
}
+ @Override
public void setRollbackOnly() {
setRollbackOnly(null);
}
@@ -107,6 +111,7 @@ public abstract class JtaTransactionPolicy implements TransactionPolicy {
}
}
+ @Override
public Object getResource(final Object key) {
if (isTransactionActive()) {
return synchronizationRegistry.getResource(key);
@@ -118,6 +123,7 @@ public abstract class JtaTransactionPolicy implements TransactionPolicy {
return resources.get(key);
}
+ @Override
public void putResource(final Object key, final Object value) {
if (isTransactionActive()) {
synchronizationRegistry.putResource(key, value);
@@ -129,6 +135,7 @@ public abstract class JtaTransactionPolicy implements TransactionPolicy {
resources.put(key, value);
}
+ @Override
public Object removeResource(final Object key) {
if (isTransactionActive()) {
final Object value = synchronizationRegistry.getResource(key);
@@ -142,13 +149,16 @@ public abstract class JtaTransactionPolicy implements TransactionPolicy {
return resources.remove(key);
}
+ @Override
public void registerSynchronization(final TransactionSynchronization synchronization) {
if (isTransactionActive()) {
synchronizationRegistry.registerInterposedSynchronization(new Synchronization() {
+ @Override
public void beforeCompletion() {
synchronization.beforeCompletion();
}
+ @Override
public void afterCompletion(final int s) {
final TransactionSynchronization.Status status;
if (s == Status.STATUS_COMMITTED) {
@@ -185,6 +195,7 @@ public abstract class JtaTransactionPolicy implements TransactionPolicy {
}
}
+ @Override
public void enlistResource(final XAResource xaResource) throws SystemException {
final Transaction transaction = getCurrentTransaction();
if (transaction != null) {
http://git-wip-us.apache.org/repos/asf/tomee/blob/a9ca7de3/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java
----------------------------------------------------------------------
diff --git a/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java b/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java
index 0e3654b..e2d341c 100644
--- a/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java
+++ b/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java
@@ -38,8 +38,8 @@ public class MovieTest {
private EJBContainer container;
- private Context getContext(String user, String pass) throws NamingException {
- Properties p = new Properties();
+ private Context getContext(final String user, final String pass) throws NamingException {
+ final Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
p.setProperty("openejb.authentication.realmName", "ScriptLogin");
p.put(Context.SECURITY_PRINCIPAL, user);
@@ -53,7 +53,7 @@ public class MovieTest {
final ClassLoader ctxCl = Thread.currentThread().getContextClassLoader();
System.setProperty("openejb.ScriptLoginModule.scriptURI", ctxCl.getResource("loginscript.js").toExternalForm());
- Properties p = new Properties();
+ final Properties p = new Properties();
p.put("movieDatabase", "new://Resource?type=DataSource");
p.put("movieDatabase.JdbcDriver", "org.hsqldb.jdbcDriver");
p.put("movieDatabase.JdbcUrl", "jdbc:hsqldb:mem:moviedb");
@@ -76,10 +76,10 @@ public class MovieTest {
movies.addMovie(new Movie("Joel Coen", "Fargo", 1996));
movies.addMovie(new Movie("Joel Coen", "The Big Lebowski", 1998));
- List<Movie> list = movies.getMovies();
+ final List<Movie> list = movies.getMovies();
Assert.assertEquals("List.size()", 3, list.size());
- for (Movie movie : list) {
+ for (final Movie movie : list) {
movies.deleteMovie(movie);
}
@@ -98,14 +98,14 @@ public class MovieTest {
movies.addMovie(new Movie("Joel Coen", "Fargo", 1996));
movies.addMovie(new Movie("Joel Coen", "The Big Lebowski", 1998));
- List<Movie> list = movies.getMovies();
+ final List<Movie> list = movies.getMovies();
Assert.assertEquals("List.size()", 3, list.size());
- for (Movie movie : list) {
+ for (final Movie movie : list) {
try {
movies.deleteMovie(movie);
Assert.fail("Employees should not be allowed to delete");
- } catch (EJBAccessException e) {
+ } catch (final EJBAccessException e) {
// Good, Employees cannot delete things
}
}
@@ -122,21 +122,21 @@ public class MovieTest {
try {
movies.addMovie(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992));
Assert.fail("Unauthenticated users should not be able to add movies");
- } catch (EJBAccessException e) {
+ } catch (final EJBAccessException e) {
// Good, guests cannot add things
}
try {
movies.deleteMovie(null);
Assert.fail("Unauthenticated users should not be allowed to delete");
- } catch (EJBAccessException e) {
+ } catch (final EJBAccessException e) {
// Good, Unauthenticated users cannot delete things
}
try {
// Read access should be allowed
movies.getMovies();
- } catch (EJBAccessException e) {
+ } catch (final EJBAccessException e) {
Assert.fail("Read access should be allowed");
}
}
@@ -146,14 +146,14 @@ public class MovieTest {
try {
getContext("eddie", "panama");
Assert.fail("supposed to have a login failure here");
- } catch (javax.naming.AuthenticationException e) {
+ } catch (final javax.naming.AuthenticationException e) {
//expected
}
try {
getContext("jimmy", "foxylady");
Assert.fail("supposed to have a login failure here");
- } catch (javax.naming.AuthenticationException e) {
+ } catch (final javax.naming.AuthenticationException e) {
//expected
}
}
http://git-wip-us.apache.org/repos/asf/tomee/blob/a9ca7de3/tomee/apache-tomee/src/main/java/org/apache/tomee/RemoteTomEEEJBContainer.java
----------------------------------------------------------------------
diff --git a/tomee/apache-tomee/src/main/java/org/apache/tomee/RemoteTomEEEJBContainer.java b/tomee/apache-tomee/src/main/java/org/apache/tomee/RemoteTomEEEJBContainer.java
index 95b8a38..5d6c4b9 100644
--- a/tomee/apache-tomee/src/main/java/org/apache/tomee/RemoteTomEEEJBContainer.java
+++ b/tomee/apache-tomee/src/main/java/org/apache/tomee/RemoteTomEEEJBContainer.java
@@ -1,161 +1,161 @@
-/**
- * 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.tomee;
-
-import org.apache.geronimo.osgi.locator.ProviderLocator;
-import org.apache.openejb.OpenEJBException;
-import org.apache.openejb.assembler.Deployer;
-import org.apache.openejb.assembler.DeployerEjb;
-import org.apache.openejb.client.RemoteInitialContextFactory;
-import org.apache.openejb.config.RemoteServer;
-import org.apache.openejb.loader.IO;
-import org.apache.tomee.util.QuickServerXmlParser;
-
-import javax.ejb.EJBException;
-import javax.ejb.embeddable.EJBContainer;
-import javax.ejb.spi.EJBContainerProvider;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.validation.ValidationException;
-import java.io.File;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-public class RemoteTomEEEJBContainer extends EJBContainer {
- private static RemoteTomEEEJBContainer instance;
- private RemoteServer container;
- private InitialContext context;
-
- @Override
- public void close() {
- instance.container.destroy();
- instance.container = null;
- }
-
- @Override
- public Context getContext() {
- return context;
- }
-
- public static class Provider implements EJBContainerProvider {
- private static final List<String> CONTAINER_NAMES = Arrays.asList(RemoteTomEEEJBContainer.class.getName(), "tomee-remote", "remote-tomee");
-
- @Override
- public EJBContainer createEJBContainer(final Map<?, ?> properties) {
- final Object provider = properties.get(EJBContainer.PROVIDER);
- int ejbContainerProviders = 1;
- try {
- ejbContainerProviders = ProviderLocator.getServices(EJBContainerProvider.class.getName(), EJBContainer.class, Thread.currentThread().getContextClassLoader()).size();
- } catch (final Exception e) {
- // no-op
- }
-
- if ((provider == null && ejbContainerProviders > 1)
- || (!RemoteTomEEEJBContainer.class.equals(provider)
- && !CONTAINER_NAMES.contains(String.valueOf(provider)))) {
- return null;
- }
-
- if (instance != null) {
- return instance;
- }
-
- final Object modules = properties.get(EJBContainer.MODULES);
-
- System.getProperties().putAll(properties);
- final File home = new File(System.getProperty("openejb.home", "doesn't exist"));
- if (!home.exists()) {
- throw new IllegalArgumentException("You need to set openejb.home");
- }
-
- final QuickServerXmlParser parser = QuickServerXmlParser.parse(new File(home, "conf/server.xml"));
- final String remoteEjb = System.getProperty(Context.PROVIDER_URL, "http://" + parser.host() + ":" + parser.http() + "/tomee/ejb");
-
- try {
- instance = new RemoteTomEEEJBContainer();
- instance.container = new RemoteServer();
- instance.container.setPortStartup(Integer.parseInt(parser.http()));
-
- try {
- instance.container.start();
- } catch (final Exception e) {
- instance.container.destroy();
- throw e;
- }
-
- instance.context = new InitialContext(new Properties() {{
- setProperty(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
- setProperty(Context.PROVIDER_URL, remoteEjb);
- }});
-
- final Deployer deployer = Deployer.class.cast(instance.context.lookup("openejb/DeployerBusinessRemote"));
-
- if (modules instanceof File) {
- final File file = File.class.cast(modules);
- deployFile(deployer, file);
- } else if (modules instanceof String) {
- final String path = String.class.cast(modules);
- final File file = new File(path);
- deployFile(deployer, file);
- } else if (modules instanceof String[]) {
- for (final String path : (String[]) modules) {
- deployFile(deployer, new File(path));
- }
- } else if (modules instanceof File[]) {
- for (final File file : (File[]) modules) {
- deployFile(deployer, file);
- }
- } // else suppose already deployed
-
- return instance;
- } catch (final OpenEJBException e) {
- throw new EJBException(e);
- } catch (final MalformedURLException e) {
- throw new EJBException(e);
- } catch (final ValidationException ve) {
- throw ve;
- } catch (final Exception e) {
- if (e instanceof EJBException) {
- throw (EJBException) e;
- }
- throw new TomEERemoteEJBContainerException("initialization exception", e);
- }
- }
- }
-
- private static void deployFile(final Deployer deployer, final File file) throws IOException, OpenEJBException {
- if ("true".equalsIgnoreCase(System.getProperty(DeployerEjb.OPENEJB_USE_BINARIES, "false"))) {
- final Properties props = new Properties();
- final byte[] slurpBinaries = IO.slurp(file).getBytes();
- props.put(DeployerEjb.OPENEJB_VALUE_BINARIES, slurpBinaries);
- props.put(DeployerEjb.OPENEJB_PATH_BINARIES, file.getName());
- deployer.deploy(file.getAbsolutePath(), props);
- } else {
- deployer.deploy(file.getAbsolutePath());
- }
- }
-
- protected static class TomEERemoteEJBContainerException extends RuntimeException {
- protected TomEERemoteEJBContainerException(final String s, final Exception e) {
- super(s, e);
- }
- }
-}
+/**
+ * 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.tomee;
+
+import org.apache.geronimo.osgi.locator.ProviderLocator;
+import org.apache.openejb.OpenEJBException;
+import org.apache.openejb.assembler.Deployer;
+import org.apache.openejb.assembler.DeployerEjb;
+import org.apache.openejb.client.RemoteInitialContextFactory;
+import org.apache.openejb.config.RemoteServer;
+import org.apache.openejb.loader.IO;
+import org.apache.tomee.util.QuickServerXmlParser;
+
+import javax.ejb.EJBException;
+import javax.ejb.embeddable.EJBContainer;
+import javax.ejb.spi.EJBContainerProvider;
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.validation.ValidationException;
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+public class RemoteTomEEEJBContainer extends EJBContainer {
+ private static RemoteTomEEEJBContainer instance;
+ private RemoteServer container;
+ private InitialContext context;
+
+ @Override
+ public void close() {
+ instance.container.destroy();
+ instance.container = null;
+ }
+
+ @Override
+ public Context getContext() {
+ return context;
+ }
+
+ public static class Provider implements EJBContainerProvider {
+ private static final List<String> CONTAINER_NAMES = Arrays.asList(RemoteTomEEEJBContainer.class.getName(), "tomee-remote", "remote-tomee");
+
+ @Override
+ public EJBContainer createEJBContainer(final Map<?, ?> properties) {
+ final Object provider = properties.get(EJBContainer.PROVIDER);
+ int ejbContainerProviders = 1;
+ try {
+ ejbContainerProviders = ProviderLocator.getServices(EJBContainerProvider.class.getName(), EJBContainer.class, Thread.currentThread().getContextClassLoader()).size();
+ } catch (final Exception e) {
+ // no-op
+ }
+
+ if ((provider == null && ejbContainerProviders > 1)
+ || (!RemoteTomEEEJBContainer.class.equals(provider)
+ && !CONTAINER_NAMES.contains(String.valueOf(provider)))) {
+ return null;
+ }
+
+ if (instance != null) {
+ return instance;
+ }
+
+ final Object modules = properties.get(EJBContainer.MODULES);
+
+ System.getProperties().putAll(properties);
+ final File home = new File(System.getProperty("openejb.home", "doesn't exist"));
+ if (!home.exists()) {
+ throw new IllegalArgumentException("You need to set openejb.home");
+ }
+
+ final QuickServerXmlParser parser = QuickServerXmlParser.parse(new File(home, "conf/server.xml"));
+ final String remoteEjb = System.getProperty(Context.PROVIDER_URL, "http://" + parser.host() + ":" + parser.http() + "/tomee/ejb");
+
+ try {
+ instance = new RemoteTomEEEJBContainer();
+ instance.container = new RemoteServer();
+ instance.container.setPortStartup(Integer.parseInt(parser.http()));
+
+ try {
+ instance.container.start();
+ } catch (final Exception e) {
+ instance.container.destroy();
+ throw e;
+ }
+
+ instance.context = new InitialContext(new Properties() {{
+ setProperty(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
+ setProperty(Context.PROVIDER_URL, remoteEjb);
+ }});
+
+ final Deployer deployer = Deployer.class.cast(instance.context.lookup("openejb/DeployerBusinessRemote"));
+
+ if (modules instanceof File) {
+ final File file = File.class.cast(modules);
+ deployFile(deployer, file);
+ } else if (modules instanceof String) {
+ final String path = String.class.cast(modules);
+ final File file = new File(path);
+ deployFile(deployer, file);
+ } else if (modules instanceof String[]) {
+ for (final String path : (String[]) modules) {
+ deployFile(deployer, new File(path));
+ }
+ } else if (modules instanceof File[]) {
+ for (final File file : (File[]) modules) {
+ deployFile(deployer, file);
+ }
+ } // else suppose already deployed
+
+ return instance;
+ } catch (final OpenEJBException e) {
+ throw new EJBException(e);
+ } catch (final MalformedURLException e) {
+ throw new EJBException(e);
+ } catch (final ValidationException ve) {
+ throw ve;
+ } catch (final Exception e) {
+ if (e instanceof EJBException) {
+ throw (EJBException) e;
+ }
+ throw new TomEERemoteEJBContainerException("initialization exception", e);
+ }
+ }
+ }
+
+ private static void deployFile(final Deployer deployer, final File file) throws IOException, OpenEJBException {
+ if ("true".equalsIgnoreCase(System.getProperty(DeployerEjb.OPENEJB_USE_BINARIES, "false"))) {
+ final Properties props = new Properties();
+ final byte[] slurpBinaries = IO.slurp(file).getBytes();
+ props.put(DeployerEjb.OPENEJB_VALUE_BINARIES, slurpBinaries);
+ props.put(DeployerEjb.OPENEJB_PATH_BINARIES, file.getName());
+ deployer.deploy(file.getAbsolutePath(), props);
+ } else {
+ deployer.deploy(file.getAbsolutePath());
+ }
+ }
+
+ protected static class TomEERemoteEJBContainerException extends RuntimeException {
+ protected TomEERemoteEJBContainerException(final String s, final Exception e) {
+ super(s, e);
+ }
+ }
+}
[07/12] tomee git commit: EOL
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/CxfRsHttpListener.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/CxfRsHttpListener.java b/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/CxfRsHttpListener.java
index bbdbbd5..0bdd6d9 100644
--- a/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/CxfRsHttpListener.java
+++ b/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/CxfRsHttpListener.java
@@ -1,1097 +1,1097 @@
-/*
- * 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.openejb.server.cxf.rs;
-
-import org.apache.cxf.BusException;
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.endpoint.Endpoint;
-import org.apache.cxf.endpoint.EndpointException;
-import org.apache.cxf.endpoint.ManagedEndpoint;
-import org.apache.cxf.endpoint.Server;
-import org.apache.cxf.endpoint.ServerImpl;
-import org.apache.cxf.helpers.IOUtils;
-import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
-import org.apache.cxf.jaxrs.JAXRSServiceImpl;
-import org.apache.cxf.jaxrs.ext.RequestHandler;
-import org.apache.cxf.jaxrs.ext.ResourceComparator;
-import org.apache.cxf.jaxrs.lifecycle.ResourceProvider;
-import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
-import org.apache.cxf.jaxrs.model.ClassResourceInfo;
-import org.apache.cxf.jaxrs.model.MethodDispatcher;
-import org.apache.cxf.jaxrs.model.OperationResourceInfo;
-import org.apache.cxf.jaxrs.model.ProviderInfo;
-import org.apache.cxf.jaxrs.model.wadl.WadlGenerator;
-import org.apache.cxf.jaxrs.provider.JAXBElementProvider;
-import org.apache.cxf.jaxrs.provider.json.JSONProvider;
-import org.apache.cxf.service.invoker.Invoker;
-import org.apache.cxf.transport.http.AbstractHTTPDestination;
-import org.apache.cxf.transport.http.HTTPTransportFactory;
-import org.apache.cxf.transport.servlet.BaseUrlHelper;
-import org.apache.openejb.AppContext;
-import org.apache.openejb.BeanContext;
-import org.apache.openejb.Injection;
-import org.apache.openejb.api.internal.Internal;
-import org.apache.openejb.api.jmx.Description;
-import org.apache.openejb.api.jmx.MBean;
-import org.apache.openejb.api.jmx.ManagedAttribute;
-import org.apache.openejb.api.jmx.ManagedOperation;
-import org.apache.openejb.assembler.classic.ServiceInfo;
-import org.apache.openejb.assembler.classic.util.ServiceConfiguration;
-import org.apache.openejb.assembler.classic.util.ServiceInfos;
-import org.apache.openejb.core.WebContext;
-import org.apache.openejb.dyni.DynamicSubclass;
-import org.apache.openejb.loader.IO;
-import org.apache.openejb.loader.SystemInstance;
-import org.apache.openejb.monitoring.LocalMBeanServer;
-import org.apache.openejb.monitoring.ObjectNameBuilder;
-import org.apache.openejb.rest.ThreadLocalContextManager;
-import org.apache.openejb.server.cxf.rs.event.ExtensionProviderRegistration;
-import org.apache.openejb.server.cxf.rs.event.ServerCreated;
-import org.apache.openejb.server.cxf.rs.event.ServerDestroyed;
-import org.apache.openejb.server.cxf.transport.util.CxfUtil;
-import org.apache.openejb.server.httpd.HttpRequest;
-import org.apache.openejb.server.httpd.HttpRequestImpl;
-import org.apache.openejb.server.httpd.HttpResponse;
-import org.apache.openejb.server.httpd.ServletRequestAdapter;
-import org.apache.openejb.server.rest.EJBRestServiceInfo;
-import org.apache.openejb.server.rest.InternalApplication;
-import org.apache.openejb.server.rest.RsHttpListener;
-import org.apache.openejb.util.AppFinder;
-import org.apache.openejb.util.LogCategory;
-import org.apache.openejb.util.Logger;
-import org.apache.openejb.util.proxy.ProxyEJB;
-import org.apache.webbeans.config.WebBeansContext;
-import org.apache.webbeans.container.BeanManagerImpl;
-import org.apache.webbeans.context.creational.CreationalContextImpl;
-
-import javax.enterprise.context.spi.CreationalContext;
-import javax.enterprise.inject.spi.Bean;
-import javax.management.ObjectName;
-import javax.management.openmbean.TabularData;
-import javax.naming.Context;
-import javax.servlet.ServletException;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.Application;
-import javax.xml.bind.Marshaller;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Constructor;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.logging.Level;
-import java.util.regex.Pattern;
-
-import static org.apache.openejb.loader.JarLocation.jarLocation;
-
-public class CxfRsHttpListener implements RsHttpListener {
-
- private static final Logger LOGGER = Logger.getInstance(LogCategory.OPENEJB_RS, CxfRsHttpListener.class);
-
- private static final java.util.logging.Logger SERVER_IMPL_LOGGER = LogUtils.getL7dLogger(ServerImpl.class);
-
- public static final String CXF_JAXRS_PREFIX = "cxf.jaxrs.";
- public static final String PROVIDERS_KEY = CXF_JAXRS_PREFIX + "providers";
- public static final String STATIC_RESOURCE_KEY = CXF_JAXRS_PREFIX + "static-resources-list";
- public static final String STATIC_SUB_RESOURCE_RESOLUTION_KEY = "staticSubresourceResolution";
- public static final String RESOURCE_COMPARATOR_KEY = CXF_JAXRS_PREFIX + "resourceComparator";
-
- public static final boolean TRY_STATIC_RESOURCES = "true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.jaxrs.static-first", "true"));
- private static final String GLOBAL_PROVIDERS = SystemInstance.get().getProperty(PROVIDERS_KEY);
-
- private static final Map<String, String> STATIC_CONTENT_TYPES;
- private static final String[] DEFAULT_WELCOME_FILES = new String[]{ "/index.html", "/index.htm" };
-
- private final HTTPTransportFactory transportFactory;
- private final String wildcard;
- private AbstractHTTPDestination destination;
- private Server server;
- private String context = "";
- private String servlet = "";
- private final Collection<Pattern> staticResourcesList = new CopyOnWriteArrayList<Pattern>();
- private final List<ObjectName> jmxNames = new ArrayList<ObjectName>();
- private final Collection<CreationalContext<?>> toRelease = new LinkedHashSet<CreationalContext<?>>();
- private final Collection<CdiSingletonResourceProvider> singletons = new LinkedHashSet<CdiSingletonResourceProvider>();
-
- private static final char[] URL_SEP = new char[] { '?', '#', ';' };
-
- static {
- STATIC_CONTENT_TYPES = new HashMap<String, String>();
- STATIC_CONTENT_TYPES.put("html", "text/html");
- STATIC_CONTENT_TYPES.put("xhtml", "text/html");
- STATIC_CONTENT_TYPES.put("txt", "text/plain");
- STATIC_CONTENT_TYPES.put("css", "text/css");
- STATIC_CONTENT_TYPES.put("jpg", "image/jpg");
- STATIC_CONTENT_TYPES.put("png", "image/png");
- STATIC_CONTENT_TYPES.put("ico", "image/ico");
- STATIC_CONTENT_TYPES.put("pdf", "application/pdf");
- STATIC_CONTENT_TYPES.put("xsd", "application/xml");
-
- for (final ProviderInfo<RequestHandler> rh : org.apache.cxf.jaxrs.provider.ProviderFactory.getSharedInstance().getRequestHandlers()) {
- final RequestHandler provider = rh.getProvider();
- if (WadlGenerator.class.isInstance(provider)) {
- final WadlGenerator wadlGenerator = WadlGenerator.class.cast(provider);
- final String ignoreRequests = SystemInstance.get().getProperty("openejb.cxf-rs.wadl-generator.ignoreRequests");
- final String ignoreMessageWriters = SystemInstance.get().getProperty("openejb.cxf-rs.wadl-generator.ignoreMessageWriters", "false");
-
- if (ignoreRequests != null) {
- wadlGenerator.setIgnoreRequests(Boolean.parseBoolean(ignoreRequests));
- }
- // CXF-5319: bug in CXF? it prevents to get the wadl as json otherwise
- if (ignoreMessageWriters != null) {
- wadlGenerator.setIgnoreMessageWriters(Boolean.parseBoolean(ignoreMessageWriters));
- }
- }
- }
- }
-
- private String pattern;
-
- public CxfRsHttpListener(final HTTPTransportFactory httpTransportFactory, final String star) {
- transportFactory = httpTransportFactory;
- wildcard = star;
- }
-
- public void setUrlPattern(final String pattern) {
- this.pattern = pattern;
- }
-
- @Override
- public void onMessage(final HttpRequest httpRequest, final HttpResponse httpResponse) throws Exception {
- // fix the address (to manage multiple connectors)
- if (HttpRequestImpl.class.isInstance(httpRequest)) {
- final HttpRequestImpl requestImpl = HttpRequestImpl.class.cast(httpRequest);
- requestImpl.initPathFromContext(context);
- requestImpl.initServletPath(servlet);
- }
-
- boolean matchedStatic = false;
- if (TRY_STATIC_RESOURCES || (matchedStatic = matchPath(httpRequest))) {
- final String pathInfo = httpRequest.getPathInfo();
- if (serveStaticContent(httpRequest, httpResponse, pathInfo)) {
- if (matchedStatic) { // we should have gotten the resource
- throw new ServletException("Static resource " + pathInfo + " is not available");
- }
- return; // ok that's a surely rest service
- }
- }
-
- doInvoke(httpRequest, httpResponse);
- }
-
- // normal endpoint without static resource handling
- public void doInvoke(final HttpRequest httpRequest, final HttpResponse httpResponse) throws IOException {
- String baseURL = BaseUrlHelper.getBaseURL(pattern != null ? new ServletRequestAdapter(httpRequest) {
- @Override // we have a filter so we need the computed servlet path to not break CXF
- public String getServletPath() {
- return pattern;
- }
- } : httpRequest);
- if (!baseURL.endsWith("/")) {
- baseURL += "/";
- }
- httpRequest.setAttribute("org.apache.cxf.transport.endpoint.address", baseURL);
-
- final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
- try {
- destination.invoke(null, httpRequest.getServletContext(), httpRequest, httpResponse);
- } catch (final Throwable t) {
- throw new IOException("Failed to invoke AbstractHTTPDestination", t);
- } finally {
- CxfUtil.clearBusLoader(oldLoader);
- }
- }
-
- public boolean matchPath(final HttpServletRequest request) {
- if (staticResourcesList.isEmpty()) {
- return false;
- }
-
- String path = request.getPathInfo();
- if (path == null) {
- path = "/";
- }
- for (final Pattern pattern : staticResourcesList) {
- if (pattern.matcher(path).matches()) {
- return true;
- }
- }
- return false;
- }
-
- public InputStream findStaticContent(final HttpServletRequest request, final String[] welcomeFiles) throws ServletException {
- String pathInfo = request.getRequestURI().substring(request.getContextPath().length());
- for (final char c : URL_SEP) {
- final int indexOf = pathInfo.indexOf(c);
- if (indexOf > 0) {
- pathInfo = pathInfo.substring(0, indexOf);
- }
- }
- InputStream is = request.getServletContext().getResourceAsStream(pathInfo);
- if (is == null && ("/".equals(pathInfo) || pathInfo.isEmpty())) {
- for (final String n : welcomeFiles) {
- is = request.getServletContext().getResourceAsStream(n);
- if (is != null) {
- break;
- }
- }
- }
- return is;
- }
-
- public boolean serveStaticContent(final HttpServletRequest request,
- final HttpServletResponse response,
- final String pathInfo) throws ServletException {
- final InputStream is = findStaticContent(request, DEFAULT_WELCOME_FILES);
- if (is == null) {
- return false;
- }
- try {
- final int ind = pathInfo.lastIndexOf(".");
- if (ind != -1 && ind < pathInfo.length()) {
- final String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1));
- if (type != null) {
- response.setContentType(type);
- }
- }
-
- final ServletOutputStream os = response.getOutputStream();
- IOUtils.copy(is, os);
- os.flush();
- response.setStatus(HttpURLConnection.HTTP_OK);
- } catch (final IOException ex) {
- throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream");
- }
- return true;
- }
-
- @Deprecated
- @Override
- public void deploySingleton(final String contextRoot, final String fullContext, final Object o, final Application appInstance,
- final Collection<Object> additionalProviders, final ServiceConfiguration configuration) {
- deploy(contextRoot, o.getClass(), fullContext, new SingletonResourceProvider(o),
- o, appInstance, null, additionalProviders, configuration, null);
- }
-
- @Deprecated
- @Override
- public void deployPojo(final ClassLoader loader,
- final String contextRoot,
- final String fullContext,
- final Class<?> loadedClazz,
- final Application app,
- final Collection<Injection> injections,
- final Context context,
- final WebBeansContext owbCtx,
- final Collection<Object> additionalProviders,
- final ServiceConfiguration configuration) {
- deploy(contextRoot, loadedClazz, fullContext, new OpenEJBPerRequestPojoResourceProvider(loader, loadedClazz, injections, context, owbCtx),
- null, app, null, additionalProviders, configuration, null);
- }
-
- @Deprecated
- @Override
- public void deployEJB(final String contextRoot,
- final String fullContext,
- final BeanContext beanContext,
- final Collection<Object> additionalProviders,
- final ServiceConfiguration configuration) {
- final Object proxy = ProxyEJB.subclassProxy(beanContext);
-
- deploy(contextRoot, beanContext.getBeanClass(), fullContext, new NoopResourceProvider(beanContext.getBeanClass(), proxy),
- proxy, null, new OpenEJBEJBInvoker(Collections.singleton(beanContext)), additionalProviders, configuration, beanContext.getWebBeansContext());
- }
-
- private void deploy(final String contextRoot, final Class<?> clazz, final String address, final ResourceProvider rp, final Object serviceBean,
- final Application app, final Invoker invoker, final Collection<Object> additionalProviders, final ServiceConfiguration configuration,
- final WebBeansContext webBeansContext) {
- final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
- try {
- final JAXRSServerFactoryBean factory = newFactory(address, createServiceJmxName(clazz.getClassLoader()), createEndpointName(app));
- configureFactory(additionalProviders, configuration, factory, webBeansContext);
- factory.setResourceClasses(clazz);
- context = contextRoot;
- if (context == null) {
- context = "";
- }
- if (!context.startsWith("/")) {
- context = "/" + context;
- }
-
- if (rp != null) {
- factory.setResourceProvider(rp);
- }
- if (app != null) {
- factory.setApplication(app);
- }
- if (invoker != null) {
- factory.setInvoker(invoker);
- }
- if (serviceBean != null) {
- factory.setServiceBean(serviceBean);
- } else {
- factory.setServiceClass(clazz);
- }
-
- server = factory.create();
- destination = (AbstractHTTPDestination) server.getDestination();
- fireServerCreated(oldLoader);
- } finally {
- if (oldLoader != null) {
- CxfUtil.clearBusLoader(oldLoader);
- }
- }
- }
-
- private void fireServerCreated(final ClassLoader oldLoader) {
- final Object ctx = AppFinder.findAppContextOrWeb(oldLoader, new AppFinder.Transformer<Object>() {
- @Override
- public Object from(final AppContext appCtx) {
- return appCtx;
- }
-
- @Override
- public Object from(final WebContext webCtx) {
- return webCtx;
- }
- });
- final AppContext appCtx = AppContext.class.isInstance(ctx) ? AppContext.class.cast(ctx) : WebContext.class.cast(ctx).getAppContext();
- WebContext webContext = appCtx == ctx ? null : WebContext.class.cast(ctx);
- if (webContext == null && appCtx.getWebContexts().size() == 1 && appCtx.getWebContexts().get(0).getClassLoader() == oldLoader) {
- webContext = appCtx.getWebContexts().get(0);
- }
- SystemInstance.get().fireEvent(new ServerCreated(server, appCtx, webContext, this.context));
- }
-
- private List<Object> providers(final Collection<ServiceInfo> services, final Collection<Object> additionalProviders, final WebBeansContext ctx) {
- final List<Object> instances = new ArrayList<Object>();
- final BeanManagerImpl bm = ctx == null ? null : ctx.getBeanManagerImpl();
- for (final Object o : additionalProviders) {
- if (o instanceof Class<?>) {
- final Class<?> clazz = (Class<?>) o;
- final String name = clazz.getName();
- if (shouldSkipProvider(name)) {
- continue;
- }
-
- if (bm != null && bm.isInUse()) {
- try {
- final Set<Bean<?>> beans = bm.getBeans(clazz);
- if (beans != null && !beans.isEmpty()) {
- final Bean<?> bean = bm.resolve(beans);
- final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
- instances.add(bm.getReference(bean, clazz, creationalContext));
- toRelease.add(creationalContext);
- continue;
- }
- } catch (final Throwable th) {
- LOGGER.info("Can't use CDI to create provider " + name);
- }
- }
-
- final Collection<Object> instance = ServiceInfos.resolve(services, new String[]{name}, ProviderFactory.INSTANCE);
- if (instance != null && !instance.isEmpty()) {
- instances.add(instance.iterator().next());
- } else {
- try {
- instances.add(newProvider(clazz));
- } catch (final Exception e) {
- LOGGER.error("can't instantiate " + name, e);
- }
- }
- } else {
- final String name = o.getClass().getName();
- if (shouldSkipProvider(name)) {
- continue;
- }
- instances.add(o);
- }
- }
-
- return instances;
- }
-
- private static boolean shouldSkipProvider(final String name) {
- return "false".equalsIgnoreCase(SystemInstance.get().getProperty(name + ".activated", "true"))
- || name.startsWith("org.apache.wink.common.internal.");
- }
-
- private static void addMandatoryProviders(final Collection<Object> instances) {
- instances.add(EJBAccessExceptionMapper.INSTANCE);
- }
-
- private Object newProvider(final Class<?> clazz) throws IllegalAccessException, InstantiationException {
- return clazz.newInstance();
- }
-
- @Override
- public void undeploy() {
- // unregister all MBeans
- for (final ObjectName objectName : jmxNames) {
- LocalMBeanServer.unregisterSilently(objectName);
- }
-
- for (final CreationalContext<?> cc : toRelease) {
- try {
- cc.release();
- } catch (final Exception e) {
- LOGGER.warning(e.getMessage(), e);
- }
- }
- for (final CdiSingletonResourceProvider provider : singletons) {
- try {
- provider.release();
- } catch (final Exception e) {
- LOGGER.warning(e.getMessage(), e);
- }
- }
-
- final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
- try {
- server.destroy();
- SystemInstance.get().fireEvent(new ServerDestroyed(server));
- } catch (final RuntimeException ise) {
- LOGGER.warning("Can't stop correctly the endpoint " + server);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(ise.getMessage(), ise);
- }
- } finally {
- if (oldLoader != null) {
- CxfUtil.clearBusLoader(oldLoader);
- }
- }
- }
-
- @Override
- public void deployApplication(final Application application, final String prefix, final String webContext,
- final Collection<Object> additionalProviders,
- final Map<String, EJBRestServiceInfo> restEjbs, final ClassLoader classLoader,
- final Collection<Injection> injections, final Context context, final WebBeansContext owbCtx,
- final ServiceConfiguration serviceConfiguration) {
- final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
- try {
- final JAXRSServerFactoryBean factory = newFactory(prefix, createServiceJmxName(classLoader), createEndpointName(application));
- configureFactory(additionalProviders, serviceConfiguration, factory, owbCtx);
- factory.setApplication(application);
-
- final List<Class<?>> classes = new ArrayList<Class<?>>();
-
- for (final Class<?> clazz : application.getClasses()) {
- if (!additionalProviders.contains(clazz) && !clazz.isInterface()) {
- classes.add(clazz);
-
- final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
-
- if (restServiceInfo != null) {
- final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
- factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
- } else {
- factory.setResourceProvider(clazz, new OpenEJBPerRequestPojoResourceProvider(
- classLoader, clazz, injections, context, owbCtx));
- }
- }
- }
-
- for (final Object o : application.getSingletons()) {
- if (!additionalProviders.contains(o)) {
- final Class<?> clazz = realClass(o.getClass());
- classes.add(clazz);
-
- final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
-
- if (restServiceInfo != null) {
- final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
- factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
- } else {
- if (owbCtx.getBeanManagerImpl().isInUse()) {
- final CdiSingletonResourceProvider provider = new CdiSingletonResourceProvider(classLoader, clazz, o, injections, context, owbCtx);
- singletons.add(provider);
- factory.setResourceProvider(clazz, provider);
- } else {
- factory.setResourceProvider(clazz, new SingletonResourceProvider(o));
- }
- }
- }
- }
-
- factory.setResourceClasses(classes);
- factory.setInvoker(new AutoJAXRSInvoker(restEjbs));
-
- this.context = webContext;
- if (!webContext.startsWith("/")) {
- this.context = "/" + webContext;
- } // /webcontext/servlet for event firing
-
- final Level level = SERVER_IMPL_LOGGER.getLevel();
- try {
- SERVER_IMPL_LOGGER.setLevel(Level.OFF);
- } catch (final UnsupportedOperationException e) {
- //ignore
- }
- try {
- server = factory.create();
- fireServerCreated(oldLoader);
- } finally {
- try {
- SERVER_IMPL_LOGGER.setLevel(level);
- } catch (final UnsupportedOperationException e) {
- //ignore
- }
- }
-
- final int servletIdx = 1 + this.context.substring(1).indexOf('/');
- if (servletIdx > 0) {
- this.servlet = this.context.substring(servletIdx);
- this.context = this.context.substring(0, servletIdx);
- }
- destination = (AbstractHTTPDestination) server.getDestination();
-
- final String base;
- if (prefix.endsWith("/")) {
- base = prefix.substring(0, prefix.length() - 1);
- } else if (prefix.endsWith(wildcard)) {
- base = prefix.substring(0, prefix.length() - wildcard.length());
- } else {
- base = prefix;
- }
-
- // stack info to log to get nice logs
- logEndpoints(application, prefix, restEjbs, factory, base);
- } finally {
- if (oldLoader != null) {
- CxfUtil.clearBusLoader(oldLoader);
- }
- }
- }
-
- private EJBRestServiceInfo getEjbRestServiceInfo(final Map<String, EJBRestServiceInfo> restEjbs, final Class<?> clazz) {
- String name = clazz.getName();
- EJBRestServiceInfo restServiceInfo = restEjbs.get(name);
-
- if (name.endsWith(DynamicSubclass.IMPL_SUFFIX)) {
- name = name.substring(0, name.length() - DynamicSubclass.IMPL_SUFFIX.length());
- restServiceInfo = restEjbs.get(name);
- if (restServiceInfo != null) { // AutoJAXRSInvoker relies on it
- restEjbs.put(clazz.getName(), restServiceInfo);
- }
- }
- return restServiceInfo;
- }
-
- private static Class<?> realClass(final Class<?> aClass) {
- Class<?> result = aClass;
- while (result.getName().contains("$$")) {
- result = result.getSuperclass();
- if (result == null) {
- return aClass;
- }
- }
- return result;
- }
-
- private static String createEndpointName(final Application application) {
- if (application == null) {
- return "jaxrs-application";
- }
- if (InternalApplication.class.isInstance(application)) {
- final Application original = InternalApplication.class.cast(application).getOriginal();
- if (original != null) {
- return original.getClass().getSimpleName();
- }
- return "jaxrs-application";
- }
- return application.getClass().getSimpleName();
- }
-
- private static String createServiceJmxName(final ClassLoader classLoader) {
- final AppContext app = AppFinder.findAppContextOrWeb(classLoader, AppFinder.AppContextTransformer.INSTANCE);
- return app == null ? "application" : app.getId();
- }
-
- private void logEndpoints(final Application application, final String prefix,
- final Map<String, EJBRestServiceInfo> restEjbs,
- final JAXRSServerFactoryBean factory, final String base) {
- final List<Logs.LogResourceEndpointInfo> resourcesToLog = new ArrayList<Logs.LogResourceEndpointInfo>();
- int classSize = 0;
- int addressSize = 0;
-
- final JAXRSServiceImpl service = (JAXRSServiceImpl) factory.getServiceFactory().getService();
- final List<ClassResourceInfo> resources = service.getClassResourceInfos();
- for (final ClassResourceInfo info : resources) {
- if (info.getResourceClass() == null) { // possible?
- continue;
- }
-
- final String address = Logs.singleSlash(base, info.getURITemplate().getValue());
-
- final String clazz = info.getResourceClass().getName();
- final String type;
- if (restEjbs.containsKey(clazz)) {
- type = "EJB";
- } else {
- type = "Pojo";
- }
-
- classSize = Math.max(classSize, clazz.length());
- addressSize = Math.max(addressSize, address.length());
-
- int methodSize = 7;
- int methodStrSize = 0;
-
- final List<Logs.LogOperationEndpointInfo> toLog = new ArrayList<Logs.LogOperationEndpointInfo>();
-
- final MethodDispatcher md = info.getMethodDispatcher();
- for (final OperationResourceInfo ori : md.getOperationResourceInfos()) {
- final String httpMethod = ori.getHttpMethod();
- final String currentAddress = Logs.singleSlash(address, ori.getURITemplate().getValue());
- final String methodToStr = Logs.toSimpleString(ori.getMethodToInvoke());
- toLog.add(new Logs.LogOperationEndpointInfo(httpMethod, currentAddress, methodToStr));
-
- if (httpMethod != null) {
- methodSize = Math.max(methodSize, httpMethod.length());
- }
- addressSize = Math.max(addressSize, currentAddress.length());
- methodStrSize = Math.max(methodStrSize, methodToStr.length());
- }
-
- Collections.sort(toLog);
-
- resourcesToLog.add(new Logs.LogResourceEndpointInfo(type, address, clazz, toLog, methodSize, methodStrSize));
- }
-
- // effective logging
-
- LOGGER.info("REST Application: " + Logs.forceLength(prefix, addressSize, true) + " -> " + application.getClass().getName());
-
- Collections.sort(resourcesToLog);
-
- for (final Logs.LogResourceEndpointInfo resource : resourcesToLog) {
-
- // Init and register MBeans
- final ObjectNameBuilder jmxName = new ObjectNameBuilder("openejb.management")
- .set("j2eeType", "JAX-RS")
- .set("J2EEServer", "openejb")
- .set("J2EEApplication", base)
- .set("EndpointType", resource.type)
- .set("name", resource.classname);
-
- final ObjectName jmxObjectName = jmxName.build();
- LocalMBeanServer.registerDynamicWrapperSilently(
- new RestServiceMBean(resource),
- jmxObjectName);
-
- jmxNames.add(jmxObjectName);
-
- LOGGER.info(" Service URI: "
- + Logs.forceLength(resource.address, addressSize, true) + " -> "
- + Logs.forceLength(resource.type, 4, false) + " "
- + Logs.forceLength(resource.classname, classSize, true));
-
- for (final Logs.LogOperationEndpointInfo log : resource.operations) {
- LOGGER.info(" "
- + Logs.forceLength(log.http, resource.methodSize, false) + " "
- + Logs.forceLength(log.address, addressSize, true) + " -> "
- + Logs.forceLength(log.method, resource.methodStrSize, true));
- }
-
- resource.operations.clear();
- }
- resourcesToLog.clear();
- }
-
- private JAXRSServerFactoryBean newFactory(final String prefix, final String service, final String endpoint) {
- final JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean() {
- @Override
- protected Endpoint createEndpoint() throws BusException, EndpointException {
- final Endpoint created = super.createEndpoint();
- created.put(ManagedEndpoint.SERVICE_NAME, service);
- created.put(ManagedEndpoint.ENDPOINT_NAME, endpoint);
- return created;
- }
- };
- factory.setDestinationFactory(transportFactory);
- factory.setBus(CxfUtil.getBus());
- factory.setAddress(prefix);
- return factory;
- }
-
- private void configureFactory(final Collection<Object> givenAdditionalProviders,
- final ServiceConfiguration serviceConfiguration,
- final JAXRSServerFactoryBean factory,
- final WebBeansContext ctx) {
- CxfUtil.configureEndpoint(factory, serviceConfiguration, CXF_JAXRS_PREFIX);
-
- final Collection<ServiceInfo> services = serviceConfiguration.getAvailableServices();
-
- final String staticSubresourceResolution = serviceConfiguration.getProperties().getProperty(CXF_JAXRS_PREFIX + STATIC_SUB_RESOURCE_RESOLUTION_KEY);
- if (staticSubresourceResolution != null) {
- factory.setStaticSubresourceResolution("true".equalsIgnoreCase(staticSubresourceResolution));
- }
-
- // resource comparator
- final String resourceComparator = serviceConfiguration.getProperties().getProperty(RESOURCE_COMPARATOR_KEY);
- if (resourceComparator != null) {
- try {
- ResourceComparator instance = (ResourceComparator) ServiceInfos.resolve(services, resourceComparator);
- if (instance == null) {
- instance = (ResourceComparator) Thread.currentThread().getContextClassLoader()
- .loadClass(resourceComparator).newInstance();
- }
- factory.setResourceComparator(instance);
- } catch (final Exception e) {
- LOGGER.error("Can't create the resource comparator " + resourceComparator, e);
- }
- }
-
- // static resources
- final String staticResources = serviceConfiguration.getProperties().getProperty(STATIC_RESOURCE_KEY);
- if (staticResources != null) {
- final String[] resources = staticResources.split(",");
- for (final String r : resources) {
- final String trimmed = r.trim();
- if (!trimmed.isEmpty()) {
- staticResourcesList.add(Pattern.compile(trimmed));
- }
- }
- }
-
- // providers
- Set<String> providersConfig = null;
-
- {
- final String provider = serviceConfiguration.getProperties().getProperty(PROVIDERS_KEY);
- if (provider != null) { // already ordered and high priority since they were configured manually
- providersConfig = new HashSet<String>();
- for (final String p : Arrays.asList(provider.split(","))) {
- providersConfig.add(p.trim());
- }
- }
-
- {
- if (GLOBAL_PROVIDERS != null) { // same idea, Note: this doesn't affect much cases which are not embedded so don't spend time on it
- if (providersConfig == null) {
- providersConfig = new HashSet<String>();
- }
- providersConfig.addAll(Arrays.asList(GLOBAL_PROVIDERS.split(",")));
- }
- }
- }
-
- // another property to configure the scanning of providers but this one is consistent with current cxf config
- // the other one is more generic but need another file
- final String key = CXF_JAXRS_PREFIX + "skip-provider-scanning";
- final boolean ignoreAutoProviders = "true".equalsIgnoreCase(SystemInstance.get().getProperty(key, serviceConfiguration.getProperties().getProperty(key, "false")));
- final Collection<Object> additionalProviders = ignoreAutoProviders ? Collections.emptyList() : givenAdditionalProviders;
- List<Object> providers = null;
- if (providersConfig != null) {
- providers = ServiceInfos.resolve(services, providersConfig.toArray(new String[providersConfig.size()]), ProviderFactory.INSTANCE);
- if (providers != null && additionalProviders != null && !additionalProviders.isEmpty()) {
- providers.addAll(sortProviders(serviceConfiguration, ctx, additionalProviders));
- }
- }
- if (providers == null) {
- providers = new ArrayList<Object>(4);
- if (additionalProviders != null && !additionalProviders.isEmpty()) {
- providers.addAll(sortProviders(serviceConfiguration, ctx, additionalProviders));
- } else {
- providers.addAll(defaultProviders());
- }
- }
-
- if (!ignoreAutoProviders) {
- addMandatoryProviders(providers);
- }
-
- SystemInstance.get().fireEvent(new ExtensionProviderRegistration(
- AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.AppContextTransformer.INSTANCE), providers));
-
- LOGGER.info("Using providers:");
- for (final Object provider : providers) {
- LOGGER.info(" " + provider);
- }
- factory.setProviders(providers);
- }
-
- private List<Object> sortProviders(final ServiceConfiguration serviceConfiguration, final WebBeansContext ctx,
- final Collection<Object> additionalProviders) {
- final Collection<ServiceInfo> services = serviceConfiguration.getAvailableServices();
- final List<Object> loadedProviders = providers(services, additionalProviders, ctx);
- if ("true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.cxf.rs.skip-provider-sorting", "false"))) {
- return loadedProviders;
- }
-
- final String comparatorClass = serviceConfiguration.getProperties().getProperty(CXF_JAXRS_PREFIX + "provider-comparator");
-
- Comparator<Object> comparator = null;
- if (comparatorClass == null) {
- comparator = DefaultProviderComparator.INSTANCE;
- } else {
- final BeanManagerImpl bm = ctx.getBeanManagerImpl();
- if (bm != null && bm.isInUse()) {
- try {
- final Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(comparatorClass);
- final Set<Bean<?>> beans = bm.getBeans(clazz);
- if (beans != null && !beans.isEmpty()) {
- final Bean<?> bean = bm.resolve(beans);
- final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
- comparator = Comparator.class.cast(bm.getReference(bean, clazz, creationalContext));
- toRelease.add(creationalContext);
- }
- } catch (final Throwable th) {
- LOGGER.debug("Can't use CDI to load comparator " + comparatorClass);
- }
- }
-
- if (comparator == null) {
- comparator = Comparator.class.cast(ServiceInfos.resolve(services, comparatorClass));
- }
- if (comparator == null) {
- try {
- comparator = Comparator.class.cast(Thread.currentThread().getContextClassLoader().loadClass(comparatorClass).newInstance());
- } catch (final Exception e) {
- throw new IllegalArgumentException(e);
- }
- }
- }
- Collections.sort(loadedProviders, comparator);
- return loadedProviders;
- }
-
- private static List<Object> defaultProviders() {
- final JAXBElementProvider jaxb = new JAXBElementProvider();
- final Map<String, Object> jaxbProperties = new HashMap<String, Object>();
- jaxbProperties.put(Marshaller.JAXB_FRAGMENT, true);
- jaxb.setMarshallerProperties(jaxbProperties);
-
- final List<Object> providers = new ArrayList<Object>(4);
- providers.add(jaxb);
- providers.add(new JSONProvider());
- return providers;
- }
-
- // we use Object cause an app with a custom comparator can desire to compare instances
- private static final class DefaultProviderComparator implements Comparator<Object> {
- private static final DefaultProviderComparator INSTANCE = new DefaultProviderComparator();
- private static final ClassLoader SYSTEM_LOADER = ClassLoader.getSystemClassLoader();
-
- @Override
- public int compare(final Object o1, final Object o2) {
- if (o1 == o2 || (o1 != null && o1.equals(o2))) {
- return 0;
- }
- if (o1 == null) {
- return -1;
- }
- if (o2 == null) {
- return 1;
- }
-
- final Class<?> c1 = o1.getClass();
- final Class<?> c2 = o2.getClass();
-
- final ClassLoader classLoader1 = c1.getClassLoader();
- final ClassLoader classLoader2 = c2.getClassLoader();
-
- final boolean loadersNotNull = classLoader1 != null && classLoader2 != null;
-
- if (classLoader1 != classLoader2
- && loadersNotNull
- && !classLoader1.equals(classLoader2) && !classLoader2.equals(classLoader1)) {
- if (isParent(classLoader1, classLoader2)) {
- return 1;
- }
- if (isParent(classLoader2, classLoader1)) {
- return -1;
- }
- } else {
- final File l1 = jarLocation(c1);
- final File l2 = jarLocation(c2);
- if (l1 == null) {
- return 1;
- }
- if (l2 == null) {
- return -1;
- }
-
- try { // WEB-INF/classes will be before WEB-INF/lib automatically
- return l1.getCanonicalPath().compareTo(l2.getCanonicalPath());
- } catch (final IOException e) {
- // no-op: sort by class name
- }
- }
-
- return c1.getName().compareTo(c2.getName());
- }
-
- private static boolean isParent(final ClassLoader l1, final ClassLoader l2) {
- ClassLoader current = l2;
- while (current != null && current != SYSTEM_LOADER) {
- if (current.equals(l1) || l1.equals(current)) {
- return true;
- }
- current = current.getParent();
- }
- return false;
- }
- }
-
- private static class ProviderFactory implements ServiceInfos.Factory {
-
- private static final ServiceInfos.Factory INSTANCE = new ProviderFactory();
-
- @Override
- public Object newInstance(final Class<?> clazz) throws Exception {
- boolean found = false;
- Object instance = null;
- for (final Constructor<?> c : clazz.getConstructors()) {
- int contextAnnotations = 0;
- for (final Annotation[] annotations : c.getParameterAnnotations()) {
- for (final Annotation a : annotations) {
- if (javax.ws.rs.core.Context.class.equals(a.annotationType())) {
- contextAnnotations++;
- break;
- }
- }
- }
- if (contextAnnotations == c.getParameterTypes().length) {
- if (found) {
- LOGGER.warning("Found multiple matching constructor for " + clazz.getName());
- return instance;
- }
-
- final Object[] params = new Object[c.getParameterTypes().length];
- for (int i = 0; i < params.length; i++) {
- params[i] = ThreadLocalContextManager.findThreadLocal(c.getParameterTypes()[i]);
- // params[i] can be null if not a known type
- }
- instance = c.newInstance(params);
- found = true;
- }
- }
- if (instance != null) {
- return instance;
- }
- return clazz.newInstance();
- }
- }
-
- @SuppressWarnings("UnusedDeclaration")
- @MBean
- @Internal
- @Description("JAX-RS service information")
- public class RestServiceMBean {
-
- private final String type;
- private final String address;
- private final String classname;
- private final TabularData operations;
-
- public RestServiceMBean(final Logs.LogResourceEndpointInfo jmxName) {
- this.type = jmxName.type;
- this.address = jmxName.address;
- this.classname = jmxName.classname;
-
- final String[] names = new String[jmxName.operations.size()];
- final String[] values = new String[jmxName.operations.size()];
- int idx = 0;
- for (final Logs.LogOperationEndpointInfo operation : jmxName.operations) {
- names[idx] = operation.http + " " + operation.address;
- values[idx] = operation.method;
- idx++;
- }
- operations = LocalMBeanServer.tabularData("Operations", "Operations for this endpoint", names, values);
- }
-
- @ManagedAttribute
- @Description("The type of the REST service")
- public String getWadlUrl() {
- if (address.endsWith("?_wadl")) {
- return address;
- }
- return address + "?_wadl";
- }
-
- @ManagedOperation
- @Description("The type of the REST service")
- public String getWadl(final String format) {
- if (format != null && format.toLowerCase().contains("json")) {
- InputStream inputStream = null;
- try {
- final URL url = new URL(getWadlUrl() + "&_type=json");
- final HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection());
- connection.setRequestProperty("Accept", "application/json");
- connection.setRequestProperty("Content-type", "application/json");
- inputStream = connection.getInputStream();
- return IO.slurp(inputStream);
- } catch (final Exception e) {
- return e.getMessage();
- } finally {
- IO.close(inputStream);
- }
- } else { // xml
- try {
- return IO.slurp(new URL(getWadlUrl()));
- } catch (final IOException e) {
- return e.getMessage();
- }
- }
- }
-
- @ManagedAttribute
- @Description("The type of the REST service")
- public String getType() {
- return type;
- }
-
- @ManagedAttribute
- @Description("The REST service address")
- public String getAddress() {
- return address;
- }
-
- @ManagedAttribute
- @Description("The REST service class name")
- public String getClassname() {
- return classname;
- }
-
- @ManagedAttribute
- @Description("All available methods")
- public TabularData getOperations() {
- return operations;
- }
- }
-}
+/*
+ * 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.openejb.server.cxf.rs;
+
+import org.apache.cxf.BusException;
+import org.apache.cxf.common.logging.LogUtils;
+import org.apache.cxf.endpoint.Endpoint;
+import org.apache.cxf.endpoint.EndpointException;
+import org.apache.cxf.endpoint.ManagedEndpoint;
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.endpoint.ServerImpl;
+import org.apache.cxf.helpers.IOUtils;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.jaxrs.JAXRSServiceImpl;
+import org.apache.cxf.jaxrs.ext.RequestHandler;
+import org.apache.cxf.jaxrs.ext.ResourceComparator;
+import org.apache.cxf.jaxrs.lifecycle.ResourceProvider;
+import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.jaxrs.model.MethodDispatcher;
+import org.apache.cxf.jaxrs.model.OperationResourceInfo;
+import org.apache.cxf.jaxrs.model.ProviderInfo;
+import org.apache.cxf.jaxrs.model.wadl.WadlGenerator;
+import org.apache.cxf.jaxrs.provider.JAXBElementProvider;
+import org.apache.cxf.jaxrs.provider.json.JSONProvider;
+import org.apache.cxf.service.invoker.Invoker;
+import org.apache.cxf.transport.http.AbstractHTTPDestination;
+import org.apache.cxf.transport.http.HTTPTransportFactory;
+import org.apache.cxf.transport.servlet.BaseUrlHelper;
+import org.apache.openejb.AppContext;
+import org.apache.openejb.BeanContext;
+import org.apache.openejb.Injection;
+import org.apache.openejb.api.internal.Internal;
+import org.apache.openejb.api.jmx.Description;
+import org.apache.openejb.api.jmx.MBean;
+import org.apache.openejb.api.jmx.ManagedAttribute;
+import org.apache.openejb.api.jmx.ManagedOperation;
+import org.apache.openejb.assembler.classic.ServiceInfo;
+import org.apache.openejb.assembler.classic.util.ServiceConfiguration;
+import org.apache.openejb.assembler.classic.util.ServiceInfos;
+import org.apache.openejb.core.WebContext;
+import org.apache.openejb.dyni.DynamicSubclass;
+import org.apache.openejb.loader.IO;
+import org.apache.openejb.loader.SystemInstance;
+import org.apache.openejb.monitoring.LocalMBeanServer;
+import org.apache.openejb.monitoring.ObjectNameBuilder;
+import org.apache.openejb.rest.ThreadLocalContextManager;
+import org.apache.openejb.server.cxf.rs.event.ExtensionProviderRegistration;
+import org.apache.openejb.server.cxf.rs.event.ServerCreated;
+import org.apache.openejb.server.cxf.rs.event.ServerDestroyed;
+import org.apache.openejb.server.cxf.transport.util.CxfUtil;
+import org.apache.openejb.server.httpd.HttpRequest;
+import org.apache.openejb.server.httpd.HttpRequestImpl;
+import org.apache.openejb.server.httpd.HttpResponse;
+import org.apache.openejb.server.httpd.ServletRequestAdapter;
+import org.apache.openejb.server.rest.EJBRestServiceInfo;
+import org.apache.openejb.server.rest.InternalApplication;
+import org.apache.openejb.server.rest.RsHttpListener;
+import org.apache.openejb.util.AppFinder;
+import org.apache.openejb.util.LogCategory;
+import org.apache.openejb.util.Logger;
+import org.apache.openejb.util.proxy.ProxyEJB;
+import org.apache.webbeans.config.WebBeansContext;
+import org.apache.webbeans.container.BeanManagerImpl;
+import org.apache.webbeans.context.creational.CreationalContextImpl;
+
+import javax.enterprise.context.spi.CreationalContext;
+import javax.enterprise.inject.spi.Bean;
+import javax.management.ObjectName;
+import javax.management.openmbean.TabularData;
+import javax.naming.Context;
+import javax.servlet.ServletException;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.Application;
+import javax.xml.bind.Marshaller;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Constructor;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.logging.Level;
+import java.util.regex.Pattern;
+
+import static org.apache.openejb.loader.JarLocation.jarLocation;
+
+public class CxfRsHttpListener implements RsHttpListener {
+
+ private static final Logger LOGGER = Logger.getInstance(LogCategory.OPENEJB_RS, CxfRsHttpListener.class);
+
+ private static final java.util.logging.Logger SERVER_IMPL_LOGGER = LogUtils.getL7dLogger(ServerImpl.class);
+
+ public static final String CXF_JAXRS_PREFIX = "cxf.jaxrs.";
+ public static final String PROVIDERS_KEY = CXF_JAXRS_PREFIX + "providers";
+ public static final String STATIC_RESOURCE_KEY = CXF_JAXRS_PREFIX + "static-resources-list";
+ public static final String STATIC_SUB_RESOURCE_RESOLUTION_KEY = "staticSubresourceResolution";
+ public static final String RESOURCE_COMPARATOR_KEY = CXF_JAXRS_PREFIX + "resourceComparator";
+
+ public static final boolean TRY_STATIC_RESOURCES = "true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.jaxrs.static-first", "true"));
+ private static final String GLOBAL_PROVIDERS = SystemInstance.get().getProperty(PROVIDERS_KEY);
+
+ private static final Map<String, String> STATIC_CONTENT_TYPES;
+ private static final String[] DEFAULT_WELCOME_FILES = new String[]{ "/index.html", "/index.htm" };
+
+ private final HTTPTransportFactory transportFactory;
+ private final String wildcard;
+ private AbstractHTTPDestination destination;
+ private Server server;
+ private String context = "";
+ private String servlet = "";
+ private final Collection<Pattern> staticResourcesList = new CopyOnWriteArrayList<Pattern>();
+ private final List<ObjectName> jmxNames = new ArrayList<ObjectName>();
+ private final Collection<CreationalContext<?>> toRelease = new LinkedHashSet<CreationalContext<?>>();
+ private final Collection<CdiSingletonResourceProvider> singletons = new LinkedHashSet<CdiSingletonResourceProvider>();
+
+ private static final char[] URL_SEP = new char[] { '?', '#', ';' };
+
+ static {
+ STATIC_CONTENT_TYPES = new HashMap<String, String>();
+ STATIC_CONTENT_TYPES.put("html", "text/html");
+ STATIC_CONTENT_TYPES.put("xhtml", "text/html");
+ STATIC_CONTENT_TYPES.put("txt", "text/plain");
+ STATIC_CONTENT_TYPES.put("css", "text/css");
+ STATIC_CONTENT_TYPES.put("jpg", "image/jpg");
+ STATIC_CONTENT_TYPES.put("png", "image/png");
+ STATIC_CONTENT_TYPES.put("ico", "image/ico");
+ STATIC_CONTENT_TYPES.put("pdf", "application/pdf");
+ STATIC_CONTENT_TYPES.put("xsd", "application/xml");
+
+ for (final ProviderInfo<RequestHandler> rh : org.apache.cxf.jaxrs.provider.ProviderFactory.getSharedInstance().getRequestHandlers()) {
+ final RequestHandler provider = rh.getProvider();
+ if (WadlGenerator.class.isInstance(provider)) {
+ final WadlGenerator wadlGenerator = WadlGenerator.class.cast(provider);
+ final String ignoreRequests = SystemInstance.get().getProperty("openejb.cxf-rs.wadl-generator.ignoreRequests");
+ final String ignoreMessageWriters = SystemInstance.get().getProperty("openejb.cxf-rs.wadl-generator.ignoreMessageWriters", "false");
+
+ if (ignoreRequests != null) {
+ wadlGenerator.setIgnoreRequests(Boolean.parseBoolean(ignoreRequests));
+ }
+ // CXF-5319: bug in CXF? it prevents to get the wadl as json otherwise
+ if (ignoreMessageWriters != null) {
+ wadlGenerator.setIgnoreMessageWriters(Boolean.parseBoolean(ignoreMessageWriters));
+ }
+ }
+ }
+ }
+
+ private String pattern;
+
+ public CxfRsHttpListener(final HTTPTransportFactory httpTransportFactory, final String star) {
+ transportFactory = httpTransportFactory;
+ wildcard = star;
+ }
+
+ public void setUrlPattern(final String pattern) {
+ this.pattern = pattern;
+ }
+
+ @Override
+ public void onMessage(final HttpRequest httpRequest, final HttpResponse httpResponse) throws Exception {
+ // fix the address (to manage multiple connectors)
+ if (HttpRequestImpl.class.isInstance(httpRequest)) {
+ final HttpRequestImpl requestImpl = HttpRequestImpl.class.cast(httpRequest);
+ requestImpl.initPathFromContext(context);
+ requestImpl.initServletPath(servlet);
+ }
+
+ boolean matchedStatic = false;
+ if (TRY_STATIC_RESOURCES || (matchedStatic = matchPath(httpRequest))) {
+ final String pathInfo = httpRequest.getPathInfo();
+ if (serveStaticContent(httpRequest, httpResponse, pathInfo)) {
+ if (matchedStatic) { // we should have gotten the resource
+ throw new ServletException("Static resource " + pathInfo + " is not available");
+ }
+ return; // ok that's a surely rest service
+ }
+ }
+
+ doInvoke(httpRequest, httpResponse);
+ }
+
+ // normal endpoint without static resource handling
+ public void doInvoke(final HttpRequest httpRequest, final HttpResponse httpResponse) throws IOException {
+ String baseURL = BaseUrlHelper.getBaseURL(pattern != null ? new ServletRequestAdapter(httpRequest) {
+ @Override // we have a filter so we need the computed servlet path to not break CXF
+ public String getServletPath() {
+ return pattern;
+ }
+ } : httpRequest);
+ if (!baseURL.endsWith("/")) {
+ baseURL += "/";
+ }
+ httpRequest.setAttribute("org.apache.cxf.transport.endpoint.address", baseURL);
+
+ final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
+ try {
+ destination.invoke(null, httpRequest.getServletContext(), httpRequest, httpResponse);
+ } catch (final Throwable t) {
+ throw new IOException("Failed to invoke AbstractHTTPDestination", t);
+ } finally {
+ CxfUtil.clearBusLoader(oldLoader);
+ }
+ }
+
+ public boolean matchPath(final HttpServletRequest request) {
+ if (staticResourcesList.isEmpty()) {
+ return false;
+ }
+
+ String path = request.getPathInfo();
+ if (path == null) {
+ path = "/";
+ }
+ for (final Pattern pattern : staticResourcesList) {
+ if (pattern.matcher(path).matches()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public InputStream findStaticContent(final HttpServletRequest request, final String[] welcomeFiles) throws ServletException {
+ String pathInfo = request.getRequestURI().substring(request.getContextPath().length());
+ for (final char c : URL_SEP) {
+ final int indexOf = pathInfo.indexOf(c);
+ if (indexOf > 0) {
+ pathInfo = pathInfo.substring(0, indexOf);
+ }
+ }
+ InputStream is = request.getServletContext().getResourceAsStream(pathInfo);
+ if (is == null && ("/".equals(pathInfo) || pathInfo.isEmpty())) {
+ for (final String n : welcomeFiles) {
+ is = request.getServletContext().getResourceAsStream(n);
+ if (is != null) {
+ break;
+ }
+ }
+ }
+ return is;
+ }
+
+ public boolean serveStaticContent(final HttpServletRequest request,
+ final HttpServletResponse response,
+ final String pathInfo) throws ServletException {
+ final InputStream is = findStaticContent(request, DEFAULT_WELCOME_FILES);
+ if (is == null) {
+ return false;
+ }
+ try {
+ final int ind = pathInfo.lastIndexOf(".");
+ if (ind != -1 && ind < pathInfo.length()) {
+ final String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1));
+ if (type != null) {
+ response.setContentType(type);
+ }
+ }
+
+ final ServletOutputStream os = response.getOutputStream();
+ IOUtils.copy(is, os);
+ os.flush();
+ response.setStatus(HttpURLConnection.HTTP_OK);
+ } catch (final IOException ex) {
+ throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream");
+ }
+ return true;
+ }
+
+ @Deprecated
+ @Override
+ public void deploySingleton(final String contextRoot, final String fullContext, final Object o, final Application appInstance,
+ final Collection<Object> additionalProviders, final ServiceConfiguration configuration) {
+ deploy(contextRoot, o.getClass(), fullContext, new SingletonResourceProvider(o),
+ o, appInstance, null, additionalProviders, configuration, null);
+ }
+
+ @Deprecated
+ @Override
+ public void deployPojo(final ClassLoader loader,
+ final String contextRoot,
+ final String fullContext,
+ final Class<?> loadedClazz,
+ final Application app,
+ final Collection<Injection> injections,
+ final Context context,
+ final WebBeansContext owbCtx,
+ final Collection<Object> additionalProviders,
+ final ServiceConfiguration configuration) {
+ deploy(contextRoot, loadedClazz, fullContext, new OpenEJBPerRequestPojoResourceProvider(loader, loadedClazz, injections, context, owbCtx),
+ null, app, null, additionalProviders, configuration, null);
+ }
+
+ @Deprecated
+ @Override
+ public void deployEJB(final String contextRoot,
+ final String fullContext,
+ final BeanContext beanContext,
+ final Collection<Object> additionalProviders,
+ final ServiceConfiguration configuration) {
+ final Object proxy = ProxyEJB.subclassProxy(beanContext);
+
+ deploy(contextRoot, beanContext.getBeanClass(), fullContext, new NoopResourceProvider(beanContext.getBeanClass(), proxy),
+ proxy, null, new OpenEJBEJBInvoker(Collections.singleton(beanContext)), additionalProviders, configuration, beanContext.getWebBeansContext());
+ }
+
+ private void deploy(final String contextRoot, final Class<?> clazz, final String address, final ResourceProvider rp, final Object serviceBean,
+ final Application app, final Invoker invoker, final Collection<Object> additionalProviders, final ServiceConfiguration configuration,
+ final WebBeansContext webBeansContext) {
+ final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
+ try {
+ final JAXRSServerFactoryBean factory = newFactory(address, createServiceJmxName(clazz.getClassLoader()), createEndpointName(app));
+ configureFactory(additionalProviders, configuration, factory, webBeansContext);
+ factory.setResourceClasses(clazz);
+ context = contextRoot;
+ if (context == null) {
+ context = "";
+ }
+ if (!context.startsWith("/")) {
+ context = "/" + context;
+ }
+
+ if (rp != null) {
+ factory.setResourceProvider(rp);
+ }
+ if (app != null) {
+ factory.setApplication(app);
+ }
+ if (invoker != null) {
+ factory.setInvoker(invoker);
+ }
+ if (serviceBean != null) {
+ factory.setServiceBean(serviceBean);
+ } else {
+ factory.setServiceClass(clazz);
+ }
+
+ server = factory.create();
+ destination = (AbstractHTTPDestination) server.getDestination();
+ fireServerCreated(oldLoader);
+ } finally {
+ if (oldLoader != null) {
+ CxfUtil.clearBusLoader(oldLoader);
+ }
+ }
+ }
+
+ private void fireServerCreated(final ClassLoader oldLoader) {
+ final Object ctx = AppFinder.findAppContextOrWeb(oldLoader, new AppFinder.Transformer<Object>() {
+ @Override
+ public Object from(final AppContext appCtx) {
+ return appCtx;
+ }
+
+ @Override
+ public Object from(final WebContext webCtx) {
+ return webCtx;
+ }
+ });
+ final AppContext appCtx = AppContext.class.isInstance(ctx) ? AppContext.class.cast(ctx) : WebContext.class.cast(ctx).getAppContext();
+ WebContext webContext = appCtx == ctx ? null : WebContext.class.cast(ctx);
+ if (webContext == null && appCtx.getWebContexts().size() == 1 && appCtx.getWebContexts().get(0).getClassLoader() == oldLoader) {
+ webContext = appCtx.getWebContexts().get(0);
+ }
+ SystemInstance.get().fireEvent(new ServerCreated(server, appCtx, webContext, this.context));
+ }
+
+ private List<Object> providers(final Collection<ServiceInfo> services, final Collection<Object> additionalProviders, final WebBeansContext ctx) {
+ final List<Object> instances = new ArrayList<Object>();
+ final BeanManagerImpl bm = ctx == null ? null : ctx.getBeanManagerImpl();
+ for (final Object o : additionalProviders) {
+ if (o instanceof Class<?>) {
+ final Class<?> clazz = (Class<?>) o;
+ final String name = clazz.getName();
+ if (shouldSkipProvider(name)) {
+ continue;
+ }
+
+ if (bm != null && bm.isInUse()) {
+ try {
+ final Set<Bean<?>> beans = bm.getBeans(clazz);
+ if (beans != null && !beans.isEmpty()) {
+ final Bean<?> bean = bm.resolve(beans);
+ final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
+ instances.add(bm.getReference(bean, clazz, creationalContext));
+ toRelease.add(creationalContext);
+ continue;
+ }
+ } catch (final Throwable th) {
+ LOGGER.info("Can't use CDI to create provider " + name);
+ }
+ }
+
+ final Collection<Object> instance = ServiceInfos.resolve(services, new String[]{name}, ProviderFactory.INSTANCE);
+ if (instance != null && !instance.isEmpty()) {
+ instances.add(instance.iterator().next());
+ } else {
+ try {
+ instances.add(newProvider(clazz));
+ } catch (final Exception e) {
+ LOGGER.error("can't instantiate " + name, e);
+ }
+ }
+ } else {
+ final String name = o.getClass().getName();
+ if (shouldSkipProvider(name)) {
+ continue;
+ }
+ instances.add(o);
+ }
+ }
+
+ return instances;
+ }
+
+ private static boolean shouldSkipProvider(final String name) {
+ return "false".equalsIgnoreCase(SystemInstance.get().getProperty(name + ".activated", "true"))
+ || name.startsWith("org.apache.wink.common.internal.");
+ }
+
+ private static void addMandatoryProviders(final Collection<Object> instances) {
+ instances.add(EJBAccessExceptionMapper.INSTANCE);
+ }
+
+ private Object newProvider(final Class<?> clazz) throws IllegalAccessException, InstantiationException {
+ return clazz.newInstance();
+ }
+
+ @Override
+ public void undeploy() {
+ // unregister all MBeans
+ for (final ObjectName objectName : jmxNames) {
+ LocalMBeanServer.unregisterSilently(objectName);
+ }
+
+ for (final CreationalContext<?> cc : toRelease) {
+ try {
+ cc.release();
+ } catch (final Exception e) {
+ LOGGER.warning(e.getMessage(), e);
+ }
+ }
+ for (final CdiSingletonResourceProvider provider : singletons) {
+ try {
+ provider.release();
+ } catch (final Exception e) {
+ LOGGER.warning(e.getMessage(), e);
+ }
+ }
+
+ final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
+ try {
+ server.destroy();
+ SystemInstance.get().fireEvent(new ServerDestroyed(server));
+ } catch (final RuntimeException ise) {
+ LOGGER.warning("Can't stop correctly the endpoint " + server);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(ise.getMessage(), ise);
+ }
+ } finally {
+ if (oldLoader != null) {
+ CxfUtil.clearBusLoader(oldLoader);
+ }
+ }
+ }
+
+ @Override
+ public void deployApplication(final Application application, final String prefix, final String webContext,
+ final Collection<Object> additionalProviders,
+ final Map<String, EJBRestServiceInfo> restEjbs, final ClassLoader classLoader,
+ final Collection<Injection> injections, final Context context, final WebBeansContext owbCtx,
+ final ServiceConfiguration serviceConfiguration) {
+ final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
+ try {
+ final JAXRSServerFactoryBean factory = newFactory(prefix, createServiceJmxName(classLoader), createEndpointName(application));
+ configureFactory(additionalProviders, serviceConfiguration, factory, owbCtx);
+ factory.setApplication(application);
+
+ final List<Class<?>> classes = new ArrayList<Class<?>>();
+
+ for (final Class<?> clazz : application.getClasses()) {
+ if (!additionalProviders.contains(clazz) && !clazz.isInterface()) {
+ classes.add(clazz);
+
+ final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
+
+ if (restServiceInfo != null) {
+ final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
+ factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
+ } else {
+ factory.setResourceProvider(clazz, new OpenEJBPerRequestPojoResourceProvider(
+ classLoader, clazz, injections, context, owbCtx));
+ }
+ }
+ }
+
+ for (final Object o : application.getSingletons()) {
+ if (!additionalProviders.contains(o)) {
+ final Class<?> clazz = realClass(o.getClass());
+ classes.add(clazz);
+
+ final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
+
+ if (restServiceInfo != null) {
+ final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
+ factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
+ } else {
+ if (owbCtx.getBeanManagerImpl().isInUse()) {
+ final CdiSingletonResourceProvider provider = new CdiSingletonResourceProvider(classLoader, clazz, o, injections, context, owbCtx);
+ singletons.add(provider);
+ factory.setResourceProvider(clazz, provider);
+ } else {
+ factory.setResourceProvider(clazz, new SingletonResourceProvider(o));
+ }
+ }
+ }
+ }
+
+ factory.setResourceClasses(classes);
+ factory.setInvoker(new AutoJAXRSInvoker(restEjbs));
+
+ this.context = webContext;
+ if (!webContext.startsWith("/")) {
+ this.context = "/" + webContext;
+ } // /webcontext/servlet for event firing
+
+ final Level level = SERVER_IMPL_LOGGER.getLevel();
+ try {
+ SERVER_IMPL_LOGGER.setLevel(Level.OFF);
+ } catch (final UnsupportedOperationException e) {
+ //ignore
+ }
+ try {
+ server = factory.create();
+ fireServerCreated(oldLoader);
+ } finally {
+ try {
+ SERVER_IMPL_LOGGER.setLevel(level);
+ } catch (final UnsupportedOperationException e) {
+ //ignore
+ }
+ }
+
+ final int servletIdx = 1 + this.context.substring(1).indexOf('/');
+ if (servletIdx > 0) {
+ this.servlet = this.context.substring(servletIdx);
+ this.context = this.context.substring(0, servletIdx);
+ }
+ destination = (AbstractHTTPDestination) server.getDestination();
+
+ final String base;
+ if (prefix.endsWith("/")) {
+ base = prefix.substring(0, prefix.length() - 1);
+ } else if (prefix.endsWith(wildcard)) {
+ base = prefix.substring(0, prefix.length() - wildcard.length());
+ } else {
+ base = prefix;
+ }
+
+ // stack info to log to get nice logs
+ logEndpoints(application, prefix, restEjbs, factory, base);
+ } finally {
+ if (oldLoader != null) {
+ CxfUtil.clearBusLoader(oldLoader);
+ }
+ }
+ }
+
+ private EJBRestServiceInfo getEjbRestServiceInfo(final Map<String, EJBRestServiceInfo> restEjbs, final Class<?> clazz) {
+ String name = clazz.getName();
+ EJBRestServiceInfo restServiceInfo = restEjbs.get(name);
+
+ if (name.endsWith(DynamicSubclass.IMPL_SUFFIX)) {
+ name = name.substring(0, name.length() - DynamicSubclass.IMPL_SUFFIX.length());
+ restServiceInfo = restEjbs.get(name);
+ if (restServiceInfo != null) { // AutoJAXRSInvoker relies on it
+ restEjbs.put(clazz.getName(), restServiceInfo);
+ }
+ }
+ return restServiceInfo;
+ }
+
+ private static Class<?> realClass(final Class<?> aClass) {
+ Class<?> result = aClass;
+ while (result.getName().contains("$$")) {
+ result = result.getSuperclass();
+ if (result == null) {
+ return aClass;
+ }
+ }
+ return result;
+ }
+
+ private static String createEndpointName(final Application application) {
+ if (application == null) {
+ return "jaxrs-application";
+ }
+ if (InternalApplication.class.isInstance(application)) {
+ final Application original = InternalApplication.class.cast(application).getOriginal();
+ if (original != null) {
+ return original.getClass().getSimpleName();
+ }
+ return "jaxrs-application";
+ }
+ return application.getClass().getSimpleName();
+ }
+
+ private static String createServiceJmxName(final ClassLoader classLoader) {
+ final AppContext app = AppFinder.findAppContextOrWeb(classLoader, AppFinder.AppContextTransformer.INSTANCE);
+ return app == null ? "application" : app.getId();
+ }
+
+ private void logEndpoints(final Application application, final String prefix,
+ final Map<String, EJBRestServiceInfo> restEjbs,
+ final JAXRSServerFactoryBean factory, final String base) {
+ final List<Logs.LogResourceEndpointInfo> resourcesToLog = new ArrayList<Logs.LogResourceEndpointInfo>();
+ int classSize = 0;
+ int addressSize = 0;
+
+ final JAXRSServiceImpl service = (JAXRSServiceImpl) factory.getServiceFactory().getService();
+ final List<ClassResourceInfo> resources = service.getClassResourceInfos();
+ for (final ClassResourceInfo info : resources) {
+ if (info.getResourceClass() == null) { // possible?
+ continue;
+ }
+
+ final String address = Logs.singleSlash(base, info.getURITemplate().getValue());
+
+ final String clazz = info.getResourceClass().getName();
+ final String type;
+ if (restEjbs.containsKey(clazz)) {
+ type = "EJB";
+ } else {
+ type = "Pojo";
+ }
+
+ classSize = Math.max(classSize, clazz.length());
+ addressSize = Math.max(addressSize, address.length());
+
+ int methodSize = 7;
+ int methodStrSize = 0;
+
+ final List<Logs.LogOperationEndpointInfo> toLog = new ArrayList<Logs.LogOperationEndpointInfo>();
+
+ final MethodDispatcher md = info.getMethodDispatcher();
+ for (final OperationResourceInfo ori : md.getOperationResourceInfos()) {
+ final String httpMethod = ori.getHttpMethod();
+ final String currentAddress = Logs.singleSlash(address, ori.getURITemplate().getValue());
+ final String methodToStr = Logs.toSimpleString(ori.getMethodToInvoke());
+ toLog.add(new Logs.LogOperationEndpointInfo(httpMethod, currentAddress, methodToStr));
+
+ if (httpMethod != null) {
+ methodSize = Math.max(methodSize, httpMethod.length());
+ }
+ addressSize = Math.max(addressSize, currentAddress.length());
+ methodStrSize = Math.max(methodStrSize, methodToStr.length());
+ }
+
+ Collections.sort(toLog);
+
+ resourcesToLog.add(new Logs.LogResourceEndpointInfo(type, address, clazz, toLog, methodSize, methodStrSize));
+ }
+
+ // effective logging
+
+ LOGGER.info("REST Application: " + Logs.forceLength(prefix, addressSize, true) + " -> " + application.getClass().getName());
+
+ Collections.sort(resourcesToLog);
+
+ for (final Logs.LogResourceEndpointInfo resource : resourcesToLog) {
+
+ // Init and register MBeans
+ final ObjectNameBuilder jmxName = new ObjectNameBuilder("openejb.management")
+ .set("j2eeType", "JAX-RS")
+ .set("J2EEServer", "openejb")
+ .set("J2EEApplication", base)
+ .set("EndpointType", resource.type)
+ .set("name", resource.classname);
+
+ final ObjectName jmxObjectName = jmxName.build();
+ LocalMBeanServer.registerDynamicWrapperSilently(
+ new RestServiceMBean(resource),
+ jmxObjectName);
+
+ jmxNames.add(jmxObjectName);
+
+ LOGGER.info(" Service URI: "
+ + Logs.forceLength(resource.address, addressSize, true) + " -> "
+ + Logs.forceLength(resource.type, 4, false) + " "
+ + Logs.forceLength(resource.classname, classSize, true));
+
+ for (final Logs.LogOperationEndpointInfo log : resource.operations) {
+ LOGGER.info(" "
+ + Logs.forceLength(log.http, resource.methodSize, false) + " "
+ + Logs.forceLength(log.address, addressSize, true) + " -> "
+ + Logs.forceLength(log.method, resource.methodStrSize, true));
+ }
+
+ resource.operations.clear();
+ }
+ resourcesToLog.clear();
+ }
+
+ private JAXRSServerFactoryBean newFactory(final String prefix, final String service, final String endpoint) {
+ final JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean() {
+ @Override
+ protected Endpoint createEndpoint() throws BusException, EndpointException {
+ final Endpoint created = super.createEndpoint();
+ created.put(ManagedEndpoint.SERVICE_NAME, service);
+ created.put(ManagedEndpoint.ENDPOINT_NAME, endpoint);
+ return created;
+ }
+ };
+ factory.setDestinationFactory(transportFactory);
+ factory.setBus(CxfUtil.getBus());
+ factory.setAddress(prefix);
+ return factory;
+ }
+
+ private void configureFactory(final Collection<Object> givenAdditionalProviders,
+ final ServiceConfiguration serviceConfiguration,
+ final JAXRSServerFactoryBean factory,
+ final WebBeansContext ctx) {
+ CxfUtil.configureEndpoint(factory, serviceConfiguration, CXF_JAXRS_PREFIX);
+
+ final Collection<ServiceInfo> services = serviceConfiguration.getAvailableServices();
+
+ final String staticSubresourceResolution = serviceConfiguration.getProperties().getProperty(CXF_JAXRS_PREFIX + STATIC_SUB_RESOURCE_RESOLUTION_KEY);
+ if (staticSubresourceResolution != null) {
+ factory.setStaticSubresourceResolution("true".equalsIgnoreCase(staticSubresourceResolution));
+ }
+
+ // resource comparator
+ final String resourceComparator = serviceConfiguration.getProperties().getProperty(RESOURCE_COMPARATOR_KEY);
+ if (resourceComparator != null) {
+ try {
+ ResourceComparator instance = (ResourceComparator) ServiceInfos.resolve(services, resourceComparator);
+ if (instance == null) {
+ instance = (ResourceComparator) Thread.currentThread().getContextClassLoader()
+ .loadClass(resourceComparator).newInstance();
+ }
+ factory.setResourceComparator(instance);
+ } catch (final Exception e) {
+ LOGGER.error("Can't create the resource comparator " + resourceComparator, e);
+ }
+ }
+
+ // static resources
+ final String staticResources = serviceConfiguration.getProperties().getProperty(STATIC_RESOURCE_KEY);
+ if (staticResources != null) {
+ final String[] resources = staticResources.split(",");
+ for (final String r : resources) {
+ final String trimmed = r.trim();
+ if (!trimmed.isEmpty()) {
+ staticResourcesList.add(Pattern.compile(trimmed));
+ }
+ }
+ }
+
+ // providers
+ Set<String> providersConfig = null;
+
+ {
+ final String provider = serviceConfiguration.getProperties().getProperty(PROVIDERS_KEY);
+ if (provider != null) { // already ordered and high priority since they were configured manually
+ providersConfig = new HashSet<String>();
+ for (final String p : Arrays.asList(provider.split(","))) {
+ providersConfig.add(p.trim());
+ }
+ }
+
+ {
+ if (GLOBAL_PROVIDERS != null) { // same idea, Note: this doesn't affect much cases which are not embedded so don't spend time on it
+ if (providersConfig == null) {
+ providersConfig = new HashSet<String>();
+ }
+ providersConfig.addAll(Arrays.asList(GLOBAL_PROVIDERS.split(",")));
+ }
+ }
+ }
+
+ // another property to configure the scanning of providers but this one is consistent with current cxf config
+ // the
<TRUNCATED>
[12/12] tomee git commit: Merge branch 'tomee-1.7.3-prepare' of
https://git-wip-us.apache.org/repos/asf/tomee into tomee-1.7.3-prepare
Posted by an...@apache.org.
Merge branch 'tomee-1.7.3-prepare' of https://git-wip-us.apache.org/repos/asf/tomee into tomee-1.7.3-prepare
# Conflicts:
# container/openejb-core/src/main/java/org/apache/openejb/core/transaction/JtaTransactionPolicy.java
# tomee/apache-tomee/src/main/java/org/apache/tomee/RemoteTomEEEJBContainer.java
Project: http://git-wip-us.apache.org/repos/asf/tomee/repo
Commit: http://git-wip-us.apache.org/repos/asf/tomee/commit/ba185f5e
Tree: http://git-wip-us.apache.org/repos/asf/tomee/tree/ba185f5e
Diff: http://git-wip-us.apache.org/repos/asf/tomee/diff/ba185f5e
Branch: refs/heads/tomee-1.7.3-prepare
Commit: ba185f5e490ea25ce2968f94a932096c91cb2188
Parents: 352bade 029dd39
Author: AndyGee <an...@gmx.de>
Authored: Tue Nov 24 18:19:17 2015 +0100
Committer: AndyGee <an...@gmx.de>
Committed: Tue Nov 24 18:19:17 2015 +0100
----------------------------------------------------------------------
.gitignore | 409 ++++++++++++++++++-
.../java/org/apache/openejb/BeanContext.java | 8 +-
.../org/apache/openejb/ClientInjections.java | 8 +-
.../org/apache/openejb/InjectionProcessor.java | 25 +-
.../main/java/org/apache/openejb/Injector.java | 20 +-
.../main/java/org/apache/openejb/OpenEJB.java | 6 +
.../org/apache/openejb/OpenEjbContainer.java | 25 +-
.../cdi/CdiResourceInjectionService.java | 2 +-
.../typed/JmsConnectionFactoryBuilder.java | 1 +
.../openejb/core/ivm/naming/ContextWrapper.java | 11 +
.../core/transaction/JtaTransactionPolicy.java | 27 +-
.../resource/activemq/ActiveMQ5Factory.java | 8 +-
.../activemq/ConnectionFactoryWrapper.java | 111 +++++
.../resource/activemq/ConnectionWrapper.java | 189 +++++++++
.../resource/activemq/SessionWrapper.java | 253 ++++++++++++
.../org/apache/openejb/core/mdb/MdbInvoker.java | 92 +++--
.../org/apache/openejb/core/mdb/MdbUtil.java | 30 +-
.../junit/context/OpenEjbTestContext.java | 11 +
examples/injection-of-connectionfactory/pom.xml | 2 +-
.../org/superbiz/injection/jms/Messages.java | 8 +-
.../injection/jms/MessagingBeanTest.java | 8 +-
.../openejb/server/ejbd/JndiRequestHandler.java | 35 +-
.../apache/tomee/RemoteTomEEEJBContainer.java | 11 +
.../apache/tomee/catalina/OpenEJBContext.java | 42 +-
.../tomee/catalina/realm/CdiEventRealm.java | 5 +-
.../tomee/common/LegacyAnnotationProcessor.java | 105 +++--
.../tomee/embedded/EmbeddedTomEEContainer.java | 11 +
tomee/tomee-juli/pom.xml | 3 +-
28 files changed, 1295 insertions(+), 171 deletions(-)
----------------------------------------------------------------------
[08/12] tomee git commit: EOL
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-client/src/main/java/org/apache/openejb/client/MulticastPulseClient.java
----------------------------------------------------------------------
diff --git a/server/openejb-client/src/main/java/org/apache/openejb/client/MulticastPulseClient.java b/server/openejb-client/src/main/java/org/apache/openejb/client/MulticastPulseClient.java
index c08d37b..7881062 100644
--- a/server/openejb-client/src/main/java/org/apache/openejb/client/MulticastPulseClient.java
+++ b/server/openejb-client/src/main/java/org/apache/openejb/client/MulticastPulseClient.java
@@ -1,778 +1,778 @@
-package org.apache.openejb.client;
-
-import sun.net.util.IPAddressUtil;
-
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.MulticastSocket;
-import java.net.NetworkInterface;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.UnknownHostException;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.ConcurrentModificationException;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.TreeSet;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * 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.
- */
-public class MulticastPulseClient extends MulticastConnectionFactory {
-
- public static final String ORG_APACHE_OPENEJB_MULTIPULSE_TTL = "org.apache.openejb.multipulse.ttl";
- public static final String ORG_APACHE_OPENEJB_MULTIPULSE_URI_LIMIT = "org.apache.openejb.multipulse.uri.limit";
-
- private static final Logger log = Logger.getLogger("OpenEJB.client");
- private static final String SERVER = "OpenEJB.MCP.Server:";
- private static final String CLIENT = "OpenEJB.MCP.Client:";
- private static final String BADURI = ":BadUri:";
- private static final String EMPTY = "NoService";
- private static final Charset UTF8 = Charset.forName("UTF-8");
- private static final int TTL = Integer.parseInt(System.getProperty(ORG_APACHE_OPENEJB_MULTIPULSE_TTL, "32"));
- private static final int LIMIT = Integer.parseInt(System.getProperty(ORG_APACHE_OPENEJB_MULTIPULSE_URI_LIMIT, "50000"));
- private static final Map<URI, Set<URI>> knownUris = new HashMap<URI, Set<URI>>();
- private static NetworkInterface[] interfaces = getNetworkInterfaces();
- private static ExecutorService executor = null;
-
- private static synchronized NetworkInterface[] getInterfaces() {
- if (null == interfaces) {
- interfaces = getNetworkInterfaces();
- }
-
- return interfaces;
- }
-
- private static synchronized ExecutorService getExecutorService() {
-
- if (null == executor) {
-
- int length = getInterfaces().length;
- if (length < 1) {
- length = 1;
- }
-
- executor = Executors.newFixedThreadPool(length * 2);
- }
-
- return executor;
- }
-
- /**
- * @param uri Connection URI
- * @return Connection
- * @throws IOException or error
- * @throws IllegalArgumentException On undefined error
- */
- @Override
- public Connection getConnection(final URI uri) throws IOException {
-
- if (knownUris.size() >= LIMIT) {
- //This is here just as a brake to prevent DOS or OOME.
- //There is no way we should have more than this number of unique MutliPulse URI's in a LAN
- throw new IllegalArgumentException("Unique MultiPulse URI limit of " +
- LIMIT +
- " reached. Increase using the system property '" +
- ORG_APACHE_OPENEJB_MULTIPULSE_URI_LIMIT +
- "'");
- }
-
- Set<URI> uriSet = knownUris.get(uri);
-
- if (null == uriSet || uriSet.isEmpty()) {
-
- final Map<String, String> params = getUriParameters(uri);
-
- final Set<String> schemes = getSet(params, "schemes", this.getDefaultSchemes());
- final String group = getString(params, "group", "default");
- final long timeout = getLong(params, "timeout", 250);
-
- try {
- uriSet = MulticastPulseClient.discoverURIs(group, schemes, uri.getHost(), uri.getPort(), timeout);
- } catch (final Exception e) {
- throw new IllegalArgumentException("Unable to find an ejb server via the MultiPulse URI: " + uri);
- }
-
- knownUris.put(uri, uriSet);
- }
-
- for (final URI serviceURI : uriSet) {
-
- //Strip serverhost and group and try to connect
- final URI tryUri = URI.create(URI.create(serviceURI.getSchemeSpecificPart()).getSchemeSpecificPart());
-
- try {
- return ConnectionManager.getConnection(tryUri);
- } catch (final Exception e) {
-
- uriSet.remove(serviceURI);
-
- if (java.net.SocketTimeoutException.class.isInstance(e) || SocketException.class.isInstance(e)) {
- //Notify server that this URI is not reachable
- MulticastPulseClient.broadcastBadUri(getString(getUriParameters(uri), "group", "default"), tryUri, uri.getHost(), uri.getPort());
- }
-
- if (log.isLoggable(Level.FINE)) {
- log.fine("Failed connection to: " + serviceURI);
- }
- }
- }
-
- throw new IOException("Unable to connect an ejb server via the MultiPulse URI: " + uri);
- }
-
- private static Map<String, String> getUriParameters(final URI uri) {
- final Map<String, String> params;
- try {
- params = URIs.parseParamters(uri);
- } catch (final URISyntaxException e) {
- throw new IllegalArgumentException("Invalid MultiPulse uri " + uri.toString(), e);
- }
- return params;
- }
-
- /**
- * Get a list of URIs discovered for the provided request.
- * <p/>
- * Returned URIs are of the format 'mp-{serverhost}:group:scheme://servicehost:port'.
- * The serverhost is prefixed with 'mp-' in case the serverhost is an IP-Address, as RFC 2396 defines scheme must begin with a 'letter'
- *
- * @param forGroup Specific case sensitive group name or * for all
- * @param schemes Acceptable scheme list
- * @param host Multicast host address
- * @param port Multicast port
- * @param timeout Time to wait for a server response, at least 50ms
- * @return A URI set, possibly empty
- * @throws Exception On error
- */
- public static Set<URI> discoverURIs(final String forGroup, final Set<String> schemes, final String host, final int port, long timeout) throws Exception {
-
- if (timeout < 50) {
- timeout = 50;
- }
-
- if (null == forGroup || forGroup.isEmpty()) {
- throw new Exception("Specify a valid group or *");
- }
-
- if (null == schemes || schemes.isEmpty()) {
- throw new Exception("Specify at least one scheme, 'ejbd' for example");
- }
-
- if (null == host || host.isEmpty()) {
- throw new Exception("Specify a valid host name");
- }
-
- if (port < 1 || port > 65535) {
- throw new Exception("Specify a valid port between 1 and 65535");
- }
-
- final InetAddress ia = getAddress(host);
-
- final byte[] bytes = (MulticastPulseClient.CLIENT + forGroup).getBytes(UTF8);
- final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
-
- final AtomicBoolean running = new AtomicBoolean(true);
- final List<Future> futures = Collections.synchronizedList(new ArrayList<Future>());
-
- MulticastSocket[] clientSockets = null;
-
- try {
- clientSockets = MulticastPulseClient.getSockets(ia, port);
- final MulticastSocket[] clientSocketsFinal = clientSockets;
-
- final Timer timer = new Timer(true);
-
- final Set<URI> set = new TreeSet<URI>(new Comparator<URI>() {
- @Override
- public int compare(final URI uri1, final URI uri2) {
-
- //Ignore server hostname
- URI u1 = URI.create(uri1.getSchemeSpecificPart());
- URI u2 = URI.create(uri2.getSchemeSpecificPart());
-
- //Ignore scheme (ejb,ejbs,etc.)
- u1 = URI.create(u1.getSchemeSpecificPart());
- u2 = URI.create(u2.getSchemeSpecificPart());
-
- //Compare URI hosts
- int i = compare(u1.getHost(), u2.getHost());
- if (i != 0) {
- i = uri1.compareTo(uri2);
- }
-
- return i;
- }
-
- private int compare(final String h1, final String h2) {
-
- //Sort by hostname, IPv4, IPv6
-
- try {
- if (IPAddressUtil.isIPv4LiteralAddress(h1)) {
- if (IPAddressUtil.isIPv6LiteralAddress(h2.replace("[", "").replace("]", ""))) {
- return -1;
- }
- } else if (IPAddressUtil.isIPv6LiteralAddress(h1.replace("[", "").replace("]", ""))) {
- if (IPAddressUtil.isIPv4LiteralAddress(h2)) {
- return 1;
- }
- } else if (0 != h1.compareTo(h2)) {
- return -1;
- }
- } catch (final Exception e) {
- //Ignore
- }
-
- return h1.compareTo(h2);
- }
- });
-
- final ReentrantLock setLock = new ReentrantLock();
-
- //Start threads that listen for multicast packets on our channel.
- //These need to start 'before' we pulse a request.
- final CountDownLatch latchListeners = new CountDownLatch(clientSocketsFinal.length);
-
- for (final MulticastSocket socket : clientSocketsFinal) {
-
- futures.add(getExecutorService().submit(new Runnable() {
- @Override
- public void run() {
- try {
- final DatagramPacket response = new DatagramPacket(new byte[2048], 2048);
- latchListeners.countDown();
-
- while (running.get()) {
- try {
-
- socket.receive(response);
-
- final SocketAddress sa = response.getSocketAddress();
-
- if (null != sa && (sa instanceof InetSocketAddress)) {
-
- int len = response.getLength();
- if (len > 2048) {
-
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Truncating multipulse length {0} to 2048", new Object[]{len});
- }
- len = 2048;
- }
-
- String s = new String(response.getData(), 0, len);
-
- if (s.startsWith(MulticastPulseClient.SERVER)) {
-
- s = (s.replace(MulticastPulseClient.SERVER, ""));
- final String group = s.substring(0, s.indexOf(':'));
- s = s.substring(group.length() + 1);
-
- if (!"*".equals(forGroup) && !forGroup.equals(group)) {
- continue;
- }
-
- final String services = s.substring(0, s.lastIndexOf('|'));
- s = s.substring(services.length() + 1);
-
- final String[] serviceList = services.split("\\|");
- final String[] hosts = s.split(",");
-
- for (final String svc : serviceList) {
-
- if (EMPTY.equals(svc)) {
- continue;
- }
-
- final URI serviceUri;
- try {
- serviceUri = URI.create(svc);
- } catch (final Exception e) {
- continue;
- }
-
- if (schemes.contains(serviceUri.getScheme())) {
-
- //Just because multicast was received on this host is does not mean the service is on the same
- //We can however use this to identify an individual machine and group
- final String serverHost = ((InetSocketAddress) response.getSocketAddress()).getAddress().getHostAddress();
-
- final String serviceHost = serviceUri.getHost();
- if (MulticastPulseClient.isLocalAddress(serviceHost, false)) {
- if (!MulticastPulseClient.isLocalAddress(serverHost, false)) {
- //A local service is only available to a local client
- continue;
- }
- }
-
- final String svcfull = ("mp-" + serverHost + ":" + group + ":" + svc);
-
- setLock.lock();
-
- try {
- if (svcfull.contains("0.0.0.0")) {
- for (final String h : hosts) {
- if (!h.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
- set.add(URI.create(svcfull.replace("0.0.0.0", ipFormat(h))));
- }
- }
- } else if (svcfull.contains("[::]")) {
- for (final String h : hosts) {
- if (!h.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
- set.add(URI.create(svcfull.replace("[::]", ipFormat(h))));
- }
- }
- } else {
- //Just add as is
- set.add(URI.create(svcfull));
- }
- } catch (final Exception e) {
- //Ignore
- } finally {
- setLock.unlock();
- }
- }
- }
- }
- }
-
- } catch (final Exception e) {
- //Ignore
- }
- }
- } finally {
- try {
- socket.leaveGroup(ia);
- } catch (final Exception e) {
- //Ignore
- }
- try {
- socket.close();
- } catch (final Exception e) {
- //Ignore
- }
- }
- }
- }));
- }
-
- try {
- //Give listener threads a reasonable amount of time to start
- if (latchListeners.await(clientSocketsFinal.length * 2, TimeUnit.SECONDS)) {
-
- //Start pulsing client request every 10ms - This will ensure we have at least 4 client pulses within our minimum timeout
- //This pulse is designed to tell a listening server to wake up and pulse back a response
- futures.add(0, getExecutorService().submit(new Runnable() {
- @Override
- public void run() {
- while (running.get()) {
- //Pulse to listening servers - It is thread safe to use same sockets as send/receive synchronization is only on the packet
- for (final MulticastSocket socket : clientSocketsFinal) {
-
- if (running.get()) {
- try {
- socket.send(request);
- } catch (final Exception e) {
- //Ignore
- }
- } else {
- break;
- }
- }
-
- if (running.get()) {
- try {
- Thread.sleep(10);
- } catch (final InterruptedException e) {
- break;
- }
- }
- }
- }
- }));
- } else {
- timeout = 1;
- }
-
- } catch (final InterruptedException e) {
- //Terminate as quickly as possible
- timeout = 1;
- }
-
- //Kill the threads after timeout
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
-
- running.set(false);
-
- try {
- for (final Future future : futures) {
- future.cancel(true);
- }
- } catch (final ConcurrentModificationException e) {
- //Ignore
- }
-
- }
- }, timeout);
-
- //Wait for threads to complete
- for (final Future future : futures) {
- try {
- future.get();
- } catch (final Exception e) {
- //Ignore
- }
- }
-
- setLock.lock();
- try {
- return new TreeSet<URI>(set);
- } finally {
- setLock.unlock();
- }
- } finally {
-
- //Just to be sure we are clean
- for (final Future future : futures) {
- try {
- future.cancel(true);
- } catch (final Exception e) {
- //Ignore
- }
- }
-
- futures.clear();
-
- for (final MulticastSocket socket : clientSockets) {
-
- try {
- socket.leaveGroup(ia);
- } catch (final Exception e) {
- //Ignore
- }
- try {
- socket.close();
- } catch (final Exception e) {
- //Ignore
- }
- }
- }
- }
-
- private static InetAddress getAddress(final String host) throws Exception {
- final InetAddress ia;
- try {
- ia = InetAddress.getByName(host);
- } catch (final UnknownHostException e) {
- throw new Exception(host + " is not a valid address", e);
- }
-
- if (null == ia || !ia.isMulticastAddress()) {
- throw new Exception(host + " is not a valid multicast address");
- }
- return ia;
- }
-
- /**
- * Is the provided host a local host
- *
- * @param host The host to test
- * @param wildcardIsLocal Should 0.0.0.0 or [::] be deemed as local
- * @return True is the host is a local host else false
- */
- public static boolean isLocalAddress(final String host, final boolean wildcardIsLocal) {
-
- final InetAddress addr;
- try {
- addr = InetAddress.getByName(host);
- } catch (final UnknownHostException e) {
- return false;
- }
-
- // Check if the address is a valid special local or loop back
- if ((wildcardIsLocal && addr.isAnyLocalAddress()) || addr.isLoopbackAddress()) {
- return true;
- }
-
- // Check if the address is defined on any local interface
- try {
- return NetworkInterface.getByInetAddress(addr) != null;
- } catch (final SocketException e) {
- return false;
- }
- }
-
- private static String ipFormat(final String h) throws UnknownHostException {
-
- final InetAddress ia = InetAddress.getByName(h);
- if (ia instanceof Inet6Address) {
- return "[" + ia.getHostAddress() + "]";
- } else {
- return h;
- }
- }
-
- public static MulticastSocket[] getSockets(final InetAddress ia, final int port) throws Exception {
-
- final ArrayList<MulticastSocket> list = new ArrayList<MulticastSocket>();
-
- for (final NetworkInterface ni : getInterfaces()) {
-
- MulticastSocket ms = null;
-
- try {
-
- ms = new MulticastSocket(port);
- ms.setNetworkInterface(ni);
- ms.setSoTimeout(0);
- ms.setTimeToLive(TTL);
- if (!ms.getBroadcast()) {
- ms.setBroadcast(true);
- }
- ms.joinGroup(ia);
-
- list.add(ms);
-
- } catch (final Exception e) {
-
- if (null != ms) {
- try {
- ms.close();
- } catch (final Exception t) {
- //Ignore
- }
- }
-
- }
- }
-
- return list.toArray(new MulticastSocket[list.size()]);
- }
-
- private static NetworkInterface[] getNetworkInterfaces() {
-
- final HashSet<NetworkInterface> list = new HashSet<NetworkInterface>();
-
- try {
- final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
- while (interfaces.hasMoreElements()) {
- final NetworkInterface next = interfaces.nextElement();
-
- if (next.supportsMulticast() && next.isUp()) {
- list.add(next);
- }
- }
- } catch (final SocketException e) {
- //Ignore
- }
-
- return list.toArray(new NetworkInterface[list.size()]);
- }
-
- private static final CommandParser cmd = new CommandParser() {
- @Override
- protected void init() {
- category("Options");
-
- opt('g', "group").type(String.class).value("*").description("Group name");
-
- opt('h', "host").type(String.class).value("239.255.3.2").description("Multicast address");
-
- opt('p', "port").type(int.class).value(6142).description("Multicast port");
-
- opt('t', "timeout").type(int.class).value(1000).description("Pulse back timeout");
- }
-
- @Override
- protected List<String> validate(final Arguments arguments) {
- return super.validate(arguments);
- }
-
- @Override
- protected List<String> usage() {
- return super.usage();
- }
- };
-
- @SuppressWarnings("UseOfSystemOutOrSystemErr")
- public static void main(final String[] args) throws Exception {
-
- final CommandParser.Arguments arguments;
- try {
- arguments = cmd.parse(args);
- } catch (final CommandParser.HelpException e) {
- System.exit(0);
- throw new Exception(); // never reached, but keeps compiler happy
- } catch (final CommandParser.InvalidOptionsException e) {
- System.exit(1);
- throw new Exception(); // never reached, but keeps compiler happy
- }
-
- final Options options = arguments.options();
-
- final String discover = options.get("group", "*");
- final String mchost = options.get("host", "239.255.3.2");
- final int mcport = options.get("port", 6142);
- final int timeout = options.get("timeout", 1500);
-
- System.out.println(String.format("Using discovery options group=%1$s, host=%2$s, port=%3$s, timeout=%4$s", discover, mchost, mcport, timeout));
- System.out.println();
-
- final AtomicBoolean running = new AtomicBoolean(true);
-
- final Thread t = new Thread(new Runnable() {
- @SuppressWarnings("UseOfSystemOutOrSystemErr")
- @Override
- public void run() {
- while (running.get()) {
-
- Set<URI> uriSet = null;
- try {
- uriSet = MulticastPulseClient.discoverURIs(discover, new HashSet<String>(Arrays.asList("ejbd", "ejbds", "http", "https")), mchost, mcport, timeout);
- } catch (final Exception e) {
- System.err.println(e.getMessage());
- }
-
- final int size = uriSet.size();
- if (uriSet != null && size > 0) {
-
- final int st = (timeout / size);
-
- for (final URI uri : uriSet) {
-
- final String server = uri.getScheme().replace("mp-", "");
- URI uriSub = URI.create(uri.getSchemeSpecificPart());
-
- final String group = uriSub.getScheme();
- uriSub = URI.create(uriSub.getSchemeSpecificPart());
-
- final String host = uriSub.getHost();
- final int port = uriSub.getPort();
-
- if (MulticastPulseClient.isLocalAddress(host, false) && !MulticastPulseClient.isLocalAddress(server, false)) {
- System.out.println(server + ":" + group + " - " + uriSub.toASCIIString() + " is not a local service");
- continue;
- }
-
- System.out.print(server + ":" + group + " - " + uriSub.toASCIIString() + " is reachable: ");
-
- boolean b = false;
- final Socket s = new Socket();
- try {
- s.connect(new InetSocketAddress(host, port), st);
- b = true;
- } catch (final Exception e) {
- if (java.net.SocketTimeoutException.class.isInstance(e) || SocketException.class.isInstance(e)) {
- MulticastPulseClient.broadcastBadUri(group, uriSub, mchost, mcport);
- System.out.print("" + e + " : ");
- }
- } finally {
- try {
- s.close();
- } catch (final Exception e) {
- //Ignore
- }
- }
-
- System.out.println(b);
- }
- } else {
- System.out.println("### Failed to discover server: " + discover);
- }
-
- System.out.println(".");
-
- try {
- Thread.sleep(500);
- } catch (final InterruptedException e) {
- //Ignore
- }
- }
- }
- }, "MulticastPulseClient Test");
-
- t.setDaemon(true);
- t.start();
-
- //noinspection ResultOfMethodCallIgnored
- System.in.read();
-
- running.set(false);
- t.interrupt();
- }
-
- /**
- * Asynchronous attempt to broadcast a bad URI on our channel.
- * Hopefully the culprit server will hear this and stop sending it.
- *
- * @param uri Bad URI to broadcast
- */
- private static void broadcastBadUri(final String group, final URI uri, final String host, final int port) {
-
- getExecutorService().submit(new Runnable() {
- @Override
- public void run() {
- try {
- final InetAddress ia = getAddress(host);
-
- final byte[] bytes = (MulticastPulseClient.CLIENT + group + MulticastPulseClient.BADURI + uri.getHost()).getBytes(UTF8);
- final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
-
- final MulticastSocket[] multicastSockets = MulticastPulseClient.getSockets(ia, port);
-
- for (final MulticastSocket socket : multicastSockets) {
-
- try {
- socket.send(request);
- } catch (final Exception e) {
- log.log(Level.WARNING, "Failed to broadcast bad URI: " + uri + " on: " + socket.getInterface().getHostAddress(), e);
- }
- }
- } catch (final Exception e) {
- log.log(Level.WARNING, "Failed to broadcast bad URI: " + uri, e);
- }
- }
- });
- }
-}
+package org.apache.openejb.client;
+
+import sun.net.util.IPAddressUtil;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MulticastSocket;
+import java.net.NetworkInterface;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.UnknownHostException;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.ConcurrentModificationException;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.TreeSet;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * 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.
+ */
+public class MulticastPulseClient extends MulticastConnectionFactory {
+
+ public static final String ORG_APACHE_OPENEJB_MULTIPULSE_TTL = "org.apache.openejb.multipulse.ttl";
+ public static final String ORG_APACHE_OPENEJB_MULTIPULSE_URI_LIMIT = "org.apache.openejb.multipulse.uri.limit";
+
+ private static final Logger log = Logger.getLogger("OpenEJB.client");
+ private static final String SERVER = "OpenEJB.MCP.Server:";
+ private static final String CLIENT = "OpenEJB.MCP.Client:";
+ private static final String BADURI = ":BadUri:";
+ private static final String EMPTY = "NoService";
+ private static final Charset UTF8 = Charset.forName("UTF-8");
+ private static final int TTL = Integer.parseInt(System.getProperty(ORG_APACHE_OPENEJB_MULTIPULSE_TTL, "32"));
+ private static final int LIMIT = Integer.parseInt(System.getProperty(ORG_APACHE_OPENEJB_MULTIPULSE_URI_LIMIT, "50000"));
+ private static final Map<URI, Set<URI>> knownUris = new HashMap<URI, Set<URI>>();
+ private static NetworkInterface[] interfaces = getNetworkInterfaces();
+ private static ExecutorService executor = null;
+
+ private static synchronized NetworkInterface[] getInterfaces() {
+ if (null == interfaces) {
+ interfaces = getNetworkInterfaces();
+ }
+
+ return interfaces;
+ }
+
+ private static synchronized ExecutorService getExecutorService() {
+
+ if (null == executor) {
+
+ int length = getInterfaces().length;
+ if (length < 1) {
+ length = 1;
+ }
+
+ executor = Executors.newFixedThreadPool(length * 2);
+ }
+
+ return executor;
+ }
+
+ /**
+ * @param uri Connection URI
+ * @return Connection
+ * @throws IOException or error
+ * @throws IllegalArgumentException On undefined error
+ */
+ @Override
+ public Connection getConnection(final URI uri) throws IOException {
+
+ if (knownUris.size() >= LIMIT) {
+ //This is here just as a brake to prevent DOS or OOME.
+ //There is no way we should have more than this number of unique MutliPulse URI's in a LAN
+ throw new IllegalArgumentException("Unique MultiPulse URI limit of " +
+ LIMIT +
+ " reached. Increase using the system property '" +
+ ORG_APACHE_OPENEJB_MULTIPULSE_URI_LIMIT +
+ "'");
+ }
+
+ Set<URI> uriSet = knownUris.get(uri);
+
+ if (null == uriSet || uriSet.isEmpty()) {
+
+ final Map<String, String> params = getUriParameters(uri);
+
+ final Set<String> schemes = getSet(params, "schemes", this.getDefaultSchemes());
+ final String group = getString(params, "group", "default");
+ final long timeout = getLong(params, "timeout", 250);
+
+ try {
+ uriSet = MulticastPulseClient.discoverURIs(group, schemes, uri.getHost(), uri.getPort(), timeout);
+ } catch (final Exception e) {
+ throw new IllegalArgumentException("Unable to find an ejb server via the MultiPulse URI: " + uri);
+ }
+
+ knownUris.put(uri, uriSet);
+ }
+
+ for (final URI serviceURI : uriSet) {
+
+ //Strip serverhost and group and try to connect
+ final URI tryUri = URI.create(URI.create(serviceURI.getSchemeSpecificPart()).getSchemeSpecificPart());
+
+ try {
+ return ConnectionManager.getConnection(tryUri);
+ } catch (final Exception e) {
+
+ uriSet.remove(serviceURI);
+
+ if (java.net.SocketTimeoutException.class.isInstance(e) || SocketException.class.isInstance(e)) {
+ //Notify server that this URI is not reachable
+ MulticastPulseClient.broadcastBadUri(getString(getUriParameters(uri), "group", "default"), tryUri, uri.getHost(), uri.getPort());
+ }
+
+ if (log.isLoggable(Level.FINE)) {
+ log.fine("Failed connection to: " + serviceURI);
+ }
+ }
+ }
+
+ throw new IOException("Unable to connect an ejb server via the MultiPulse URI: " + uri);
+ }
+
+ private static Map<String, String> getUriParameters(final URI uri) {
+ final Map<String, String> params;
+ try {
+ params = URIs.parseParamters(uri);
+ } catch (final URISyntaxException e) {
+ throw new IllegalArgumentException("Invalid MultiPulse uri " + uri.toString(), e);
+ }
+ return params;
+ }
+
+ /**
+ * Get a list of URIs discovered for the provided request.
+ * <p/>
+ * Returned URIs are of the format 'mp-{serverhost}:group:scheme://servicehost:port'.
+ * The serverhost is prefixed with 'mp-' in case the serverhost is an IP-Address, as RFC 2396 defines scheme must begin with a 'letter'
+ *
+ * @param forGroup Specific case sensitive group name or * for all
+ * @param schemes Acceptable scheme list
+ * @param host Multicast host address
+ * @param port Multicast port
+ * @param timeout Time to wait for a server response, at least 50ms
+ * @return A URI set, possibly empty
+ * @throws Exception On error
+ */
+ public static Set<URI> discoverURIs(final String forGroup, final Set<String> schemes, final String host, final int port, long timeout) throws Exception {
+
+ if (timeout < 50) {
+ timeout = 50;
+ }
+
+ if (null == forGroup || forGroup.isEmpty()) {
+ throw new Exception("Specify a valid group or *");
+ }
+
+ if (null == schemes || schemes.isEmpty()) {
+ throw new Exception("Specify at least one scheme, 'ejbd' for example");
+ }
+
+ if (null == host || host.isEmpty()) {
+ throw new Exception("Specify a valid host name");
+ }
+
+ if (port < 1 || port > 65535) {
+ throw new Exception("Specify a valid port between 1 and 65535");
+ }
+
+ final InetAddress ia = getAddress(host);
+
+ final byte[] bytes = (MulticastPulseClient.CLIENT + forGroup).getBytes(UTF8);
+ final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
+
+ final AtomicBoolean running = new AtomicBoolean(true);
+ final List<Future> futures = Collections.synchronizedList(new ArrayList<Future>());
+
+ MulticastSocket[] clientSockets = null;
+
+ try {
+ clientSockets = MulticastPulseClient.getSockets(ia, port);
+ final MulticastSocket[] clientSocketsFinal = clientSockets;
+
+ final Timer timer = new Timer(true);
+
+ final Set<URI> set = new TreeSet<URI>(new Comparator<URI>() {
+ @Override
+ public int compare(final URI uri1, final URI uri2) {
+
+ //Ignore server hostname
+ URI u1 = URI.create(uri1.getSchemeSpecificPart());
+ URI u2 = URI.create(uri2.getSchemeSpecificPart());
+
+ //Ignore scheme (ejb,ejbs,etc.)
+ u1 = URI.create(u1.getSchemeSpecificPart());
+ u2 = URI.create(u2.getSchemeSpecificPart());
+
+ //Compare URI hosts
+ int i = compare(u1.getHost(), u2.getHost());
+ if (i != 0) {
+ i = uri1.compareTo(uri2);
+ }
+
+ return i;
+ }
+
+ private int compare(final String h1, final String h2) {
+
+ //Sort by hostname, IPv4, IPv6
+
+ try {
+ if (IPAddressUtil.isIPv4LiteralAddress(h1)) {
+ if (IPAddressUtil.isIPv6LiteralAddress(h2.replace("[", "").replace("]", ""))) {
+ return -1;
+ }
+ } else if (IPAddressUtil.isIPv6LiteralAddress(h1.replace("[", "").replace("]", ""))) {
+ if (IPAddressUtil.isIPv4LiteralAddress(h2)) {
+ return 1;
+ }
+ } else if (0 != h1.compareTo(h2)) {
+ return -1;
+ }
+ } catch (final Exception e) {
+ //Ignore
+ }
+
+ return h1.compareTo(h2);
+ }
+ });
+
+ final ReentrantLock setLock = new ReentrantLock();
+
+ //Start threads that listen for multicast packets on our channel.
+ //These need to start 'before' we pulse a request.
+ final CountDownLatch latchListeners = new CountDownLatch(clientSocketsFinal.length);
+
+ for (final MulticastSocket socket : clientSocketsFinal) {
+
+ futures.add(getExecutorService().submit(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ final DatagramPacket response = new DatagramPacket(new byte[2048], 2048);
+ latchListeners.countDown();
+
+ while (running.get()) {
+ try {
+
+ socket.receive(response);
+
+ final SocketAddress sa = response.getSocketAddress();
+
+ if (null != sa && (sa instanceof InetSocketAddress)) {
+
+ int len = response.getLength();
+ if (len > 2048) {
+
+ if (log.isLoggable(Level.FINE)) {
+ log.log(Level.FINE, "Truncating multipulse length {0} to 2048", new Object[]{len});
+ }
+ len = 2048;
+ }
+
+ String s = new String(response.getData(), 0, len);
+
+ if (s.startsWith(MulticastPulseClient.SERVER)) {
+
+ s = (s.replace(MulticastPulseClient.SERVER, ""));
+ final String group = s.substring(0, s.indexOf(':'));
+ s = s.substring(group.length() + 1);
+
+ if (!"*".equals(forGroup) && !forGroup.equals(group)) {
+ continue;
+ }
+
+ final String services = s.substring(0, s.lastIndexOf('|'));
+ s = s.substring(services.length() + 1);
+
+ final String[] serviceList = services.split("\\|");
+ final String[] hosts = s.split(",");
+
+ for (final String svc : serviceList) {
+
+ if (EMPTY.equals(svc)) {
+ continue;
+ }
+
+ final URI serviceUri;
+ try {
+ serviceUri = URI.create(svc);
+ } catch (final Exception e) {
+ continue;
+ }
+
+ if (schemes.contains(serviceUri.getScheme())) {
+
+ //Just because multicast was received on this host is does not mean the service is on the same
+ //We can however use this to identify an individual machine and group
+ final String serverHost = ((InetSocketAddress) response.getSocketAddress()).getAddress().getHostAddress();
+
+ final String serviceHost = serviceUri.getHost();
+ if (MulticastPulseClient.isLocalAddress(serviceHost, false)) {
+ if (!MulticastPulseClient.isLocalAddress(serverHost, false)) {
+ //A local service is only available to a local client
+ continue;
+ }
+ }
+
+ final String svcfull = ("mp-" + serverHost + ":" + group + ":" + svc);
+
+ setLock.lock();
+
+ try {
+ if (svcfull.contains("0.0.0.0")) {
+ for (final String h : hosts) {
+ if (!h.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
+ set.add(URI.create(svcfull.replace("0.0.0.0", ipFormat(h))));
+ }
+ }
+ } else if (svcfull.contains("[::]")) {
+ for (final String h : hosts) {
+ if (!h.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
+ set.add(URI.create(svcfull.replace("[::]", ipFormat(h))));
+ }
+ }
+ } else {
+ //Just add as is
+ set.add(URI.create(svcfull));
+ }
+ } catch (final Exception e) {
+ //Ignore
+ } finally {
+ setLock.unlock();
+ }
+ }
+ }
+ }
+ }
+
+ } catch (final Exception e) {
+ //Ignore
+ }
+ }
+ } finally {
+ try {
+ socket.leaveGroup(ia);
+ } catch (final Exception e) {
+ //Ignore
+ }
+ try {
+ socket.close();
+ } catch (final Exception e) {
+ //Ignore
+ }
+ }
+ }
+ }));
+ }
+
+ try {
+ //Give listener threads a reasonable amount of time to start
+ if (latchListeners.await(clientSocketsFinal.length * 2, TimeUnit.SECONDS)) {
+
+ //Start pulsing client request every 10ms - This will ensure we have at least 4 client pulses within our minimum timeout
+ //This pulse is designed to tell a listening server to wake up and pulse back a response
+ futures.add(0, getExecutorService().submit(new Runnable() {
+ @Override
+ public void run() {
+ while (running.get()) {
+ //Pulse to listening servers - It is thread safe to use same sockets as send/receive synchronization is only on the packet
+ for (final MulticastSocket socket : clientSocketsFinal) {
+
+ if (running.get()) {
+ try {
+ socket.send(request);
+ } catch (final Exception e) {
+ //Ignore
+ }
+ } else {
+ break;
+ }
+ }
+
+ if (running.get()) {
+ try {
+ Thread.sleep(10);
+ } catch (final InterruptedException e) {
+ break;
+ }
+ }
+ }
+ }
+ }));
+ } else {
+ timeout = 1;
+ }
+
+ } catch (final InterruptedException e) {
+ //Terminate as quickly as possible
+ timeout = 1;
+ }
+
+ //Kill the threads after timeout
+ timer.schedule(new TimerTask() {
+ @Override
+ public void run() {
+
+ running.set(false);
+
+ try {
+ for (final Future future : futures) {
+ future.cancel(true);
+ }
+ } catch (final ConcurrentModificationException e) {
+ //Ignore
+ }
+
+ }
+ }, timeout);
+
+ //Wait for threads to complete
+ for (final Future future : futures) {
+ try {
+ future.get();
+ } catch (final Exception e) {
+ //Ignore
+ }
+ }
+
+ setLock.lock();
+ try {
+ return new TreeSet<URI>(set);
+ } finally {
+ setLock.unlock();
+ }
+ } finally {
+
+ //Just to be sure we are clean
+ for (final Future future : futures) {
+ try {
+ future.cancel(true);
+ } catch (final Exception e) {
+ //Ignore
+ }
+ }
+
+ futures.clear();
+
+ for (final MulticastSocket socket : clientSockets) {
+
+ try {
+ socket.leaveGroup(ia);
+ } catch (final Exception e) {
+ //Ignore
+ }
+ try {
+ socket.close();
+ } catch (final Exception e) {
+ //Ignore
+ }
+ }
+ }
+ }
+
+ private static InetAddress getAddress(final String host) throws Exception {
+ final InetAddress ia;
+ try {
+ ia = InetAddress.getByName(host);
+ } catch (final UnknownHostException e) {
+ throw new Exception(host + " is not a valid address", e);
+ }
+
+ if (null == ia || !ia.isMulticastAddress()) {
+ throw new Exception(host + " is not a valid multicast address");
+ }
+ return ia;
+ }
+
+ /**
+ * Is the provided host a local host
+ *
+ * @param host The host to test
+ * @param wildcardIsLocal Should 0.0.0.0 or [::] be deemed as local
+ * @return True is the host is a local host else false
+ */
+ public static boolean isLocalAddress(final String host, final boolean wildcardIsLocal) {
+
+ final InetAddress addr;
+ try {
+ addr = InetAddress.getByName(host);
+ } catch (final UnknownHostException e) {
+ return false;
+ }
+
+ // Check if the address is a valid special local or loop back
+ if ((wildcardIsLocal && addr.isAnyLocalAddress()) || addr.isLoopbackAddress()) {
+ return true;
+ }
+
+ // Check if the address is defined on any local interface
+ try {
+ return NetworkInterface.getByInetAddress(addr) != null;
+ } catch (final SocketException e) {
+ return false;
+ }
+ }
+
+ private static String ipFormat(final String h) throws UnknownHostException {
+
+ final InetAddress ia = InetAddress.getByName(h);
+ if (ia instanceof Inet6Address) {
+ return "[" + ia.getHostAddress() + "]";
+ } else {
+ return h;
+ }
+ }
+
+ public static MulticastSocket[] getSockets(final InetAddress ia, final int port) throws Exception {
+
+ final ArrayList<MulticastSocket> list = new ArrayList<MulticastSocket>();
+
+ for (final NetworkInterface ni : getInterfaces()) {
+
+ MulticastSocket ms = null;
+
+ try {
+
+ ms = new MulticastSocket(port);
+ ms.setNetworkInterface(ni);
+ ms.setSoTimeout(0);
+ ms.setTimeToLive(TTL);
+ if (!ms.getBroadcast()) {
+ ms.setBroadcast(true);
+ }
+ ms.joinGroup(ia);
+
+ list.add(ms);
+
+ } catch (final Exception e) {
+
+ if (null != ms) {
+ try {
+ ms.close();
+ } catch (final Exception t) {
+ //Ignore
+ }
+ }
+
+ }
+ }
+
+ return list.toArray(new MulticastSocket[list.size()]);
+ }
+
+ private static NetworkInterface[] getNetworkInterfaces() {
+
+ final HashSet<NetworkInterface> list = new HashSet<NetworkInterface>();
+
+ try {
+ final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
+ while (interfaces.hasMoreElements()) {
+ final NetworkInterface next = interfaces.nextElement();
+
+ if (next.supportsMulticast() && next.isUp()) {
+ list.add(next);
+ }
+ }
+ } catch (final SocketException e) {
+ //Ignore
+ }
+
+ return list.toArray(new NetworkInterface[list.size()]);
+ }
+
+ private static final CommandParser cmd = new CommandParser() {
+ @Override
+ protected void init() {
+ category("Options");
+
+ opt('g', "group").type(String.class).value("*").description("Group name");
+
+ opt('h', "host").type(String.class).value("239.255.3.2").description("Multicast address");
+
+ opt('p', "port").type(int.class).value(6142).description("Multicast port");
+
+ opt('t', "timeout").type(int.class).value(1000).description("Pulse back timeout");
+ }
+
+ @Override
+ protected List<String> validate(final Arguments arguments) {
+ return super.validate(arguments);
+ }
+
+ @Override
+ protected List<String> usage() {
+ return super.usage();
+ }
+ };
+
+ @SuppressWarnings("UseOfSystemOutOrSystemErr")
+ public static void main(final String[] args) throws Exception {
+
+ final CommandParser.Arguments arguments;
+ try {
+ arguments = cmd.parse(args);
+ } catch (final CommandParser.HelpException e) {
+ System.exit(0);
+ throw new Exception(); // never reached, but keeps compiler happy
+ } catch (final CommandParser.InvalidOptionsException e) {
+ System.exit(1);
+ throw new Exception(); // never reached, but keeps compiler happy
+ }
+
+ final Options options = arguments.options();
+
+ final String discover = options.get("group", "*");
+ final String mchost = options.get("host", "239.255.3.2");
+ final int mcport = options.get("port", 6142);
+ final int timeout = options.get("timeout", 1500);
+
+ System.out.println(String.format("Using discovery options group=%1$s, host=%2$s, port=%3$s, timeout=%4$s", discover, mchost, mcport, timeout));
+ System.out.println();
+
+ final AtomicBoolean running = new AtomicBoolean(true);
+
+ final Thread t = new Thread(new Runnable() {
+ @SuppressWarnings("UseOfSystemOutOrSystemErr")
+ @Override
+ public void run() {
+ while (running.get()) {
+
+ Set<URI> uriSet = null;
+ try {
+ uriSet = MulticastPulseClient.discoverURIs(discover, new HashSet<String>(Arrays.asList("ejbd", "ejbds", "http", "https")), mchost, mcport, timeout);
+ } catch (final Exception e) {
+ System.err.println(e.getMessage());
+ }
+
+ final int size = uriSet.size();
+ if (uriSet != null && size > 0) {
+
+ final int st = (timeout / size);
+
+ for (final URI uri : uriSet) {
+
+ final String server = uri.getScheme().replace("mp-", "");
+ URI uriSub = URI.create(uri.getSchemeSpecificPart());
+
+ final String group = uriSub.getScheme();
+ uriSub = URI.create(uriSub.getSchemeSpecificPart());
+
+ final String host = uriSub.getHost();
+ final int port = uriSub.getPort();
+
+ if (MulticastPulseClient.isLocalAddress(host, false) && !MulticastPulseClient.isLocalAddress(server, false)) {
+ System.out.println(server + ":" + group + " - " + uriSub.toASCIIString() + " is not a local service");
+ continue;
+ }
+
+ System.out.print(server + ":" + group + " - " + uriSub.toASCIIString() + " is reachable: ");
+
+ boolean b = false;
+ final Socket s = new Socket();
+ try {
+ s.connect(new InetSocketAddress(host, port), st);
+ b = true;
+ } catch (final Exception e) {
+ if (java.net.SocketTimeoutException.class.isInstance(e) || SocketException.class.isInstance(e)) {
+ MulticastPulseClient.broadcastBadUri(group, uriSub, mchost, mcport);
+ System.out.print("" + e + " : ");
+ }
+ } finally {
+ try {
+ s.close();
+ } catch (final Exception e) {
+ //Ignore
+ }
+ }
+
+ System.out.println(b);
+ }
+ } else {
+ System.out.println("### Failed to discover server: " + discover);
+ }
+
+ System.out.println(".");
+
+ try {
+ Thread.sleep(500);
+ } catch (final InterruptedException e) {
+ //Ignore
+ }
+ }
+ }
+ }, "MulticastPulseClient Test");
+
+ t.setDaemon(true);
+ t.start();
+
+ //noinspection ResultOfMethodCallIgnored
+ System.in.read();
+
+ running.set(false);
+ t.interrupt();
+ }
+
+ /**
+ * Asynchronous attempt to broadcast a bad URI on our channel.
+ * Hopefully the culprit server will hear this and stop sending it.
+ *
+ * @param uri Bad URI to broadcast
+ */
+ private static void broadcastBadUri(final String group, final URI uri, final String host, final int port) {
+
+ getExecutorService().submit(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ final InetAddress ia = getAddress(host);
+
+ final byte[] bytes = (MulticastPulseClient.CLIENT + group + MulticastPulseClient.BADURI + uri.getHost()).getBytes(UTF8);
+ final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
+
+ final MulticastSocket[] multicastSockets = MulticastPulseClient.getSockets(ia, port);
+
+ for (final MulticastSocket socket : multicastSockets) {
+
+ try {
+ socket.send(request);
+ } catch (final Exception e) {
+ log.log(Level.WARNING, "Failed to broadcast bad URI: " + uri + " on: " + socket.getInterface().getHostAddress(), e);
+ }
+ }
+ } catch (final Exception e) {
+ log.log(Level.WARNING, "Failed to broadcast bad URI: " + uri, e);
+ }
+ }
+ });
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-client/src/main/java/org/apache/openejb/client/ProtocolMetaData.java
----------------------------------------------------------------------
diff --git a/server/openejb-client/src/main/java/org/apache/openejb/client/ProtocolMetaData.java b/server/openejb-client/src/main/java/org/apache/openejb/client/ProtocolMetaData.java
index b19252b..95a120f 100644
--- a/server/openejb-client/src/main/java/org/apache/openejb/client/ProtocolMetaData.java
+++ b/server/openejb-client/src/main/java/org/apache/openejb/client/ProtocolMetaData.java
@@ -1,112 +1,112 @@
-/**
- * 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.openejb.client;
-
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Arrays;
-
-/**
- * OpenEJB Enterprise Javabean Protocol (OEJP)
- * <p/>
- * OEJP uses a "<major>.<minor>" numbering scheme to indicate versions of the protocol.
- * <p/>
- * Protocol-Version = "OEJP" "/" 1*DIGIT "." 1*DIGIT
- * <p/>
- * Some compatability is guaranteed with the major part of the version number.
- *
- * @version $Revision$ $Date$
- */
-@SuppressWarnings("UnusedDeclaration")
-public class ProtocolMetaData {
-
- public static final String VERSION = "4.7";
-
- private static final String OEJB = "OEJP";
- private transient String id;
- private transient int major;
- private transient int minor;
-
- public ProtocolMetaData() {
- init(OEJB + "/" + VERSION);
- }
-
- public ProtocolMetaData(final String version) {
- init(OEJB + "/" + version);
- }
-
- private void init(final String spec) {
-
- if (!spec.matches("^OEJP/[0-9]\\.[0-9]$")) {
- throw new RuntimeException("Protocol version spec must follow format [ \"OEJB\" \"/\" 1*DIGIT \".\" 1*DIGIT ] - " + spec);
- }
-
- final char[] chars = new char[8];
- spec.getChars(0, chars.length, chars, 0);
-
- this.id = new String(chars, 0, 4);
- this.major = Integer.parseInt(new String(chars, 5, 1));
- this.minor = Integer.parseInt(new String(chars, 7, 1));
- }
-
- public boolean isAtLeast(final int major, final int minor) {
- return this.major >= major && (this.major != major || this.minor >= minor);
- }
-
- public String getId() {
- return id;
- }
-
- public int getMajor() {
- return major;
- }
-
- public int getMinor() {
- return minor;
- }
-
- public String getVersion() {
- return major + "." + minor;
- }
-
- public String getSpec() {
- return id + "/" + major + "." + minor;
- }
-
- public void writeExternal(final OutputStream out) throws IOException {
- out.write(getSpec().getBytes("UTF-8"));
- out.flush();
- }
-
- public void readExternal(final InputStream in) throws IOException {
- final byte[] spec = new byte[8];
- for (int i = 0; i < spec.length; i++) {
- spec[i] = (byte) in.read();
- if (spec[i] == -1) {
- throw new EOFException("Unable to read protocol version. Reached the end of the stream.");
- }
- }
- try {
- init(new String(spec, "UTF-8"));
- } catch (final Throwable e) {
- throw new IOException("Failed to read spec: " + Arrays.toString(spec), e);
- }
- }
-}
+/**
+ * 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.openejb.client;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Arrays;
+
+/**
+ * OpenEJB Enterprise Javabean Protocol (OEJP)
+ * <p/>
+ * OEJP uses a "<major>.<minor>" numbering scheme to indicate versions of the protocol.
+ * <p/>
+ * Protocol-Version = "OEJP" "/" 1*DIGIT "." 1*DIGIT
+ * <p/>
+ * Some compatability is guaranteed with the major part of the version number.
+ *
+ * @version $Revision$ $Date$
+ */
+@SuppressWarnings("UnusedDeclaration")
+public class ProtocolMetaData {
+
+ public static final String VERSION = "4.7";
+
+ private static final String OEJB = "OEJP";
+ private transient String id;
+ private transient int major;
+ private transient int minor;
+
+ public ProtocolMetaData() {
+ init(OEJB + "/" + VERSION);
+ }
+
+ public ProtocolMetaData(final String version) {
+ init(OEJB + "/" + version);
+ }
+
+ private void init(final String spec) {
+
+ if (!spec.matches("^OEJP/[0-9]\\.[0-9]$")) {
+ throw new RuntimeException("Protocol version spec must follow format [ \"OEJB\" \"/\" 1*DIGIT \".\" 1*DIGIT ] - " + spec);
+ }
+
+ final char[] chars = new char[8];
+ spec.getChars(0, chars.length, chars, 0);
+
+ this.id = new String(chars, 0, 4);
+ this.major = Integer.parseInt(new String(chars, 5, 1));
+ this.minor = Integer.parseInt(new String(chars, 7, 1));
+ }
+
+ public boolean isAtLeast(final int major, final int minor) {
+ return this.major >= major && (this.major != major || this.minor >= minor);
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public int getMajor() {
+ return major;
+ }
+
+ public int getMinor() {
+ return minor;
+ }
+
+ public String getVersion() {
+ return major + "." + minor;
+ }
+
+ public String getSpec() {
+ return id + "/" + major + "." + minor;
+ }
+
+ public void writeExternal(final OutputStream out) throws IOException {
+ out.write(getSpec().getBytes("UTF-8"));
+ out.flush();
+ }
+
+ public void readExternal(final InputStream in) throws IOException {
+ final byte[] spec = new byte[8];
+ for (int i = 0; i < spec.length; i++) {
+ spec[i] = (byte) in.read();
+ if (spec[i] == -1) {
+ throw new EOFException("Unable to read protocol version. Reached the end of the stream.");
+ }
+ }
+ try {
+ init(new String(spec, "UTF-8"));
+ } catch (final Throwable e) {
+ throw new IOException("Failed to read spec: " + Arrays.toString(spec), e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/AutoJAXRSInvoker.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/AutoJAXRSInvoker.java b/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/AutoJAXRSInvoker.java
index 012cb05..579f7eb 100644
--- a/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/AutoJAXRSInvoker.java
+++ b/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/AutoJAXRSInvoker.java
@@ -1,70 +1,70 @@
-/*
- * 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.openejb.server.cxf.rs;
-
-import org.apache.cxf.jaxrs.JAXRSInvoker;
-import org.apache.cxf.jaxrs.model.ClassResourceInfo;
-import org.apache.cxf.message.Exchange;
-import org.apache.cxf.service.invoker.Invoker;
-import org.apache.openejb.BeanContext;
-import org.apache.openejb.BeanType;
-import org.apache.openejb.server.rest.EJBRestServiceInfo;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Map;
-
-public class AutoJAXRSInvoker implements Invoker {
- private final Map<String, EJBRestServiceInfo> ejbs;
- private final OpenEJBEJBInvoker ejbInvoker;
- private final JAXRSInvoker jaxrsInvoker;
-
- public AutoJAXRSInvoker(final Map<String, EJBRestServiceInfo> restEjbs) {
- ejbs = restEjbs;
-
- // delegates
- jaxrsInvoker = new PojoInvoker();
- if (!ejbs.isEmpty()) {
- ejbInvoker = new OpenEJBEJBInvoker(beanContexts(restEjbs));
- } else {
- ejbInvoker = null; // no need
- }
- }
-
- private static Collection<BeanContext> beanContexts(final Map<String, EJBRestServiceInfo> restEjbs) {
- final Collection<BeanContext> bc = new ArrayList<BeanContext>();
- for (final EJBRestServiceInfo i : restEjbs.values()) {
- bc.add(i.context);
- }
- return bc;
- }
-
- @Override
- public Object invoke(final Exchange exchange, final Object o) { // mainly a select the right invoker impl
- final ClassResourceInfo cri = (ClassResourceInfo) exchange.get("root.resource.class");
-
- if (cri != null) {
- final String clazz = cri.getServiceClass().getName();
- final EJBRestServiceInfo restServiceInfo = ejbs.get(clazz);
- if (restServiceInfo != null && !BeanType.MANAGED.equals(restServiceInfo.context.getComponentType())) {
- return ejbInvoker.invoke(exchange, o);
- }
- }
-
- return jaxrsInvoker.invoke(exchange, o);
- }
-}
+/*
+ * 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.openejb.server.cxf.rs;
+
+import org.apache.cxf.jaxrs.JAXRSInvoker;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Exchange;
+import org.apache.cxf.service.invoker.Invoker;
+import org.apache.openejb.BeanContext;
+import org.apache.openejb.BeanType;
+import org.apache.openejb.server.rest.EJBRestServiceInfo;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Map;
+
+public class AutoJAXRSInvoker implements Invoker {
+ private final Map<String, EJBRestServiceInfo> ejbs;
+ private final OpenEJBEJBInvoker ejbInvoker;
+ private final JAXRSInvoker jaxrsInvoker;
+
+ public AutoJAXRSInvoker(final Map<String, EJBRestServiceInfo> restEjbs) {
+ ejbs = restEjbs;
+
+ // delegates
+ jaxrsInvoker = new PojoInvoker();
+ if (!ejbs.isEmpty()) {
+ ejbInvoker = new OpenEJBEJBInvoker(beanContexts(restEjbs));
+ } else {
+ ejbInvoker = null; // no need
+ }
+ }
+
+ private static Collection<BeanContext> beanContexts(final Map<String, EJBRestServiceInfo> restEjbs) {
+ final Collection<BeanContext> bc = new ArrayList<BeanContext>();
+ for (final EJBRestServiceInfo i : restEjbs.values()) {
+ bc.add(i.context);
+ }
+ return bc;
+ }
+
+ @Override
+ public Object invoke(final Exchange exchange, final Object o) { // mainly a select the right invoker impl
+ final ClassResourceInfo cri = (ClassResourceInfo) exchange.get("root.resource.class");
+
+ if (cri != null) {
+ final String clazz = cri.getServiceClass().getName();
+ final EJBRestServiceInfo restServiceInfo = ejbs.get(clazz);
+ if (restServiceInfo != null && !BeanType.MANAGED.equals(restServiceInfo.context.getComponentType())) {
+ return ejbInvoker.invoke(exchange, o);
+ }
+ }
+
+ return jaxrsInvoker.invoke(exchange, o);
+ }
+}
[02/12] tomee git commit: Check for null
Posted by an...@apache.org.
Check for null
Project: http://git-wip-us.apache.org/repos/asf/tomee/repo
Commit: http://git-wip-us.apache.org/repos/asf/tomee/commit/267945eb
Tree: http://git-wip-us.apache.org/repos/asf/tomee/tree/267945eb
Diff: http://git-wip-us.apache.org/repos/asf/tomee/diff/267945eb
Branch: refs/heads/tomee-1.7.3-prepare
Commit: 267945ebeccc3138dbed634d15e60776a28fde3d
Parents: a9ca7de
Author: AndyGee <an...@gmx.de>
Authored: Fri Nov 20 10:45:05 2015 +0100
Committer: AndyGee <an...@gmx.de>
Committed: Fri Nov 20 10:45:05 2015 +0100
----------------------------------------------------------------------
.../test/java/org/superbiz/injection/secure/MovieTest.java | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/tomee/blob/267945eb/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java
----------------------------------------------------------------------
diff --git a/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java b/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java
index e2d341c..b36c812 100644
--- a/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java
+++ b/examples/testing-security-4/src/test/java/org/superbiz/injection/secure/MovieTest.java
@@ -27,6 +27,7 @@ import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
+import java.net.URL;
import java.util.List;
import java.util.Properties;
@@ -51,7 +52,13 @@ public class MovieTest {
@Before
public void setUp() throws Exception {
final ClassLoader ctxCl = Thread.currentThread().getContextClassLoader();
- System.setProperty("openejb.ScriptLoginModule.scriptURI", ctxCl.getResource("loginscript.js").toExternalForm());
+ final URL resource = ctxCl.getResource("loginscript.js");
+
+ if (null != resource) {
+ System.setProperty("openejb.ScriptLoginModule.scriptURI", resource.toExternalForm());
+ }else{
+ throw new Exception("Resource loginscript.js was not found");
+ }
final Properties p = new Properties();
p.put("movieDatabase", "new://Resource?type=DataSource");
[04/12] tomee git commit: EOL
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/ContainersImplTomEE.java
----------------------------------------------------------------------
diff --git a/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/ContainersImplTomEE.java b/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/ContainersImplTomEE.java
index e4a71f5..9515459 100644
--- a/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/ContainersImplTomEE.java
+++ b/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/ContainersImplTomEE.java
@@ -1,169 +1,169 @@
-/*
- * 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.openejb.tck.impl;
-
-import org.apache.openejb.assembler.Deployer;
-import org.apache.openejb.assembler.classic.AppInfo;
-import org.apache.openejb.client.RemoteInitialContextFactory;
-import org.apache.openejb.config.RemoteServer;
-import org.apache.openejb.config.ValidationException;
-import org.apache.openejb.loader.Options;
-import org.apache.openejb.tck.OpenEJBTCKRuntimeException;
-import org.apache.openejb.tck.util.ServerLocal;
-import org.jboss.testharness.api.DeploymentException;
-import org.jboss.testharness.spi.Containers;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Arrays;
-import java.util.Properties;
-
-/**
- * @version $Rev$ $Date$
- */
-public class ContainersImplTomEE extends AbstractContainers implements Containers {
- private static int count = 0;
- private final RemoteServer server;
- private Deployer deployer = null;
- private Exception exception;
- private AppInfo appInfo;
- private File currentFile = null;
- private final int port = ServerLocal.getPort(8080);
-
- private Deployer lookup() {
- final Options options = new Options(System.getProperties());
- final Properties props = new Properties();
- props.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
- props.put(Context.PROVIDER_URL, options.get(Context.PROVIDER_URL, "http://localhost:" + port + "/tomee/ejb"));
-
- final String deployerJndi = System.getProperty("openejb.deployer.jndiname", "openejb/DeployerBusinessRemote");
-
- try {
- final InitialContext context = new InitialContext(props);
- return (Deployer) context.lookup(deployerJndi);
- } catch (final Exception e) {
- throw new OpenEJBTCKRuntimeException(e);
- }
- }
-
- public ContainersImplTomEE() {
- System.out.println("ContainersImpl=" + ContainersImplTomEE.class.getName());
- System.out.println("Initialized ContainersImplTomEE " + (++count));
- server = new RemoteServer();
- server.setPortStartup(this.port);
- }
-
- @Override
- public boolean deploy(final InputStream archive, final String name) throws IOException {
- exception = null;
- appInfo = null;
-
- System.out.println("Deploying " + archive + " with name " + name);
-
- currentFile = getFile(name);
- System.out.println(currentFile);
- writeToFile(currentFile, archive);
- try {
- if (deployer == null) {
- deployer = lookup();
- }
- appInfo = deployer.deploy(currentFile.getAbsolutePath());
- } catch (final Exception ex) {
- Exception e = ex;
- if (e.getCause() instanceof ValidationException) {
- e = (Exception) e.getCause();
- }
-
- if (name.contains(".broken.")) {
- // Tests that contain the name '.broken.' are expected to fail deployment
- // This is how the TCK verifies the container is doing the required error checking
- exception = (DeploymentException) new DeploymentException("deploy failed").initCause(e);
- } else {
- // This on the other hand is not good ....
- System.out.println("FIX Deployment of " + name);
- e.printStackTrace();
- exception = e;
- }
-
- return false;
- }
- return true;
- }
-
- @Override
- public DeploymentException getDeploymentException() {
- try {
- return (DeploymentException) exception;
- } catch (final Exception e) {
- System.out.println("BADCAST");
- return new DeploymentException("", exception);
- }
- }
-
- @Override
- public void undeploy(final String name) throws IOException {
- if (appInfo == null) {
- if (!(exception instanceof DeploymentException)) {
- System.out.println("Nothing to undeploy" + name);
- }
- return;
- }
-
- System.out.println("Undeploying " + name);
- try {
- deployer.undeploy(appInfo.path);
- } catch (final Exception e) {
- e.printStackTrace();
- throw new OpenEJBTCKRuntimeException(e);
- }
-
- final File toDelete;
- if (currentFile != null && (toDelete = currentFile.getParentFile()).exists()) {
- System.out.println("deleting " + toDelete.getAbsolutePath());
- delete(toDelete);
- }
- }
-
- protected File getFile(final String name) {
- final File dir = new File(tmpDir, Math.random() + "");
- if (!dir.exists() && !dir.mkdir()) {
- throw new RuntimeException("Failed to create directory: " + dir);
- }
- dir.deleteOnExit();
- return new File(dir, name);
- }
-
- @Override
- public void setup() throws IOException {
- System.out.println("Setup called");
- try {
- server.start(Arrays.asList("-Dopenejb.classloader.forced-load=org.apache.openejb.tck"), "start", true);
- } catch (final Exception e) {
- cleanup();
- e.printStackTrace();
- }
- }
-
- @Override
- public void cleanup() throws IOException {
- System.out.println("Cleanup called");
- server.destroy();
- }
-}
+/*
+ * 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.openejb.tck.impl;
+
+import org.apache.openejb.assembler.Deployer;
+import org.apache.openejb.assembler.classic.AppInfo;
+import org.apache.openejb.client.RemoteInitialContextFactory;
+import org.apache.openejb.config.RemoteServer;
+import org.apache.openejb.config.ValidationException;
+import org.apache.openejb.loader.Options;
+import org.apache.openejb.tck.OpenEJBTCKRuntimeException;
+import org.apache.openejb.tck.util.ServerLocal;
+import org.jboss.testharness.api.DeploymentException;
+import org.jboss.testharness.spi.Containers;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Properties;
+
+/**
+ * @version $Rev$ $Date$
+ */
+public class ContainersImplTomEE extends AbstractContainers implements Containers {
+ private static int count = 0;
+ private final RemoteServer server;
+ private Deployer deployer = null;
+ private Exception exception;
+ private AppInfo appInfo;
+ private File currentFile = null;
+ private final int port = ServerLocal.getPort(8080);
+
+ private Deployer lookup() {
+ final Options options = new Options(System.getProperties());
+ final Properties props = new Properties();
+ props.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
+ props.put(Context.PROVIDER_URL, options.get(Context.PROVIDER_URL, "http://localhost:" + port + "/tomee/ejb"));
+
+ final String deployerJndi = System.getProperty("openejb.deployer.jndiname", "openejb/DeployerBusinessRemote");
+
+ try {
+ final InitialContext context = new InitialContext(props);
+ return (Deployer) context.lookup(deployerJndi);
+ } catch (final Exception e) {
+ throw new OpenEJBTCKRuntimeException(e);
+ }
+ }
+
+ public ContainersImplTomEE() {
+ System.out.println("ContainersImpl=" + ContainersImplTomEE.class.getName());
+ System.out.println("Initialized ContainersImplTomEE " + (++count));
+ server = new RemoteServer();
+ server.setPortStartup(this.port);
+ }
+
+ @Override
+ public boolean deploy(final InputStream archive, final String name) throws IOException {
+ exception = null;
+ appInfo = null;
+
+ System.out.println("Deploying " + archive + " with name " + name);
+
+ currentFile = getFile(name);
+ System.out.println(currentFile);
+ writeToFile(currentFile, archive);
+ try {
+ if (deployer == null) {
+ deployer = lookup();
+ }
+ appInfo = deployer.deploy(currentFile.getAbsolutePath());
+ } catch (final Exception ex) {
+ Exception e = ex;
+ if (e.getCause() instanceof ValidationException) {
+ e = (Exception) e.getCause();
+ }
+
+ if (name.contains(".broken.")) {
+ // Tests that contain the name '.broken.' are expected to fail deployment
+ // This is how the TCK verifies the container is doing the required error checking
+ exception = (DeploymentException) new DeploymentException("deploy failed").initCause(e);
+ } else {
+ // This on the other hand is not good ....
+ System.out.println("FIX Deployment of " + name);
+ e.printStackTrace();
+ exception = e;
+ }
+
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public DeploymentException getDeploymentException() {
+ try {
+ return (DeploymentException) exception;
+ } catch (final Exception e) {
+ System.out.println("BADCAST");
+ return new DeploymentException("", exception);
+ }
+ }
+
+ @Override
+ public void undeploy(final String name) throws IOException {
+ if (appInfo == null) {
+ if (!(exception instanceof DeploymentException)) {
+ System.out.println("Nothing to undeploy" + name);
+ }
+ return;
+ }
+
+ System.out.println("Undeploying " + name);
+ try {
+ deployer.undeploy(appInfo.path);
+ } catch (final Exception e) {
+ e.printStackTrace();
+ throw new OpenEJBTCKRuntimeException(e);
+ }
+
+ final File toDelete;
+ if (currentFile != null && (toDelete = currentFile.getParentFile()).exists()) {
+ System.out.println("deleting " + toDelete.getAbsolutePath());
+ delete(toDelete);
+ }
+ }
+
+ protected File getFile(final String name) {
+ final File dir = new File(tmpDir, Math.random() + "");
+ if (!dir.exists() && !dir.mkdir()) {
+ throw new RuntimeException("Failed to create directory: " + dir);
+ }
+ dir.deleteOnExit();
+ return new File(dir, name);
+ }
+
+ @Override
+ public void setup() throws IOException {
+ System.out.println("Setup called");
+ try {
+ server.start(Arrays.asList("-Dopenejb.classloader.forced-load=org.apache.openejb.tck"), "start", true);
+ } catch (final Exception e) {
+ cleanup();
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void cleanup() throws IOException {
+ System.out.println("Cleanup called");
+ server.destroy();
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/FullRestartContainer.java
----------------------------------------------------------------------
diff --git a/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/FullRestartContainer.java b/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/FullRestartContainer.java
index f4d5cd1..7dab768 100644
--- a/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/FullRestartContainer.java
+++ b/tck/tck-common/src/main/java/org/apache/openejb/tck/impl/FullRestartContainer.java
@@ -1,137 +1,137 @@
-/*
- * 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.openejb.tck.impl;
-
-import org.apache.openejb.client.RemoteInitialContextFactory;
-import org.apache.openejb.config.RemoteServer;
-import org.apache.openejb.loader.Options;
-import org.apache.openejb.tck.OpenEJBTCKRuntimeException;
-import org.apache.openejb.tck.util.ServerLocal;
-import org.apache.tomee.catalina.facade.ExceptionManagerFacade;
-import org.jboss.testharness.api.DeploymentException;
-import org.jboss.testharness.spi.Containers;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-/**
- * flow:
- * - copy file
- * - start the server
- * - stop the server
- * - remove the file
- */
-public class FullRestartContainer extends AbstractContainers implements Containers {
- private static final File WEBAPP_DIR = new File(System.getProperty("openejb.home"), "webapps/");
- private static final File APPS_DIR = new File(System.getProperty("openejb.home"), "apps/");
-
- private RemoteServer server;
- private Exception exception;
- private File currentFile;
-
- public FullRestartContainer() {
- System.out.println("ContainersImpl=" + FullRestartContainer.class.getName());
- }
-
- @Override
- public DeploymentException getDeploymentException() {
- if (exception instanceof DeploymentException) {
- return (DeploymentException) exception;
- }
- System.out.println("BADCAST");
- return new DeploymentException("", exception);
- }
-
- @Override
- public boolean deploy(final InputStream archive, final String name) throws IOException {
- if (name.endsWith("war")) {
- currentFile = new File(WEBAPP_DIR, name);
- } else {
- currentFile = new File(APPS_DIR, name);
- }
-
- System.out.println(currentFile);
- writeToFile(currentFile, archive);
-
- final int port = ServerLocal.getPort(-1);
- if (port > 0) {
- server = new RemoteServer(100, true);
- server.setPortStartup(port);
- } else {
- throw new OpenEJBTCKRuntimeException("Please set the tomee port using the system property 'server.http.port'");
- }
-
- try {
- server.start();
- } catch (final Exception e) {
- server.destroy();
- e.printStackTrace();
- throw new RuntimeException(e);
- }
-
- return (exception = lookup().exception()) == null;
- }
-
- @Override
- public void undeploy(final String name) throws IOException {
-
- if (null != server) {
- server.destroy();
- }
-
- final File folder = new File(currentFile.getParentFile(), currentFile.getName().substring(0, currentFile.getName().length() - 4));
- if (folder.exists()) {
- delete(folder);
- }
- delete(currentFile);
- }
-
- @Override
- public void setup() throws IOException {
- // no-op
- }
-
- @Override
- public void cleanup() throws IOException {
- // no-op
- }
-
- private ExceptionManagerFacade lookup() {
- final Options options = new Options(System.getProperties());
- final Properties props = new Properties();
- props.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
- final int port = ServerLocal.getPort(-1);
- if (port > 0) {
- System.out.println("provider url = " + "http://localhost:" + port + "/tomee/ejb");
- props.put(Context.PROVIDER_URL, options.get(Context.PROVIDER_URL, "http://localhost:" + port + "/tomee/ejb"));
- } else {
- throw new OpenEJBTCKRuntimeException("Please set the tomee port using the system property 'server.http.port'");
- }
-
- try {
- final InitialContext context = new InitialContext(props);
- return (ExceptionManagerFacade) context.lookup("openejb/ExceptionManagerFacadeBusinessRemote");
- } catch (final Exception e) {
- throw new OpenEJBTCKRuntimeException(e);
- }
- }
-}
+/*
+ * 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.openejb.tck.impl;
+
+import org.apache.openejb.client.RemoteInitialContextFactory;
+import org.apache.openejb.config.RemoteServer;
+import org.apache.openejb.loader.Options;
+import org.apache.openejb.tck.OpenEJBTCKRuntimeException;
+import org.apache.openejb.tck.util.ServerLocal;
+import org.apache.tomee.catalina.facade.ExceptionManagerFacade;
+import org.jboss.testharness.api.DeploymentException;
+import org.jboss.testharness.spi.Containers;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * flow:
+ * - copy file
+ * - start the server
+ * - stop the server
+ * - remove the file
+ */
+public class FullRestartContainer extends AbstractContainers implements Containers {
+ private static final File WEBAPP_DIR = new File(System.getProperty("openejb.home"), "webapps/");
+ private static final File APPS_DIR = new File(System.getProperty("openejb.home"), "apps/");
+
+ private RemoteServer server;
+ private Exception exception;
+ private File currentFile;
+
+ public FullRestartContainer() {
+ System.out.println("ContainersImpl=" + FullRestartContainer.class.getName());
+ }
+
+ @Override
+ public DeploymentException getDeploymentException() {
+ if (exception instanceof DeploymentException) {
+ return (DeploymentException) exception;
+ }
+ System.out.println("BADCAST");
+ return new DeploymentException("", exception);
+ }
+
+ @Override
+ public boolean deploy(final InputStream archive, final String name) throws IOException {
+ if (name.endsWith("war")) {
+ currentFile = new File(WEBAPP_DIR, name);
+ } else {
+ currentFile = new File(APPS_DIR, name);
+ }
+
+ System.out.println(currentFile);
+ writeToFile(currentFile, archive);
+
+ final int port = ServerLocal.getPort(-1);
+ if (port > 0) {
+ server = new RemoteServer(100, true);
+ server.setPortStartup(port);
+ } else {
+ throw new OpenEJBTCKRuntimeException("Please set the tomee port using the system property 'server.http.port'");
+ }
+
+ try {
+ server.start();
+ } catch (final Exception e) {
+ server.destroy();
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+
+ return (exception = lookup().exception()) == null;
+ }
+
+ @Override
+ public void undeploy(final String name) throws IOException {
+
+ if (null != server) {
+ server.destroy();
+ }
+
+ final File folder = new File(currentFile.getParentFile(), currentFile.getName().substring(0, currentFile.getName().length() - 4));
+ if (folder.exists()) {
+ delete(folder);
+ }
+ delete(currentFile);
+ }
+
+ @Override
+ public void setup() throws IOException {
+ // no-op
+ }
+
+ @Override
+ public void cleanup() throws IOException {
+ // no-op
+ }
+
+ private ExceptionManagerFacade lookup() {
+ final Options options = new Options(System.getProperties());
+ final Properties props = new Properties();
+ props.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
+ final int port = ServerLocal.getPort(-1);
+ if (port > 0) {
+ System.out.println("provider url = " + "http://localhost:" + port + "/tomee/ejb");
+ props.put(Context.PROVIDER_URL, options.get(Context.PROVIDER_URL, "http://localhost:" + port + "/tomee/ejb"));
+ } else {
+ throw new OpenEJBTCKRuntimeException("Please set the tomee port using the system property 'server.http.port'");
+ }
+
+ try {
+ final InitialContext context = new InitialContext(props);
+ return (ExceptionManagerFacade) context.lookup("openejb/ExceptionManagerFacadeBusinessRemote");
+ } catch (final Exception e) {
+ throw new OpenEJBTCKRuntimeException(e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/tomee/apache-tomee/src/main/resources/service.bat
----------------------------------------------------------------------
diff --git a/tomee/apache-tomee/src/main/resources/service.bat b/tomee/apache-tomee/src/main/resources/service.bat
index b061f3f..457b4c0 100644
--- a/tomee/apache-tomee/src/main/resources/service.bat
+++ b/tomee/apache-tomee/src/main/resources/service.bat
@@ -1,226 +1,226 @@
-@echo off
-rem Licensed to the Apache Software Foundation (ASF) under one or more
-rem contributor license agreements. See the NOTICE file distributed with
-rem this work for additional information regarding copyright ownership.
-rem The ASF licenses this file to You under the Apache License, Version 2.0
-rem (the "License"); you may not use this file except in compliance with
-rem the License. You may obtain a copy of the License at
-rem
-rem http://www.apache.org/licenses/LICENSE-2.0
-rem
-rem Unless required by applicable law or agreed to in writing, software
-rem distributed under the License is distributed on an "AS IS" BASIS,
-rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-rem See the License for the specific language governing permissions and
-rem limitations under the License.
-
-rem The following line can be used to define a specific jre or jdk path
-rem set "JAVA_HOME=C:/JDK"
-
-REM Prefer a local JRE if we find one in the current bin directory
-IF EXIST "%~dp0jre" (
- SET "JRE_HOME=%~dp0jre"
-)
-
-REM Prefer a local JDK if we find one in the current bin directory
-IF EXIST "%~dp0jdk" (
- SET "JAVA_HOME=%~dp0jdk"
-)
-
-@IF NOT "%ECHO%" == "" ECHO %ECHO%
-@IF "%OS%" == "Windows_NT" setlocal
-
-IF "%OS%" == "Windows_NT" (
- SET "DIRNAME=%~dp0%"
-) ELSE (
- SET DIRNAME=.\
-)
-
-pushd %DIRNAME%
-
-rem ---------------------------------------------------------------------------
-rem NT Service Install/Uninstall script
-rem
-rem Options
-rem install Install the service using TomEE as service name.
-rem Service is installed using default settings.
-rem remove Remove the service from the System.
-rem
-rem name (optional) If the second argument is present it is considered
-rem to be new service name
-rem
-rem $Id: service.bat 1000718 2010-09-24 06:00:00Z mturk $
-rem ---------------------------------------------------------------------------
-
-SET proc=undefined
-
-IF /i %PROCESSOR_ARCHITECTURE% EQU X86 SET "proc=%~dp0TomEE.x86.exe"
-IF /i %PROCESSOR_ARCHITECTURE% EQU AMD64 SET "proc=%~dp0TomEE.amd64.exe"
-IF /i %PROCESSOR_ARCHITECTURE% EQU IA64 SET "proc=%~dp0TomEE.ia64.exe"
-
-IF /i "%proc%" EQU undefined (
- ECHO Failed to determine OS architecture
- GOTO end
-)
-
-set "SELF=%~dp0%service.bat"
-rem Guess CATALINA_HOME if not defined
-set "CURRENT_DIR=%cd%"
-if not "%CATALINA_HOME%" == "" goto gotHome
-set "CATALINA_HOME=%cd%"
-if exist "%CATALINA_HOME%\bin\service.bat" goto okHome
-rem CD to the upper dir
-cd ..
-set "CATALINA_HOME=%cd%"
-:gotHome
-if exist "%CATALINA_HOME%\bin\service.bat" goto okHome
-echo The service exe was not found...
-echo The CATALINA_HOME environment variable is not defined correctly.
-echo This environment variable is needed to run this program
-goto end
-:okHome
-rem Make sure prerequisite environment variables are set
-if not "%JAVA_HOME%" == "" goto gotJdkHome
-if not "%JRE_HOME%" == "" goto gotJreHome
-echo Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
-echo Service will try to guess them from the registry.
-goto okJavaHome
-:gotJreHome
-if not exist "%JRE_HOME%\bin\java.exe" goto noJavaHome
-if not exist "%JRE_HOME%\bin\javaw.exe" goto noJavaHome
-goto okJavaHome
-:gotJdkHome
-if not exist "%JAVA_HOME%\jre\bin\java.exe" goto noJavaHome
-if not exist "%JAVA_HOME%\jre\bin\javaw.exe" goto noJavaHome
-if not exist "%JAVA_HOME%\bin\javac.exe" goto noJavaHome
-if not "%JRE_HOME%" == "" goto okJavaHome
-set "JRE_HOME=%JAVA_HOME%\jre"
-goto okJavaHome
-:noJavaHome
-echo The JAVA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-echo NB: JAVA_HOME should point to a JDK not a JRE
-goto end
-:okJavaHome
-if not "%CATALINA_BASE%" == "" goto gotBase
-set "CATALINA_BASE=%CATALINA_HOME%"
-:gotBase
-
-set "EXECUTABLE=%proc%"
-
-rem Set default Service name (If you change this then rename also TomEE.exe to the same name)
-set SERVICE_NAME=TomEE
-set PR_DISPLAYNAME=Apache TomEE
-
-if "x%1x" == "xx" goto displayUsage
-set SERVICE_CMD=%1
-shift
-if "x%1x" == "xx" goto checkServiceCmd
-:checkUser
-if "x%1x" == "x/userx" goto runAsUser
-if "x%1x" == "x--userx" goto runAsUser
-set SERVICE_NAME=%1
-set PR_DISPLAYNAME=Apache TomEE (%1)
-shift
-if "x%1x" == "xx" goto checkServiceCmd
-goto checkUser
-:runAsUser
-shift
-if "x%1x" == "xx" goto displayUsage
-set SERVICE_USER=%1
-shift
-runas /env /savecred /user:%SERVICE_USER% "%COMSPEC% /K \"%SELF%\" %SERVICE_CMD% %SERVICE_NAME%"
-goto end
-:checkServiceCmd
-if /i %SERVICE_CMD% == install goto doInstall
-if /i %SERVICE_CMD% == remove goto doRemove
-if /i %SERVICE_CMD% == uninstall goto doRemove
-echo Unknown parameter "%1"
-:displayUsage
-echo.
-echo Usage: service.bat install/remove [service_name] [/user username]
-goto end
-
-:doRemove
-rem Remove the service
-"%EXECUTABLE%" //DS//%SERVICE_NAME%
-if not errorlevel 1 goto removed
-echo Failed removing '%SERVICE_NAME%' service
-goto end
-:removed
-echo The service '%SERVICE_NAME%' has been removed
-goto end
-
-:doInstall
-rem Install the service
-echo Installing the service '%SERVICE_NAME%' ...
-echo Using CATALINA_HOME: "%CATALINA_HOME%"
-echo Using CATALINA_BASE: "%CATALINA_BASE%"
-echo Using JAVA_HOME: "%JAVA_HOME%"
-echo Using JRE_HOME: "%JRE_HOME%"
-
-rem Use the environment variables as an example
-rem Each command line option is prefixed with PR_
-
-set "PR_DESCRIPTION=Apache TomEE - http://tomee.apache.org/"
-set "PR_INSTALL=%EXECUTABLE%"
-set "PR_LOGPATH=%CATALINA_BASE%\logs"
-set "PR_CLASSPATH=%CATALINA_HOME%\bin\bootstrap.jar;%CATALINA_BASE%\bin\tomcat-juli.jar;%CATALINA_HOME%\bin\tomcat-juli.jar"
-rem Set the server jvm from JAVA_HOME
-set "PR_JVM=%JRE_HOME%\bin\server\jvm.dll"
-if exist "%PR_JVM%" goto foundJvm
-rem Set the client jvm from JAVA_HOME
-set "PR_JVM=%JRE_HOME%\bin\client\jvm.dll"
-if exist "%PR_JVM%" goto foundJvm
-set PR_JVM=auto
-:foundJvm
-echo Using JVM: "%PR_JVM%"
-
-"%EXECUTABLE%" //IS//%SERVICE_NAME% ^
- --DisplayName=%SERVICE_NAME% ^
- --StartClass org.apache.catalina.startup.Bootstrap ^
- --StopClass org.apache.catalina.startup.Bootstrap ^
- --StartParams start ^
- --StopParams stop ^
- --Startup auto ^
- --JvmMs=512 ^
- --JvmMx=1024 ^
- --JvmSs=2048 ^
- --StartMode jvm ^
- --StopMode jvm ^
- --LogLevel Info ^
- --LogPrefix TomEE
-
-echo Installed, will now configure TomEE
-
-if not errorlevel 1 goto installed
-echo Failed installing '%SERVICE_NAME%' service
-goto end
-
-:installed
-rem Clear the environment variables. They are not needed any more.
-set PR_DISPLAYNAME=
-set PR_DESCRIPTION=
-set PR_INSTALL=
-set PR_LOGPATH=
-set PR_CLASSPATH=
-set PR_JVM=
-
-rem Set extra parameters
-"%EXECUTABLE%" //US//%SERVICE_NAME% ^
- ++JvmOptions "-javaagent:%CATALINA_HOME%\lib\openejb-javaagent.jar;-Dcatalina.base=%CATALINA_BASE%;-Dcatalina.home=%CATALINA_HOME%;-Djava.endorsed.dirs=%CATALINA_HOME%\endorsed"
-
-rem More extra parameters
-set "PR_LOGPATH=%CATALINA_BASE%\logs"
-set PR_STDOUTPUT=auto
-set PR_STDERROR=auto
-
-rem before this option was added: "++JvmOptions=-Djava.library.path="%CATALINA_BASE%\bin" ^"
-rem the drawback was it was preventing custom native lib to be loaded even if added to Path
-"%EXECUTABLE%" //US//%SERVICE_NAME% ^
- ++JvmOptions "-Djava.io.tmpdir=%CATALINA_BASE%\temp;-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager;-Djava.util.logging.config.file=%CATALINA_BASE%\conf\logging.properties;-Djava.awt.headless=true;-XX:+UseParallelGC;-XX:MaxPermSize=256M"
-
-echo The service '%SERVICE_NAME%' has been installed.
-
-:end
-cd "%CURRENT_DIR%"
+@echo off
+rem Licensed to the Apache Software Foundation (ASF) under one or more
+rem contributor license agreements. See the NOTICE file distributed with
+rem this work for additional information regarding copyright ownership.
+rem The ASF licenses this file to You under the Apache License, Version 2.0
+rem (the "License"); you may not use this file except in compliance with
+rem the License. You may obtain a copy of the License at
+rem
+rem http://www.apache.org/licenses/LICENSE-2.0
+rem
+rem Unless required by applicable law or agreed to in writing, software
+rem distributed under the License is distributed on an "AS IS" BASIS,
+rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+rem See the License for the specific language governing permissions and
+rem limitations under the License.
+
+rem The following line can be used to define a specific jre or jdk path
+rem set "JAVA_HOME=C:/JDK"
+
+REM Prefer a local JRE if we find one in the current bin directory
+IF EXIST "%~dp0jre" (
+ SET "JRE_HOME=%~dp0jre"
+)
+
+REM Prefer a local JDK if we find one in the current bin directory
+IF EXIST "%~dp0jdk" (
+ SET "JAVA_HOME=%~dp0jdk"
+)
+
+@IF NOT "%ECHO%" == "" ECHO %ECHO%
+@IF "%OS%" == "Windows_NT" setlocal
+
+IF "%OS%" == "Windows_NT" (
+ SET "DIRNAME=%~dp0%"
+) ELSE (
+ SET DIRNAME=.\
+)
+
+pushd %DIRNAME%
+
+rem ---------------------------------------------------------------------------
+rem NT Service Install/Uninstall script
+rem
+rem Options
+rem install Install the service using TomEE as service name.
+rem Service is installed using default settings.
+rem remove Remove the service from the System.
+rem
+rem name (optional) If the second argument is present it is considered
+rem to be new service name
+rem
+rem $Id: service.bat 1000718 2010-09-24 06:00:00Z mturk $
+rem ---------------------------------------------------------------------------
+
+SET proc=undefined
+
+IF /i %PROCESSOR_ARCHITECTURE% EQU X86 SET "proc=%~dp0TomEE.x86.exe"
+IF /i %PROCESSOR_ARCHITECTURE% EQU AMD64 SET "proc=%~dp0TomEE.amd64.exe"
+IF /i %PROCESSOR_ARCHITECTURE% EQU IA64 SET "proc=%~dp0TomEE.ia64.exe"
+
+IF /i "%proc%" EQU undefined (
+ ECHO Failed to determine OS architecture
+ GOTO end
+)
+
+set "SELF=%~dp0%service.bat"
+rem Guess CATALINA_HOME if not defined
+set "CURRENT_DIR=%cd%"
+if not "%CATALINA_HOME%" == "" goto gotHome
+set "CATALINA_HOME=%cd%"
+if exist "%CATALINA_HOME%\bin\service.bat" goto okHome
+rem CD to the upper dir
+cd ..
+set "CATALINA_HOME=%cd%"
+:gotHome
+if exist "%CATALINA_HOME%\bin\service.bat" goto okHome
+echo The service exe was not found...
+echo The CATALINA_HOME environment variable is not defined correctly.
+echo This environment variable is needed to run this program
+goto end
+:okHome
+rem Make sure prerequisite environment variables are set
+if not "%JAVA_HOME%" == "" goto gotJdkHome
+if not "%JRE_HOME%" == "" goto gotJreHome
+echo Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
+echo Service will try to guess them from the registry.
+goto okJavaHome
+:gotJreHome
+if not exist "%JRE_HOME%\bin\java.exe" goto noJavaHome
+if not exist "%JRE_HOME%\bin\javaw.exe" goto noJavaHome
+goto okJavaHome
+:gotJdkHome
+if not exist "%JAVA_HOME%\jre\bin\java.exe" goto noJavaHome
+if not exist "%JAVA_HOME%\jre\bin\javaw.exe" goto noJavaHome
+if not exist "%JAVA_HOME%\bin\javac.exe" goto noJavaHome
+if not "%JRE_HOME%" == "" goto okJavaHome
+set "JRE_HOME=%JAVA_HOME%\jre"
+goto okJavaHome
+:noJavaHome
+echo The JAVA_HOME environment variable is not defined correctly
+echo This environment variable is needed to run this program
+echo NB: JAVA_HOME should point to a JDK not a JRE
+goto end
+:okJavaHome
+if not "%CATALINA_BASE%" == "" goto gotBase
+set "CATALINA_BASE=%CATALINA_HOME%"
+:gotBase
+
+set "EXECUTABLE=%proc%"
+
+rem Set default Service name (If you change this then rename also TomEE.exe to the same name)
+set SERVICE_NAME=TomEE
+set PR_DISPLAYNAME=Apache TomEE
+
+if "x%1x" == "xx" goto displayUsage
+set SERVICE_CMD=%1
+shift
+if "x%1x" == "xx" goto checkServiceCmd
+:checkUser
+if "x%1x" == "x/userx" goto runAsUser
+if "x%1x" == "x--userx" goto runAsUser
+set SERVICE_NAME=%1
+set PR_DISPLAYNAME=Apache TomEE (%1)
+shift
+if "x%1x" == "xx" goto checkServiceCmd
+goto checkUser
+:runAsUser
+shift
+if "x%1x" == "xx" goto displayUsage
+set SERVICE_USER=%1
+shift
+runas /env /savecred /user:%SERVICE_USER% "%COMSPEC% /K \"%SELF%\" %SERVICE_CMD% %SERVICE_NAME%"
+goto end
+:checkServiceCmd
+if /i %SERVICE_CMD% == install goto doInstall
+if /i %SERVICE_CMD% == remove goto doRemove
+if /i %SERVICE_CMD% == uninstall goto doRemove
+echo Unknown parameter "%1"
+:displayUsage
+echo.
+echo Usage: service.bat install/remove [service_name] [/user username]
+goto end
+
+:doRemove
+rem Remove the service
+"%EXECUTABLE%" //DS//%SERVICE_NAME%
+if not errorlevel 1 goto removed
+echo Failed removing '%SERVICE_NAME%' service
+goto end
+:removed
+echo The service '%SERVICE_NAME%' has been removed
+goto end
+
+:doInstall
+rem Install the service
+echo Installing the service '%SERVICE_NAME%' ...
+echo Using CATALINA_HOME: "%CATALINA_HOME%"
+echo Using CATALINA_BASE: "%CATALINA_BASE%"
+echo Using JAVA_HOME: "%JAVA_HOME%"
+echo Using JRE_HOME: "%JRE_HOME%"
+
+rem Use the environment variables as an example
+rem Each command line option is prefixed with PR_
+
+set "PR_DESCRIPTION=Apache TomEE - http://tomee.apache.org/"
+set "PR_INSTALL=%EXECUTABLE%"
+set "PR_LOGPATH=%CATALINA_BASE%\logs"
+set "PR_CLASSPATH=%CATALINA_HOME%\bin\bootstrap.jar;%CATALINA_BASE%\bin\tomcat-juli.jar;%CATALINA_HOME%\bin\tomcat-juli.jar"
+rem Set the server jvm from JAVA_HOME
+set "PR_JVM=%JRE_HOME%\bin\server\jvm.dll"
+if exist "%PR_JVM%" goto foundJvm
+rem Set the client jvm from JAVA_HOME
+set "PR_JVM=%JRE_HOME%\bin\client\jvm.dll"
+if exist "%PR_JVM%" goto foundJvm
+set PR_JVM=auto
+:foundJvm
+echo Using JVM: "%PR_JVM%"
+
+"%EXECUTABLE%" //IS//%SERVICE_NAME% ^
+ --DisplayName=%SERVICE_NAME% ^
+ --StartClass org.apache.catalina.startup.Bootstrap ^
+ --StopClass org.apache.catalina.startup.Bootstrap ^
+ --StartParams start ^
+ --StopParams stop ^
+ --Startup auto ^
+ --JvmMs=512 ^
+ --JvmMx=1024 ^
+ --JvmSs=2048 ^
+ --StartMode jvm ^
+ --StopMode jvm ^
+ --LogLevel Info ^
+ --LogPrefix TomEE
+
+echo Installed, will now configure TomEE
+
+if not errorlevel 1 goto installed
+echo Failed installing '%SERVICE_NAME%' service
+goto end
+
+:installed
+rem Clear the environment variables. They are not needed any more.
+set PR_DISPLAYNAME=
+set PR_DESCRIPTION=
+set PR_INSTALL=
+set PR_LOGPATH=
+set PR_CLASSPATH=
+set PR_JVM=
+
+rem Set extra parameters
+"%EXECUTABLE%" //US//%SERVICE_NAME% ^
+ ++JvmOptions "-javaagent:%CATALINA_HOME%\lib\openejb-javaagent.jar;-Dcatalina.base=%CATALINA_BASE%;-Dcatalina.home=%CATALINA_HOME%;-Djava.endorsed.dirs=%CATALINA_HOME%\endorsed"
+
+rem More extra parameters
+set "PR_LOGPATH=%CATALINA_BASE%\logs"
+set PR_STDOUTPUT=auto
+set PR_STDERROR=auto
+
+rem before this option was added: "++JvmOptions=-Djava.library.path="%CATALINA_BASE%\bin" ^"
+rem the drawback was it was preventing custom native lib to be loaded even if added to Path
+"%EXECUTABLE%" //US//%SERVICE_NAME% ^
+ ++JvmOptions "-Djava.io.tmpdir=%CATALINA_BASE%\temp;-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager;-Djava.util.logging.config.file=%CATALINA_BASE%\conf\logging.properties;-Djava.awt.headless=true;-XX:+UseParallelGC;-XX:MaxPermSize=256M"
+
+echo The service '%SERVICE_NAME%' has been installed.
+
+:end
+cd "%CURRENT_DIR%"
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/tomee/apache-tomee/src/main/resources/tomee.bat
----------------------------------------------------------------------
diff --git a/tomee/apache-tomee/src/main/resources/tomee.bat b/tomee/apache-tomee/src/main/resources/tomee.bat
index a945bbd..6c6045e 100644
--- a/tomee/apache-tomee/src/main/resources/tomee.bat
+++ b/tomee/apache-tomee/src/main/resources/tomee.bat
@@ -1,85 +1,85 @@
-@echo off
-rem Licensed to the Apache Software Foundation (ASF) under one or more
-rem contributor license agreements. See the NOTICE file distributed with
-rem this work for additional information regarding copyright ownership.
-rem The ASF licenses this file to You under the Apache License, Version 2.0
-rem (the "License"); you may not use this file except in compliance with
-rem the License. You may obtain a copy of the License at
-rem
-rem http://www.apache.org/licenses/LICENSE-2.0
-rem
-rem Unless required by applicable law or agreed to in writing, software
-rem distributed under the License is distributed on an "AS IS" BASIS,
-rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-rem See the License for the specific language governing permissions and
-rem limitations under the License.
-
-if "%OS%" == "Windows_NT" setlocal
-
-set port=8080
-
-rem Guess CATALINA_HOME if not defined
-set "CURRENT_DIR=%cd%"
-if not "%CATALINA_HOME%" == "" goto gotHome
-set "CATALINA_HOME=%CURRENT_DIR%"
-if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
-cd ..
-set "CATALINA_HOME=%cd%"
-cd "%CURRENT_DIR%"
-:gotHome
-
-if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
-echo The CATALINA_HOME environment variable is not defined correctly
-echo This environment variable is needed to run this program
-goto end
-:okHome
-
-rem Copy CATALINA_BASE from CATALINA_HOME if not defined
-if not "%CATALINA_BASE%" == "" goto gotBase
-set "CATALINA_BASE=%CATALINA_HOME%"
-:gotBase
-
-rem Ensure that any user defined CLASSPATH variables are not used on startup,
-rem but allow them to be specified in setenv.bat, in rare case when it is needed.
-set CLASSPATH=
-
-rem Get standard Java environment variables
-if exist "%CATALINA_HOME%\bin\setclasspath.bat" goto okSetclasspath
-echo Cannot find "%CATALINA_HOME%\bin\setclasspath.bat"
-echo This file is needed to run this program
-goto end
-:okSetclasspath
-call "%CATALINA_HOME%\bin\setclasspath.bat" %1
-if errorlevel 1 goto end
-
-
-if not "%CATALINA_TMPDIR%" == "" goto gotTmpdir
-set "CATALINA_TMPDIR=%CATALINA_BASE%\temp"
-:gotTmpdir
-
-
-rem create classpath
-setlocal enabledelayedexpansion
-
-set cp="%CATALINA_HOME%\bin\tomcat-juli.jar"
-set lib="%CATALINA_HOME%\lib\"
-echo %lib%
-for %%F in (%lib%/*.jar) do (
- set cp=!cp!;%%F%
-)
-
-if ""%1"" == ""deploy"" goto doDeploy
-if ""%1"" == ""undeploy"" goto doUndeploy
-goto doExec
-
-:doDeploy
-:doUndeploy
-%_RUNJAVA% -cp "%cp%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" org.apache.openejb.cli.Bootstrap %1 -s http://localhost:%port%/tomee/ejb %2
-goto end
-
-:doExec
-%_RUNJAVA% -cp "%cp%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" org.apache.openejb.cli.Bootstrap %*
-goto end
-
-:end
-
+@echo off
+rem Licensed to the Apache Software Foundation (ASF) under one or more
+rem contributor license agreements. See the NOTICE file distributed with
+rem this work for additional information regarding copyright ownership.
+rem The ASF licenses this file to You under the Apache License, Version 2.0
+rem (the "License"); you may not use this file except in compliance with
+rem the License. You may obtain a copy of the License at
+rem
+rem http://www.apache.org/licenses/LICENSE-2.0
+rem
+rem Unless required by applicable law or agreed to in writing, software
+rem distributed under the License is distributed on an "AS IS" BASIS,
+rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+rem See the License for the specific language governing permissions and
+rem limitations under the License.
+
+if "%OS%" == "Windows_NT" setlocal
+
+set port=8080
+
+rem Guess CATALINA_HOME if not defined
+set "CURRENT_DIR=%cd%"
+if not "%CATALINA_HOME%" == "" goto gotHome
+set "CATALINA_HOME=%CURRENT_DIR%"
+if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
+cd ..
+set "CATALINA_HOME=%cd%"
+cd "%CURRENT_DIR%"
+:gotHome
+
+if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
+echo The CATALINA_HOME environment variable is not defined correctly
+echo This environment variable is needed to run this program
+goto end
+:okHome
+
+rem Copy CATALINA_BASE from CATALINA_HOME if not defined
+if not "%CATALINA_BASE%" == "" goto gotBase
+set "CATALINA_BASE=%CATALINA_HOME%"
+:gotBase
+
+rem Ensure that any user defined CLASSPATH variables are not used on startup,
+rem but allow them to be specified in setenv.bat, in rare case when it is needed.
+set CLASSPATH=
+
+rem Get standard Java environment variables
+if exist "%CATALINA_HOME%\bin\setclasspath.bat" goto okSetclasspath
+echo Cannot find "%CATALINA_HOME%\bin\setclasspath.bat"
+echo This file is needed to run this program
+goto end
+:okSetclasspath
+call "%CATALINA_HOME%\bin\setclasspath.bat" %1
+if errorlevel 1 goto end
+
+
+if not "%CATALINA_TMPDIR%" == "" goto gotTmpdir
+set "CATALINA_TMPDIR=%CATALINA_BASE%\temp"
+:gotTmpdir
+
+
+rem create classpath
+setlocal enabledelayedexpansion
+
+set cp="%CATALINA_HOME%\bin\tomcat-juli.jar"
+set lib="%CATALINA_HOME%\lib\"
+echo %lib%
+for %%F in (%lib%/*.jar) do (
+ set cp=!cp!;%%F%
+)
+
+if ""%1"" == ""deploy"" goto doDeploy
+if ""%1"" == ""undeploy"" goto doUndeploy
+goto doExec
+
+:doDeploy
+:doUndeploy
+%_RUNJAVA% -cp "%cp%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" org.apache.openejb.cli.Bootstrap %1 -s http://localhost:%port%/tomee/ejb %2
+goto end
+
+:doExec
+%_RUNJAVA% -cp "%cp%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" org.apache.openejb.cli.Bootstrap %*
+goto end
+
+:end
+
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/Contexts.java
----------------------------------------------------------------------
diff --git a/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/Contexts.java b/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/Contexts.java
index 78434d0..dd8a6b1 100644
--- a/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/Contexts.java
+++ b/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/Contexts.java
@@ -1,148 +1,148 @@
-/*
- * 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.tomee.catalina;
-
-import org.apache.catalina.Container;
-import org.apache.catalina.Context;
-import org.apache.catalina.Globals;
-import org.apache.catalina.Host;
-import org.apache.catalina.core.StandardContext;
-import org.apache.catalina.core.StandardEngine;
-import org.apache.catalina.core.StandardHost;
-import org.apache.catalina.util.ContextName;
-
-import java.io.File;
-
-public class Contexts {
- public static String getHostname(final StandardContext ctx) {
- String hostName = null;
- final Container parentHost = ctx.getParent();
- if (parentHost != null) {
- hostName = parentHost.getName();
- }
- if ((hostName == null) || (hostName.length() < 1)) {
- hostName = "_";
- }
- return hostName;
- }
-
- public static File warPath(final Context standardContext) {
- final File file = realWarPath(standardContext);
- if (file == null) {
- return null;
- }
-
- final String name = file.getName();
- if (!file.isDirectory() && name.endsWith(".war")) {
- final File extracted = new File(file.getParentFile(), name.substring(0, name.length() - ".war".length()));
- if (extracted.exists()) {
- return extracted;
- }
- }
- return file;
- }
-
- public static File realWarPath(final Context standardContext) {
- if (standardContext == null) {
- return null;
- }
-
- final File docBase;
- Container container = standardContext;
- while (container != null) {
- if (container instanceof Host) {
- break;
- }
- container = container.getParent();
- }
-
- if (standardContext.getDocBase() != null) {
- File file = new File(standardContext.getDocBase());
- if (!file.isAbsolute()) {
- if (container == null) {
- docBase = new File(engineBase(standardContext), standardContext.getDocBase());
- } else {
- final String appBase = ((Host) container).getAppBase();
- file = new File(appBase);
- if (!file.isAbsolute()) {
- file = new File(engineBase(standardContext), appBase);
- }
- docBase = new File(file, standardContext.getDocBase());
- }
- } else {
- docBase = file;
- }
- } else {
- final String path = standardContext.getPath();
- if (path == null) {
- throw new IllegalStateException("Can't find docBase");
- } else {
- docBase = new File(new ContextName(path, standardContext.getWebappVersion()).getBaseName());
- }
- }
-
- if (!docBase.exists()) { // for old compatibility, will be removed soon
- return oldRealWarPath(standardContext);
- }
-
- final String name = docBase.getName();
- if (name.endsWith(".war")) {
- final File extracted = new File(docBase.getParentFile(), name.substring(0, name.length() - ".war".length()));
- if (extracted.exists()) {
- return extracted;
- }
- }
-
- return docBase;
- }
-
- private static File engineBase(final Context standardContext) {
- String base=System.getProperty(Globals.CATALINA_BASE_PROP);
- if( base == null ) {
- final StandardEngine eng = (StandardEngine) standardContext.getParent().getParent();
- base = eng.getBaseDir();
- }
- return new File(base);
- }
-
- @Deprecated
- private static File oldRealWarPath(final Context standardContext) {
- String doc = standardContext.getDocBase();
- // handle ROOT case
- if (doc == null || doc.length() == 0) {
- doc = "ROOT";
- }
-
- File war = new File(doc);
- if (war.exists()) {
- return war;
- }
-
- final StandardHost host = (StandardHost) standardContext.getParent();
- final String base = host.getAppBase();
- war = new File(base, doc);
- if (war.exists()) {
- return war;
- }
-
- war = new File(new File(System.getProperty("catalina.home"), base), doc);
- if (war.exists()) {
- return war;
- }
- return new File(new File(System.getProperty("catalina.base"), base), doc); // shouldn't occur
- }
-}
+/*
+ * 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.tomee.catalina;
+
+import org.apache.catalina.Container;
+import org.apache.catalina.Context;
+import org.apache.catalina.Globals;
+import org.apache.catalina.Host;
+import org.apache.catalina.core.StandardContext;
+import org.apache.catalina.core.StandardEngine;
+import org.apache.catalina.core.StandardHost;
+import org.apache.catalina.util.ContextName;
+
+import java.io.File;
+
+public class Contexts {
+ public static String getHostname(final StandardContext ctx) {
+ String hostName = null;
+ final Container parentHost = ctx.getParent();
+ if (parentHost != null) {
+ hostName = parentHost.getName();
+ }
+ if ((hostName == null) || (hostName.length() < 1)) {
+ hostName = "_";
+ }
+ return hostName;
+ }
+
+ public static File warPath(final Context standardContext) {
+ final File file = realWarPath(standardContext);
+ if (file == null) {
+ return null;
+ }
+
+ final String name = file.getName();
+ if (!file.isDirectory() && name.endsWith(".war")) {
+ final File extracted = new File(file.getParentFile(), name.substring(0, name.length() - ".war".length()));
+ if (extracted.exists()) {
+ return extracted;
+ }
+ }
+ return file;
+ }
+
+ public static File realWarPath(final Context standardContext) {
+ if (standardContext == null) {
+ return null;
+ }
+
+ final File docBase;
+ Container container = standardContext;
+ while (container != null) {
+ if (container instanceof Host) {
+ break;
+ }
+ container = container.getParent();
+ }
+
+ if (standardContext.getDocBase() != null) {
+ File file = new File(standardContext.getDocBase());
+ if (!file.isAbsolute()) {
+ if (container == null) {
+ docBase = new File(engineBase(standardContext), standardContext.getDocBase());
+ } else {
+ final String appBase = ((Host) container).getAppBase();
+ file = new File(appBase);
+ if (!file.isAbsolute()) {
+ file = new File(engineBase(standardContext), appBase);
+ }
+ docBase = new File(file, standardContext.getDocBase());
+ }
+ } else {
+ docBase = file;
+ }
+ } else {
+ final String path = standardContext.getPath();
+ if (path == null) {
+ throw new IllegalStateException("Can't find docBase");
+ } else {
+ docBase = new File(new ContextName(path, standardContext.getWebappVersion()).getBaseName());
+ }
+ }
+
+ if (!docBase.exists()) { // for old compatibility, will be removed soon
+ return oldRealWarPath(standardContext);
+ }
+
+ final String name = docBase.getName();
+ if (name.endsWith(".war")) {
+ final File extracted = new File(docBase.getParentFile(), name.substring(0, name.length() - ".war".length()));
+ if (extracted.exists()) {
+ return extracted;
+ }
+ }
+
+ return docBase;
+ }
+
+ private static File engineBase(final Context standardContext) {
+ String base=System.getProperty(Globals.CATALINA_BASE_PROP);
+ if( base == null ) {
+ final StandardEngine eng = (StandardEngine) standardContext.getParent().getParent();
+ base = eng.getBaseDir();
+ }
+ return new File(base);
+ }
+
+ @Deprecated
+ private static File oldRealWarPath(final Context standardContext) {
+ String doc = standardContext.getDocBase();
+ // handle ROOT case
+ if (doc == null || doc.length() == 0) {
+ doc = "ROOT";
+ }
+
+ File war = new File(doc);
+ if (war.exists()) {
+ return war;
+ }
+
+ final StandardHost host = (StandardHost) standardContext.getParent();
+ final String base = host.getAppBase();
+ war = new File(base, doc);
+ if (war.exists()) {
+ return war;
+ }
+
+ war = new File(new File(System.getProperty("catalina.home"), base), doc);
+ if (war.exists()) {
+ return war;
+ }
+ return new File(new File(System.getProperty("catalina.base"), base), doc); // shouldn't occur
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/ProvisioningWebappLoader.java
----------------------------------------------------------------------
diff --git a/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/ProvisioningWebappLoader.java b/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/ProvisioningWebappLoader.java
index 1357bcc..ab6fc11 100644
--- a/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/ProvisioningWebappLoader.java
+++ b/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/ProvisioningWebappLoader.java
@@ -1,119 +1,119 @@
-/*
- * 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.tomee.catalina;
-
-import org.apache.catalina.Context;
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.loader.VirtualWebappLoader;
-import org.apache.openejb.ClassLoaderUtil;
-import org.apache.openejb.classloader.ClassLoaderConfigurer;
-import org.apache.openejb.classloader.CompositeClassLoaderConfigurer;
-import org.apache.openejb.config.QuickJarsTxtParser;
-import org.apache.openejb.loader.ProvisioningUtil;
-import org.apache.openejb.loader.SystemInstance;
-import org.apache.openejb.util.reflection.Reflections;
-
-import java.io.File;
-
-/**
- * Usage example in META-INF/context.xml
- * <p/>
- * <p/>
- * <Context antiJARLocking="true" >
- * <Loader
- * className="org.apache.tomee.catalina.ProvisioningWebappLoader"
- * searchExternalFirst="true"
- * virtualClasspath="mvn:commons-el:commons-el:1.0;mvn:commons-el:commons-el:1.0"
- * searchVirtualFirst="true"
- * />
- * </Context>
- */
-public class ProvisioningWebappLoader extends VirtualWebappLoader {
- public static final boolean SKIP_BACKGROUND_PROCESS = "true".equals(SystemInstance.get().getProperty("tomee.classloader.skip-background-process", "false"));
-
- @Override
- public void backgroundProcess() {
- if (SKIP_BACKGROUND_PROCESS) {
- return;
- }
-
- final ClassLoader classloader = super.getClassLoader();
- if (classloader instanceof LazyStopWebappClassLoader) {
- final LazyStopWebappClassLoader lazyStopWebappClassLoader = (LazyStopWebappClassLoader) classloader;
- lazyStopWebappClassLoader.restarting();
- try {
- super.backgroundProcess();
- } finally {
- lazyStopWebappClassLoader.restarted();
- }
- } else {
- super.backgroundProcess();
- }
- }
-
- @Override
- public boolean modified() {
- if (SKIP_BACKGROUND_PROCESS) {
- return false;
- }
- return super.modified();
- }
-
- @Override
- protected void startInternal() throws LifecycleException {
- // standard tomcat part
- final StringBuilder builder = new StringBuilder();
- final String classpath = String.class.cast(Reflections.get(this, "virtualClasspath"));
- if (classpath != null && !classpath.isEmpty()) {
- for (final String s : String.class.cast(classpath).split(";")) {
- builder.append(ProvisioningUtil.realLocation(s)).append(";");
- }
- }
-
- ClassLoaderConfigurer configurer = ClassLoaderUtil.configurer(getContainer().getName());
-
- // WEB-INF/jars.xml
- if (Context.class.isInstance(getContainer())) {
- final File war = Contexts.warPath(Context.class.cast(getContainer()));
- final File jarsXml = new File(war, "WEB-INF/" + QuickJarsTxtParser.FILE_NAME);
- final ClassLoaderConfigurer configurerTxt = QuickJarsTxtParser.parse(jarsXml);
- if (configurerTxt != null) {
- configurer = new CompositeClassLoaderConfigurer(configurer, configurerTxt);
- }
- }
-
- // clean up builder and set classpath to delegate to parent init
- String cp = builder.toString();
- if (cp.endsWith(";")) {
- cp = cp.substring(0, cp.length() - 1);
- }
- Reflections.set(this, "virtualClasspath", cp);
-
- LazyStopWebappClassLoader.initContext(configurer);
- LazyStopWebappClassLoader.initContext(Context.class.cast(getContainer()));
- try {
- super.startInternal();
- } finally {
- LazyStopWebappClassLoader.cleanContext();
- }
- }
-
- @Override
- public String toString() {
- return "Provisioning" + super.toString();
- }
-}
+/*
+ * 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.tomee.catalina;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.LifecycleException;
+import org.apache.catalina.loader.VirtualWebappLoader;
+import org.apache.openejb.ClassLoaderUtil;
+import org.apache.openejb.classloader.ClassLoaderConfigurer;
+import org.apache.openejb.classloader.CompositeClassLoaderConfigurer;
+import org.apache.openejb.config.QuickJarsTxtParser;
+import org.apache.openejb.loader.ProvisioningUtil;
+import org.apache.openejb.loader.SystemInstance;
+import org.apache.openejb.util.reflection.Reflections;
+
+import java.io.File;
+
+/**
+ * Usage example in META-INF/context.xml
+ * <p/>
+ * <p/>
+ * <Context antiJARLocking="true" >
+ * <Loader
+ * className="org.apache.tomee.catalina.ProvisioningWebappLoader"
+ * searchExternalFirst="true"
+ * virtualClasspath="mvn:commons-el:commons-el:1.0;mvn:commons-el:commons-el:1.0"
+ * searchVirtualFirst="true"
+ * />
+ * </Context>
+ */
+public class ProvisioningWebappLoader extends VirtualWebappLoader {
+ public static final boolean SKIP_BACKGROUND_PROCESS = "true".equals(SystemInstance.get().getProperty("tomee.classloader.skip-background-process", "false"));
+
+ @Override
+ public void backgroundProcess() {
+ if (SKIP_BACKGROUND_PROCESS) {
+ return;
+ }
+
+ final ClassLoader classloader = super.getClassLoader();
+ if (classloader instanceof LazyStopWebappClassLoader) {
+ final LazyStopWebappClassLoader lazyStopWebappClassLoader = (LazyStopWebappClassLoader) classloader;
+ lazyStopWebappClassLoader.restarting();
+ try {
+ super.backgroundProcess();
+ } finally {
+ lazyStopWebappClassLoader.restarted();
+ }
+ } else {
+ super.backgroundProcess();
+ }
+ }
+
+ @Override
+ public boolean modified() {
+ if (SKIP_BACKGROUND_PROCESS) {
+ return false;
+ }
+ return super.modified();
+ }
+
+ @Override
+ protected void startInternal() throws LifecycleException {
+ // standard tomcat part
+ final StringBuilder builder = new StringBuilder();
+ final String classpath = String.class.cast(Reflections.get(this, "virtualClasspath"));
+ if (classpath != null && !classpath.isEmpty()) {
+ for (final String s : String.class.cast(classpath).split(";")) {
+ builder.append(ProvisioningUtil.realLocation(s)).append(";");
+ }
+ }
+
+ ClassLoaderConfigurer configurer = ClassLoaderUtil.configurer(getContainer().getName());
+
+ // WEB-INF/jars.xml
+ if (Context.class.isInstance(getContainer())) {
+ final File war = Contexts.warPath(Context.class.cast(getContainer()));
+ final File jarsXml = new File(war, "WEB-INF/" + QuickJarsTxtParser.FILE_NAME);
+ final ClassLoaderConfigurer configurerTxt = QuickJarsTxtParser.parse(jarsXml);
+ if (configurerTxt != null) {
+ configurer = new CompositeClassLoaderConfigurer(configurer, configurerTxt);
+ }
+ }
+
+ // clean up builder and set classpath to delegate to parent init
+ String cp = builder.toString();
+ if (cp.endsWith(";")) {
+ cp = cp.substring(0, cp.length() - 1);
+ }
+ Reflections.set(this, "virtualClasspath", cp);
+
+ LazyStopWebappClassLoader.initContext(configurer);
+ LazyStopWebappClassLoader.initContext(Context.class.cast(getContainer()));
+ try {
+ super.startInternal();
+ } finally {
+ LazyStopWebappClassLoader.cleanContext();
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "Provisioning" + super.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/tomee/tomee-common/src/main/java/org/apache/tomee/common/NamingUtil.java
----------------------------------------------------------------------
diff --git a/tomee/tomee-common/src/main/java/org/apache/tomee/common/NamingUtil.java b/tomee/tomee-common/src/main/java/org/apache/tomee/common/NamingUtil.java
index 0bdceff..b452c3e 100644
--- a/tomee/tomee-common/src/main/java/org/apache/tomee/common/NamingUtil.java
+++ b/tomee/tomee-common/src/main/java/org/apache/tomee/common/NamingUtil.java
@@ -1,149 +1,149 @@
-/**
- *
- * 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.tomee.common;
-
-import org.apache.catalina.core.StandardContext;
-import org.apache.naming.EjbRef;
-
-import javax.naming.RefAddr;
-import javax.naming.Reference;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class NamingUtil {
- public static final String NAME = "name";
- public static final String DEPLOYMENT_ID = "deploymentid";
- public static final String EXTERNAL = "external";
- public static final String LOCAL = "local";
- public static final String LOCALBEAN = "localbean";
- public static final String REMOTE = EjbRef.REMOTE;
- public static final String JNDI_NAME = "jndiname";
- public static final String JNDI_PROVIDER_ID = "jndiproviderid";
- public static final String UNIT = "unit";
- public static final String EXTENDED = "extended";
- public static final String PROPERTIES = "properties";
- public static final String RESOURCE_ID = "resourceid";
- public static final String COMPONENT_TYPE = "componenttype";
- public static final String WS_ID = "wsid";
- public static final String WS_CLASS = "wsclass";
- public static final String WS_QNAME = "wsqname";
- public static final String WS_PORT_QNAME = "wsportqname";
- public static final String WSDL_URL = "wsdlurl";
-
- private static final AtomicInteger id = new AtomicInteger(31);
- private static final Map<String,Object> registry = new ConcurrentHashMap<String, Object>();
-
- // these two attributes are used to be able to cleanup quickly the registry (otherwise we need to duplicate a lot of logic)
- private static StandardContext currentContext;
- private static final Map<StandardContext, Collection<String>> ID_BY_CONTEXT = new HashMap<StandardContext, Collection<String>>();
-
- public static String getProperty(final Reference ref, final String name) {
- final RefAddr addr = ref.get(name);
- if (addr == null) {
- return null;
- }
- final Object value = addr.getContent();
- return (String) value;
- }
-
- public static boolean isPropertyTrue(final Reference ref, final String name) {
- final RefAddr addr = ref.get(name);
- if (addr == null) {
- return false;
- }
- final Object value = addr.getContent();
- return Boolean.parseBoolean(String.valueOf(value));
- }
-
- public static void setStaticValue(final Resource resource, final Object value) {
- setStaticValue(resource, null, value);
- }
-
- public static void setStaticValue(final Resource resource, final String name, final Object value) {
- final String token = String.valueOf(id.incrementAndGet());
- registry.put(token, value);
- resource.setProperty("static-token" + (name != null ? "-" + name : ""), token);
- if (currentContext != null) {
- Collection<String> ids = ID_BY_CONTEXT.get(currentContext);
- if (ids == null) {
- ids = new ArrayList<String>();
- ID_BY_CONTEXT.put(currentContext, ids);
- }
- ids.add(token);
- }
- }
-
- @SuppressWarnings({"unchecked"})
- public static<T> T getStaticValue(final Reference ref) {
- return (T) getStaticValue(ref, null);
- }
-
- @SuppressWarnings({"unchecked"})
- public static <T> T getStaticValue(final Reference ref, String name) {
- name = name != null ? "-" + name : "";
- final String token = getProperty(ref, "static-token" + name);
- if (token == null) {
- return null;
- }
- return (T) registry.get(token);
- }
-
- public static Class<?> loadClass(final String className) {
- if (className == null) {
- return null;
- }
- try {
- final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- if (classLoader != null) {
- try {
- return classLoader.loadClass(className);
- } catch(final ClassNotFoundException e) {
- // no-op
- }
- }
- return Class.forName(className);
- } catch (final ClassNotFoundException e) {
- return null;
- }
- }
-
- /**
- * This interface exists because the class org.apache.catalina.deploy.ContextResource
- * is not available in the common classloader in tomcat 55
- */
- public interface Resource {
- void setProperty(String name, Object value);
- }
-
- public static void setCurrentContext(final StandardContext currentContext) {
- NamingUtil.currentContext = currentContext;
- }
-
- public static void cleanUpContextResource(final StandardContext context) {
- final Collection<String> keys = ID_BY_CONTEXT.remove(context);
- if (keys != null) {
- for (final String k : keys) {
- registry.remove(k);
- }
- }
- }
-}
+/**
+ *
+ * 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.tomee.common;
+
+import org.apache.catalina.core.StandardContext;
+import org.apache.naming.EjbRef;
+
+import javax.naming.RefAddr;
+import javax.naming.Reference;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class NamingUtil {
+ public static final String NAME = "name";
+ public static final String DEPLOYMENT_ID = "deploymentid";
+ public static final String EXTERNAL = "external";
+ public static final String LOCAL = "local";
+ public static final String LOCALBEAN = "localbean";
+ public static final String REMOTE = EjbRef.REMOTE;
+ public static final String JNDI_NAME = "jndiname";
+ public static final String JNDI_PROVIDER_ID = "jndiproviderid";
+ public static final String UNIT = "unit";
+ public static final String EXTENDED = "extended";
+ public static final String PROPERTIES = "properties";
+ public static final String RESOURCE_ID = "resourceid";
+ public static final String COMPONENT_TYPE = "componenttype";
+ public static final String WS_ID = "wsid";
+ public static final String WS_CLASS = "wsclass";
+ public static final String WS_QNAME = "wsqname";
+ public static final String WS_PORT_QNAME = "wsportqname";
+ public static final String WSDL_URL = "wsdlurl";
+
+ private static final AtomicInteger id = new AtomicInteger(31);
+ private static final Map<String,Object> registry = new ConcurrentHashMap<String, Object>();
+
+ // these two attributes are used to be able to cleanup quickly the registry (otherwise we need to duplicate a lot of logic)
+ private static StandardContext currentContext;
+ private static final Map<StandardContext, Collection<String>> ID_BY_CONTEXT = new HashMap<StandardContext, Collection<String>>();
+
+ public static String getProperty(final Reference ref, final String name) {
+ final RefAddr addr = ref.get(name);
+ if (addr == null) {
+ return null;
+ }
+ final Object value = addr.getContent();
+ return (String) value;
+ }
+
+ public static boolean isPropertyTrue(final Reference ref, final String name) {
+ final RefAddr addr = ref.get(name);
+ if (addr == null) {
+ return false;
+ }
+ final Object value = addr.getContent();
+ return Boolean.parseBoolean(String.valueOf(value));
+ }
+
+ public static void setStaticValue(final Resource resource, final Object value) {
+ setStaticValue(resource, null, value);
+ }
+
+ public static void setStaticValue(final Resource resource, final String name, final Object value) {
+ final String token = String.valueOf(id.incrementAndGet());
+ registry.put(token, value);
+ resource.setProperty("static-token" + (name != null ? "-" + name : ""), token);
+ if (currentContext != null) {
+ Collection<String> ids = ID_BY_CONTEXT.get(currentContext);
+ if (ids == null) {
+ ids = new ArrayList<String>();
+ ID_BY_CONTEXT.put(currentContext, ids);
+ }
+ ids.add(token);
+ }
+ }
+
+ @SuppressWarnings({"unchecked"})
+ public static<T> T getStaticValue(final Reference ref) {
+ return (T) getStaticValue(ref, null);
+ }
+
+ @SuppressWarnings({"unchecked"})
+ public static <T> T getStaticValue(final Reference ref, String name) {
+ name = name != null ? "-" + name : "";
+ final String token = getProperty(ref, "static-token" + name);
+ if (token == null) {
+ return null;
+ }
+ return (T) registry.get(token);
+ }
+
+ public static Class<?> loadClass(final String className) {
+ if (className == null) {
+ return null;
+ }
+ try {
+ final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+ if (classLoader != null) {
+ try {
+ return classLoader.loadClass(className);
+ } catch(final ClassNotFoundException e) {
+ // no-op
+ }
+ }
+ return Class.forName(className);
+ } catch (final ClassNotFoundException e) {
+ return null;
+ }
+ }
+
+ /**
+ * This interface exists because the class org.apache.catalina.deploy.ContextResource
+ * is not available in the common classloader in tomcat 55
+ */
+ public interface Resource {
+ void setProperty(String name, Object value);
+ }
+
+ public static void setCurrentContext(final StandardContext currentContext) {
+ NamingUtil.currentContext = currentContext;
+ }
+
+ public static void cleanUpContextResource(final StandardContext context) {
+ final Collection<String> keys = ID_BY_CONTEXT.remove(context);
+ if (keys != null) {
+ for (final String k : keys) {
+ registry.remove(k);
+ }
+ }
+ }
+}
[10/12] tomee git commit: EOL
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractTomEEMojo.java
----------------------------------------------------------------------
diff --git a/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractTomEEMojo.java b/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractTomEEMojo.java
index 2ebfbd9..2290e36 100644
--- a/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractTomEEMojo.java
+++ b/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractTomEEMojo.java
@@ -1,1363 +1,1363 @@
-/*
- * 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.openejb.maven.plugin;
-
-import org.apache.maven.artifact.Artifact;
-import org.apache.maven.artifact.factory.ArtifactFactory;
-import org.apache.maven.artifact.repository.ArtifactRepository;
-import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
-import org.apache.maven.artifact.repository.DefaultArtifactRepository;
-import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
-import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
-import org.apache.maven.artifact.resolver.ArtifactResolutionException;
-import org.apache.maven.artifact.resolver.ArtifactResolver;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
-import org.apache.maven.plugins.annotations.Component;
-import org.apache.maven.plugins.annotations.Parameter;
-import org.apache.maven.project.MavenProject;
-import org.apache.maven.settings.Settings;
-import org.apache.openejb.OpenEJBRuntimeException;
-import org.apache.openejb.config.RemoteServer;
-import org.apache.openejb.loader.Files;
-import org.apache.openejb.loader.IO;
-import org.apache.openejb.loader.Zips;
-import org.apache.openejb.maven.plugin.cli.Args;
-import org.apache.openejb.util.Join;
-import org.apache.openejb.util.NetworkUtil;
-import org.apache.openejb.util.OpenEjbVersion;
-import org.apache.tomee.util.QuickServerXmlParser;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.Closeable;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Scanner;
-import java.util.concurrent.CountDownLatch;
-import java.util.logging.SimpleFormatter;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-import static org.apache.maven.artifact.Artifact.SCOPE_COMPILE;
-import static org.apache.maven.artifact.repository.ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN;
-import static org.apache.maven.artifact.repository.ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY;
-import static org.apache.maven.artifact.repository.ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER;
-import static org.apache.maven.artifact.versioning.VersionRange.createFromVersion;
-import static org.apache.openejb.util.JarExtractor.delete;
-import static org.codehaus.plexus.util.FileUtils.deleteDirectory;
-import static org.codehaus.plexus.util.IOUtil.close;
-import static org.codehaus.plexus.util.IOUtil.copy;
-
-public abstract class AbstractTomEEMojo extends AbstractAddressMojo {
- // if we get let say > 5 patterns like it we should create a LocationAnalyzer
- // for < 5 patterns it should be fine
- private static final String NAME_STR = "?name=";
- private static final String UNZIP_PREFIX = "unzip:";
- private static final String REMOVE_PREFIX = "remove:";
- public static final String QUIT_CMD = "quit";
- public static final String EXIT_CMD = "exit";
- public static final String TOM_EE = "TomEE";
-
- @Component
- protected ArtifactFactory factory;
-
- @Component
- protected ArtifactResolver resolver;
-
- @Parameter(defaultValue = "${localRepository}", readonly = true)
- protected ArtifactRepository local;
-
- @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true)
- protected List<ArtifactRepository> remoteRepos;
-
- @Parameter(property = "tomee-plugin.skipCurrentProject", defaultValue = "false")
- protected boolean skipCurrentProject;
-
- @Parameter(property = "tomee-plugin.version", defaultValue = "-1")
- protected String tomeeVersion;
-
- @Parameter(property = "tomee-plugin.groupId", defaultValue = "org.apache.openejb")
- protected String tomeeGroupId;
-
- @Parameter(property = "tomee-plugin.artifactId", defaultValue = "apache-tomee")
- protected String tomeeArtifactId;
-
- /**
- * while tar.gz is not managed it is readonly
- */
- @Parameter(property = "tomee-plugin.type", defaultValue = "zip", readonly = true)
- protected String tomeeType;
-
- @Parameter(property = "tomee-plugin.apache-repos", defaultValue = "snapshots")
- protected String apacheRepos;
-
- @Parameter(property = "tomee-plugin.classifier", defaultValue = "webprofile")
- protected String tomeeClassifier;
-
- @Parameter(property = "tomee-plugin.shutdown", defaultValue = "8005")
- protected int tomeeShutdownPort;
-
- @Parameter(property = "tomee-plugin.shutdown.attempts", defaultValue = "60")
- protected int tomeeShutdownAttempts;
-
- @Parameter(property = "tomee-plugin.shutdown-command", defaultValue = "SHUTDOWN")
- protected String tomeeShutdownCommand;
-
- @Parameter(property = "tomee-plugin.ajp", defaultValue = "8009")
- protected int tomeeAjpPort;
-
- @Parameter(property = "tomee-plugin.https")
- protected Integer tomeeHttpsPort;
-
- @Parameter(property = "tomee-plugin.args")
- protected String args;
-
- @Parameter(property = "tomee-plugin.debug", defaultValue = "false")
- protected boolean debug;
-
- @Parameter(property = "tomee-plugin.simple-log", defaultValue = "false")
- protected boolean simpleLog;
-
- @Parameter(property = "tomee-plugin.debugPort", defaultValue = "5005")
- protected int debugPort;
-
- @Parameter(defaultValue = "${project.basedir}/src/main/webapp", property = "tomee-plugin.webappResources")
- protected File webappResources;
-
- @Parameter(defaultValue = "${project.build.outputDirectory}", property = "tomee-plugin.webappClasses")
- protected File webappClasses;
-
- @Parameter(defaultValue = "${project.build.directory}/apache-tomee", property = "tomee-plugin.catalina-base")
- protected File catalinaBase;
-
- /**
- * rename the current artifact
- */
- @Parameter
- protected String context;
-
- /**
- * relative to tomee.base.
- */
- @Parameter(defaultValue = "webapps")
- protected String webappDir;
-
- /**
- * relative to tomee.base.
- */
- @Parameter(defaultValue = "apps")
- protected String appDir;
-
- /**
- * relative to tomee.base.
- */
- @Parameter(defaultValue = "lib")
- protected String libDir;
-
- @Parameter(defaultValue = "${project.basedir}/src/main")
- protected File mainDir;
-
- @Parameter(defaultValue = "${project.build.directory}")
- protected File target;
-
- @Parameter(property = "tomee-plugin.conf", defaultValue = "${project.basedir}/src/main/tomee/conf")
- protected File config;
-
- @Parameter(property = "tomee-plugin.bin", defaultValue = "${project.basedir}/src/main/tomee/bin")
- protected File bin;
-
- @Parameter(property = "tomee-plugin.lib", defaultValue = "${project.basedir}/src/main/tomee/lib")
- protected File lib;
-
- @Parameter
- protected Map<String, String> systemVariables;
-
- @Parameter
- private List<String> classpaths;
-
- /**
- * forcing nice default for war development (WEB-INF/classes and web resources)
- */
- @Parameter(property = "tomee-plugin.webappDefaultConfig", defaultValue = "false")
- protected boolean webappDefaultConfig;
-
- /**
- * use a real random instead of secure random. saves few ms at startup.
- */
- @Parameter(property = "tomee-plugin.quick-session", defaultValue = "true")
- protected boolean quickSession;
-
- @Parameter
- protected List<String> customizers;
-
- @Parameter(defaultValue = "${project}", readonly = true, required = true)
- protected MavenProject project;
-
- /**
- * force webapp to be reloadable
- */
- @Parameter(property = "tomee-plugin.force-reloadable", defaultValue = "false")
- protected boolean forceReloadable;
-
- /**
- * supported formats:
- * --> groupId:artifactId:version...
- * --> unzip:groupId:artifactId:version...
- * --> remove:prefix (often prefix = artifactId)
- */
- @Parameter
- protected List<String> libs;
-
- @Parameter
- protected List<String> endorsedLibs;
-
- @Parameter
- protected List<String> javaagents;
-
- @Parameter(property = "tomee-plugin.persist-javaagents", defaultValue = "false")
- protected boolean persistJavaagents;
-
- @Parameter
- protected List<String> webapps;
-
- @Parameter
- protected List<String> apps;
-
- @Parameter(property = "tomee-plugin.classes", defaultValue = "${project.build.outputDirectory}", readonly = true)
- protected File classes;
-
- @Parameter(defaultValue = "${project.build.directory}/${project.build.finalName}.${project.packaging}")
- protected File warFile;
-
- @Parameter(property = "tomee-plugin.remove-default-webapps", defaultValue = "true")
- protected boolean removeDefaultWebapps;
-
- @Parameter(property = "tomee-plugin.deploy-openejb-internal-application", defaultValue = "false")
- protected boolean deployOpenEjbApplication;
-
- @Parameter(property = "tomee-plugin.remove-tomee-webapps", defaultValue = "true")
- protected boolean removeTomeeWebapp;
-
- @Parameter(property = "tomee-plugin.ejb-remote", defaultValue = "true")
- protected boolean ejbRemote;
-
- @Parameter(defaultValue = "${project.packaging}", readonly = true)
- protected String packaging;
-
- @Parameter(property = "tomee-plugin.keep-server-xml", defaultValue = "false")
- protected boolean keepServerXmlAsthis;
-
- @Parameter(property = "tomee-plugin.check-started", defaultValue = "false")
- protected boolean checkStarted;
-
- @Parameter(property = "tomee-plugin.use-console", defaultValue = "true")
- protected boolean useConsole;
-
- @Parameter(property = "tomee-plugin.exiting", defaultValue = "false")
- protected boolean tomeeAlreadyInstalled;
-
- /**
- * The current user system settings for use in Maven.
- */
- @Parameter(defaultValue = "${settings}", readonly = true)
- protected Settings settings;
-
- /**
- * use openejb-standalone automatically instead of TomEE
- */
- @Parameter(property = "tomee-plugin.openejb", defaultValue = "false")
- protected boolean useOpenEJB;
-
- /**
- * for TomEE and wars only, which docBase to use for this war.
- */
- @Parameter
- protected List<File> docBases;
-
- /**
- * for TomEE and wars only, add some external repositories to classloader.
- */
- @Parameter
- protected List<File> externalRepositories;
-
- /**
- * when you set docBases to src/main/webapp setting it to true will allow hot refresh.
- */
- @Parameter(property = "tomee-plugin.skipWarResources", defaultValue = "false")
- protected boolean skipWarResources = false;
-
- protected File deployedFile = null;
- protected RemoteServer server = null;
- protected String container = TOM_EE;
-
- @Override
- public void execute() throws MojoExecutionException, MojoFailureException {
- fixConfig();
-
- if ("-1".equals(tomeeVersion)) {
- final String version = OpenEjbVersion.get().getVersion();
- tomeeVersion = "1" + version.substring(1, version.length());
- }
-
- if (!tomeeAlreadyInstalled) {
- final Collection<String> existingWebapps; // added before using the plugin with maven dependency plugin or sthg like that
- if (removeDefaultWebapps) {
- existingWebapps = webappsAlreadyAdded();
- } else {
- existingWebapps = Collections.emptyList();
- }
-
- unzip(resolve());
- if (removeDefaultWebapps) { // do it first to let add other war
- removeDefaultWebapps(removeTomeeWebapp, existingWebapps);
- }
- copyLibs(libs, new File(catalinaBase, libDir), "jar");
- copyLibs(endorsedLibs, new File(catalinaBase, "endorsed"), "jar");
- copyLibs(webapps, new File(catalinaBase, webappDir), "war");
- copyLibs(apps, new File(catalinaBase, appDir), "jar");
- overrideConf(config, "conf");
- overrideConf(lib, "lib");
- final Collection<File> copied = overrideConf(bin, "bin");
-
- for (final File copy : copied) {
- if (copy.getName().endsWith(".bat") || copy.getName().endsWith(".sh")) {
- if (!copy.setExecutable(true)) {
- getLog().warn("can't make " + copy.getPath() + " executable");
- }
- }
- }
-
- if (classpaths == null) { // NPE protection for activateSimpleLog() and run()
- classpaths = new ArrayList<String>();
- }
- if (simpleLog) {
- activateSimpleLog();
- }
-
- if (!keepServerXmlAsthis) {
- overrideAddresses();
- }
- if (!skipCurrentProject) {
- copyWar();
- }
-
- if (customizers != null) {
- final Thread thread = Thread.currentThread();
- final ClassLoader currentLoader = thread.getContextClassLoader();
- final ClassLoader tccl = createClassLoader(currentLoader);
- thread.setContextClassLoader(tccl);
- try {
- // a customizer is a Runnable with or without a constructor taking a File as parameter (catalina base)
- // one goal is to avoid coupling as much as possible with this plugin
- //
- // if really needed we could introduce a Customizer interface but then it has more impacts on your packaging/config
- for (final String customizer : customizers) {
- try {
- final Class<?> clazz = tccl.loadClass(customizer);
- try {
- final Constructor<?> cons = clazz.getConstructor(File.class);
- Runnable.class.cast(cons.newInstance(catalinaBase)).run();
- } catch (final NoSuchMethodException e) {
- try {
- Runnable.class.cast(clazz.newInstance()).run();
- } catch (final Exception e1) {
- throw new MojoExecutionException("can't create customizer: " + currentLoader, e);
- }
- }
- } catch (final ClassNotFoundException e) {
- throw new MojoExecutionException("can't find customizer: " + currentLoader, e);
- } catch (final InvocationTargetException e) {
- throw new MojoExecutionException("can't create customizer: " + currentLoader, e);
- } catch (final InstantiationException e) {
- throw new MojoExecutionException("can't create customizer: " + currentLoader, e);
- } catch (final IllegalAccessException e) {
- throw new MojoExecutionException("can't create customizer: " + currentLoader, e);
- }
- }
- } finally {
- try {
- if (tccl != null && Closeable.class.isInstance(tccl)) {
- Closeable.class.cast(tccl).close();
- }
- } catch (final IOException e) {
- // no-op
- }
- thread.setContextClassLoader(currentLoader);
- }
- }
- }
-
- run();
- }
-
- @SuppressWarnings("unchecked")
- private ClassLoader createClassLoader(final ClassLoader parent) {
- final List<URL> urls = new ArrayList<URL>();
- for (final Artifact artifact : (Collection<Artifact>) project.getArtifacts()) {
- try {
- urls.add(artifact.getFile().toURI().toURL());
- } catch (final MalformedURLException e) {
- getLog().warn("can't use artifact " + artifact.toString());
- }
- }
- if (classes != null && classes.exists()) {
- try {
- urls.add(classes.toURI().toURL());
- } catch (final MalformedURLException e) {
- getLog().warn("can't use path " + classes.getAbsolutePath());
- }
- }
- return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
- }
-
- protected void fixConfig() {
- if (useOpenEJB) {
- tomeeGroupId = "org.apache.openejb";
- tomeeArtifactId = "openejb-standalone";
- tomeeClassifier = null;
- tomeeShutdownCommand = "Q";
- if (8005 == tomeeShutdownPort) { // default admin port
- tomeeShutdownPort = 4200;
- }
- if (tomeeVersion.startsWith("1.")) {
- tomeeVersion = OpenEjbVersion.get().getVersion();
- }
-
- if (catalinaBase.getName().equals("apache-tomee") && catalinaBase.getParentFile().equals(target)) {
- catalinaBase = new File(target, "apache-openejb");
- }
- if (config.getParentFile().getName().equals("tomee") && config.getParentFile().getParentFile().equals(mainDir)) {
- config = new File(mainDir, "openejb/conf");
- }
- if (lib.getParentFile().getName().equals("tomee") && lib.getParentFile().getParentFile().equals(mainDir)) {
- lib = new File(mainDir, "openejb/lib");
- }
- if (bin.getParentFile().getName().equals("tomee") && bin.getParentFile().getParentFile().equals(mainDir)) {
- bin = new File(mainDir, "openejb/bin");
- }
- }
- }
-
- protected String getAdditionalClasspath() {
- if (!classpaths.isEmpty()) {
- final StringBuilder cpBuilder = new StringBuilder();
- for (final String cp : classpaths) {
- cpBuilder.append(cp);
- cpBuilder.append(File.pathSeparatorChar);
- }
- return cpBuilder.substring(0, cpBuilder.length() - 1); // Dump the final path separator
- }
- return null;
- }
-
- private List<String> webappsAlreadyAdded() {
- final List<String> list = new ArrayList<String>();
- final File webapps = new File(catalinaBase, webappDir);
- if (webapps.exists() && webapps.isDirectory()) {
- final File[] files = webapps.listFiles();
- if (files != null) {
- for (final File f : files) {
- list.add(f.getName());
- }
- }
- }
- return list;
- }
-
- private void activateSimpleLog() {
- // replacing java.util.logging.SimpleFormatter by SimpleTomEEFormatter
- final File loggingProperties = new File(catalinaBase, "conf/logging.properties");
- if (loggingProperties.exists() && !new File(config, "conf/logging.properties").exists()) {
- try {
- String content = IO.slurp(loggingProperties);
- if (!content.contains("java.util.logging.ConsoleHandler.formatter")) {
- content += System.getProperty("line.separator") + "java.util.logging.ConsoleHandler.formatter = org.apache.tomee.jul.formatter.SimpleTomEEFormatter";
- } else {
- content = content.replace(SimpleFormatter.class.getName(), "org.apache.tomee.jul.formatter.SimpleTomEEFormatter");
- }
-
- doWrite(loggingProperties, content);
- } catch (final Exception e) {
- getLog().error("Can't set SimpleTomEEFormatter", e);
- }
- }
- }
-
- private void removeDefaultWebapps(final boolean removeTomee, final Collection<String> providedWebapps) {
- final File webapps = new File(catalinaBase, webappDir);
- if (webapps.isDirectory()) {
- final File[] files = webapps.listFiles();
- if (null != files) {
- for (final File webapp : files) {
- final String name = webapp.getName();
- if (webapp.isDirectory() && !providedWebapps.contains(name) && (removeTomee || !name.equals("tomee"))) {
- try {
- deleteDirectory(webapp);
- } catch (final IOException ignored) {
- // no-op
- }
- }
- }
- }
- }
-
- getLog().info("Removed not mandatory default webapps");
- }
-
- private void copyLibs(final List<String> files, final File destParent, final String defaultType) {
- if (files == null || files.isEmpty()) {
- return;
- }
-
- if (!destParent.exists() && !destParent.mkdirs()) {
- getLog().warn("can't create '" + destParent.getPath() + "'");
- }
-
- for (final String file : files) {
- updateLib(file, destParent, defaultType);
- }
- }
-
- private void updateLib(final String rawLib, final File destParent, final String defaultType) {
- InputStream is = null;
- OutputStream os = null;
-
- // special hook to get more info
- String lib = rawLib;
- String extractedName = null;
- if (lib.contains(NAME_STR)) {
- lib = lib.substring(0, rawLib.indexOf(NAME_STR));
- extractedName = rawLib.substring(rawLib.indexOf(NAME_STR) + NAME_STR.length(), rawLib.length());
- if (!extractedName.endsWith(".jar") && !extractedName.endsWith(".war")
- && !extractedName.endsWith(".ear") && !extractedName.endsWith(".rar")) {
- extractedName = extractedName + "." + defaultType;
- }
- }
-
- boolean unzip = false;
- if (lib.startsWith(UNZIP_PREFIX)) {
- lib = lib.substring(UNZIP_PREFIX.length());
- unzip = true;
- }
-
- if (lib.startsWith(REMOVE_PREFIX)) {
- final String prefix = lib.substring(REMOVE_PREFIX.length());
- final File[] files = destParent.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(final File dir, final String name) {
- return name.startsWith(prefix);
- }
- });
- if (files != null) {
- for (final File file : files) {
- if (!IO.delete(file)) {
- file.deleteOnExit();
- }
- getLog().info("Deleted " + file.getPath());
- }
- }
- } else {
- try {
- final File file = mvnToFile(lib, defaultType);
- if (!unzip) {
- final File dest;
- if (extractedName == null) {
- dest = new File(destParent, file.getName());
- } else {
- dest = new File(destParent, extractedName);
- }
-
- is = new BufferedInputStream(new FileInputStream(file));
- os = new BufferedOutputStream(new FileOutputStream(dest));
- copy(is, os);
-
- getLog().info("Copied '" + lib + "' in '" + dest.getAbsolutePath());
- } else {
- Zips.unzip(file, destParent, true);
-
- getLog().info("Unzipped '" + lib + "' in '" + destParent.getAbsolutePath());
- }
- } catch (final Exception e) {
- getLog().error(e.getMessage(), e);
- throw new TomEEException(e.getMessage(), e);
- } finally {
- close(is);
- close(os);
- }
- }
- }
-
- private File mvnToFile(final String lib, final String defaultType) throws ArtifactResolutionException, ArtifactNotFoundException {
- final String[] infos = lib.split(":");
- final String classifier;
- final String type;
- if (infos.length < 3) {
- throw new TomEEException("format for librairies should be <groupId>:<artifactId>:<version>[:<type>[:<classifier>]]");
- }
- if (infos.length >= 4) {
- type = infos[3];
- } else {
- type = defaultType;
- }
- if (infos.length == 5) {
- classifier = infos[4];
- } else {
- classifier = null;
- }
-
- final Artifact artifact = factory.createDependencyArtifact(infos[0], infos[1], createFromVersion(infos[2]), type, classifier, SCOPE_COMPILE);
- resolver.resolve(artifact, remoteRepos, local);
- return artifact.getFile();
- }
-
- private void copyWar() {
- if ("pom".equals(packaging)) {
- return;
- }
-
- final boolean war = "war".equals(packaging);
- final String name = destinationName();
- final File out;
- if (war) {
- out = new File(catalinaBase, webappDir + "/" + name);
- } else {
- final File parent = new File(catalinaBase, appDir);
- if (!parent.exists() && !parent.mkdirs()) {
- getLog().warn("can't create '" + parent.getPath() + "'");
- }
- out = new File(parent, name);
- }
- delete(out);
- if (!warFile.isDirectory() && name.endsWith("." + packaging)) {
- final String dir = name.substring(0, name.lastIndexOf('.'));
- final File unpacked;
- if (war) {
- unpacked = new File(catalinaBase, webappDir + "/" + dir);
- } else {
- unpacked = new File(catalinaBase, appDir + "/" + dir);
- }
- delete(unpacked);
- }
-
- if (warFile.exists() && warFile.isDirectory()) {
- try {
- IO.copyDirectory(warFile, out);
- } catch (final IOException e) {
- throw new TomEEException(e.getMessage(), e);
- }
- } else if (warFile.exists()) {
- InputStream is = null;
- OutputStream os = null;
- try {
- is = new FileInputStream(warFile);
- os = new FileOutputStream(out);
- copy(is, os);
-
- getLog().info("Installed '" + warFile.getAbsolutePath() + "' in " + out.getAbsolutePath());
- } catch (final Exception e) {
- throw new TomEEException(e.getMessage(), e);
- } finally {
- close(is);
- close(os);
- }
- } else {
- getLog().warn("'" + warFile + "' doesn't exist, ignoring (maybe run mvn package before this plugin)");
- }
-
- deployedFile = out;
- }
-
- protected String destinationName() {
- if (context != null) {
- if (!context.contains(".") && !warFile.isDirectory()) {
- return context + "." + packaging;
- }
- return context;
- }
- return warFile.getName();
- }
-
- private void overrideAddresses() {
- final File serverXml = new File(catalinaBase, "conf/server.xml");
- if (!serverXml.exists()) { // openejb
- return;
- }
-
- final QuickServerXmlParser parser = QuickServerXmlParser.parse(serverXml);
-
- String value = read(serverXml);
-
- File keystoreFile = new File(parser.keystore());
-
- if (!keystoreFile.exists()) {
- keystoreFile = new File(System.getProperty("user.home"), ".keystore");
- }
-
- if (!keystoreFile.exists()) {
- keystoreFile = new File("target", ".keystore");
- }
-
- final String keystoreFilePath = (keystoreFile.exists() ? keystoreFile.getAbsolutePath() : "");
-
-
- if (tomeeHttpsPort != null && tomeeHttpsPort > 0 && parser.value("HTTPS", null) == null) {
- // ensure connector is not commented
- value = value.replace("<Service name=\"Catalina\">", "<Service name=\"Catalina\">\n"
- + " <Connector port=\"" + tomeeHttpsPort + "\" protocol=\"HTTP/1.1\" SSLEnabled=\"true\"\n" +
- " scheme=\"https\" secure=\"true\"\n" +
- " clientAuth=\"false\" sslProtocol=\"TLS\" keystoreFile=\"" + keystoreFilePath + "\" />\n");
- }
-
- if (tomeeHttpsPort == null) {
- // avoid NPE
- tomeeHttpsPort = 8443;
- }
-
- FileWriter writer = null;
- try {
- writer = new FileWriter(serverXml);
- writer.write(value
- .replace(parser.http(), Integer.toString(this.getTomeeHttpPortChecked()))
- .replace(parser.https(), Integer.toString(this.getTomeeHttpsPortChecked()))
- .replace(parser.ajp(), Integer.toString(tomeeAjpPort))
- .replace(parser.stop(), Integer.toString(this.getTomeeShutdownPortChecked()))
- .replace(parser.host(), tomeeHost)
- .replace(parser.appBase(), webappDir));
- } catch (final IOException e) {
- throw new TomEEException(e.getMessage(), e);
- } finally {
- close(writer);
- }
- }
-
- private static String read(final File file) {
- FileInputStream in = null;
- try {
- in = new FileInputStream(file);
- final StringBuilder sb = new StringBuilder();
- int i = in.read();
- while (i != -1) {
- sb.append((char) i);
- i = in.read();
- }
- return sb.toString();
- } catch (final Exception e) {
- throw new TomEEException(e.getMessage(), e);
- } finally {
- close(in);
- }
- }
-
- private Collection<File> overrideConf(final File dir, final String baseDir) {
- if (!dir.exists()) {
- return Collections.emptyList();
- }
-
- final File[] files = dir.listFiles();
- if (files != null) {
- final Collection<File> copied = new ArrayList<File>();
- for (final File f : files) {
- if (f.isHidden()) {
- continue;
- }
-
- final String file = baseDir + "/" + f.getName();
- final File destination = new File(catalinaBase, file);
- if (f.isDirectory()) {
- Files.mkdirs(destination);
- try {
- IO.copyDirectory(f, destination);
- } catch (final IOException e) {
- throw new TomEEException(e.getMessage(), e);
- }
- } else {
- InputStream in = null;
- OutputStream out = null;
- try {
- in = new FileInputStream(f);
- out = new FileOutputStream(destination);
- copy(in, out);
-
- copied.add(f);
- getLog().info("Override '" + file + "'");
- } catch (final Exception e) {
- throw new TomEEException(e.getMessage(), e);
- } finally {
- close(in);
- close(out);
- }
- }
- }
-
- return copied;
- }
-
- return Collections.emptyList();
- }
-
- protected void run() {
- if (classpaths == null) { // NPE protection when execute is skipped and mojo delegates to run directly
- classpaths = new ArrayList<String>();
- }
-
- final List<String> strings = generateJVMArgs();
-
- // init env for RemoteServer
- System.setProperty("openejb.home", catalinaBase.getAbsolutePath());
- if (debug) {
- System.setProperty("openejb.server.debug", "true");
- System.setProperty("server.debug.port", Integer.toString(debugPort));
- }
- System.setProperty("server.shutdown.port", Integer.toString(this.getTomeeShutdownPortChecked()));
- System.setProperty("server.shutdown.command", tomeeShutdownCommand);
-
- server = new RemoteServer(getConnectAttempts(), debug);
- server.setAdditionalClasspath(getAdditionalClasspath());
-
- addShutdownHooks(server); // some shutdown hooks are always added (see UpdatableTomEEMojo)
-
- if (TOM_EE.equals(container)) {
-
- server.setPortStartup(this.getTomeeHttpPortChecked());
-
- getLog().info("Running '" + getClass().getName().replace("TomEEMojo", "").toLowerCase(Locale.ENGLISH)
- + "'. Configured TomEE in plugin is " + tomeeHost + ":" + this.getTomeeHttpPortChecked()
- + " (plugin shutdown port is " + this.getTomeeShutdownPortChecked() + " and https port is " + this.getTomeeHttpsPortChecked() + ")");
- } else {
- getLog().info("Running '" + getClass().getSimpleName().replace("TomEEMojo", "").toLowerCase(Locale.ENGLISH));
- }
-
- final InputStream originalIn = System.in; // piped when starting resmote server so saving it
-
- serverCmd(server, strings);
-
- if (getWaitTomEE()) {
- final CountDownLatch stopCondition = new CountDownLatch(1);
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
- stopServer(stopCondition);
- }
- });
-
- if (useConsole) {
- final Scanner reader = new Scanner(originalIn);
-
- System.out.flush();
- getLog().info("Waiting for command: " + availableCommands());
-
- String line;
- while ((line = getNextLine(reader)) != null) {
-
- if (isQuit(line)) {
- break;
- }
-
- if ("ignore".equals(line)) {
- continue;
- }
-
- if (!handleLine(line.trim())) {
- System.out.flush();
- getLog().warn("Command '" + line + "' not understood. Use one of " + availableCommands());
- }
- }
-
- reader.close();
- stopServer(stopCondition); // better than using shutdown hook since it doesn't rely on the hook which are not sent by eclipse for instance
- }
-
- try {
- stopCondition.await();
- } catch (final InterruptedException e) {
- // no-op
- }
- }
- }
-
- private synchronized int getTomeeHttpPortChecked() {
- if (this.tomeeHttpPort <= 0) {
- this.tomeeHttpPort = NetworkUtil.getNextAvailablePort();
- }
- return this.tomeeHttpPort;
- }
-
- private synchronized int getTomeeHttpsPortChecked() {
- if (this.tomeeHttpsPort <= 0) {
- this.tomeeHttpsPort = NetworkUtil.getNextAvailablePort();
- }
- return this.tomeeHttpsPort;
- }
-
- private synchronized int getTomeeShutdownPortChecked() {
- if (this.tomeeShutdownPort <= 0) {
- this.tomeeShutdownPort = NetworkUtil.getNextAvailablePort();
- }
- return this.tomeeShutdownPort;
- }
-
- private String getNextLine(final Scanner reader) {
- try {
- return reader.nextLine();
- } catch (final NoSuchElementException e) {
- return "ignore";
- }
- }
-
- protected List<String> generateJVMArgs() {
- final String deployOpenEjbAppKey = "openejb.system.apps";
- final String servletCompliance = "org.apache.catalina.STRICT_SERVLET_COMPLIANCE";
-
- boolean deactivateStrictServletCompliance = args == null || !args.contains(servletCompliance);
-
- final List<String> strings = new ArrayList<String>();
- if (systemVariables != null) {
- for (final Map.Entry<String, String> entry : systemVariables.entrySet()) {
- final String key = entry.getKey();
- if (servletCompliance.equals(key)) {
- deactivateStrictServletCompliance = false;
- }
-
- final String value = entry.getValue();
- if (value == null) {
- strings.add("-D" + key);
- } else if (value.contains(" ")) {
- strings.add(String.format("'-D%s=%s'", key, value));
- } else {
- strings.add(String.format("-D%s=%s", key, value));
- }
-
- if (deployOpenEjbAppKey.equals(key)) {
- deployOpenEjbApplication = true;
- }
- }
- }
-
- if (webappDefaultConfig) {
- forceDefaultForNiceWebAppDevelopment();
- }
-
- if (deactivateStrictServletCompliance) {
- strings.add("-D" + servletCompliance + "=false");
- }
- if (quickSession) {
- strings.add("-Dopenejb.session.manager=org.apache.tomee.catalina.session.QuickSessionManager");
- }
- if (removeTomeeWebapp && ejbRemote) { // if we have tomee webapp no need to activate ejb remote support this way
- strings.add("-Dtomee.remote.support=true");
- }
- if (!deployOpenEjbApplication) { // true is the default so don't need to set the property
- if (args == null || !args.contains("-D" + deployOpenEjbAppKey)) {
- strings.add("-D" + deployOpenEjbAppKey + "=false");
- }
- }
- if (args != null) {
- strings.addAll(Args.parse(args));
- }
- if (javaagents != null) {
- addJavaagents(strings);
- }
-
- if (forceReloadable) {
- strings.add("-Dtomee.force-reloadable=true");
- }
-
- if (!getWaitTomEE()) {
- strings.add("-Dtomee.noshutdownhook=true");
- }
-
- String appName = null; // computed lazily
- if (docBases != null && !docBases.isEmpty()) {
- if ("war".equals(packaging)) {
- appName = destinationName().replace(".war", "");
- if (appName.startsWith("/")) {
- appName = appName.substring(1);
- }
- strings.add("-Dtomee." + appName + ".docBases=" + filesToString(docBases));
- strings.add("-Dtomee." + appName + ".docBases.cache=false"); // doesn't work for dev if activated
- } else {
- getLog().warn("docBases parameter only valid for a war");
- }
- }
-
- if (externalRepositories != null && !externalRepositories.isEmpty()) {
- if ("war".equals(packaging)) {
- appName = appName == null ? destinationName().replace(".war", "") : appName;
- if (appName.startsWith("/")) {
- appName = appName.substring(1);
- }
- strings.add("-Dtomee." + appName + ".externalRepositories=" + filesToString(externalRepositories));
- } else {
- getLog().warn("externalRepositories parameter only valid for a war");
- }
- }
-
- if (skipWarResources) {
- strings.add("-Dtomee.skip-war-resources=" + skipWarResources);
- }
-
- return strings;
- }
-
- private void addJavaagents(final List<String> strings) {
- final String existingJavaagent = "\\\"-javaagent:$CATALINA_HOME/lib/openejb-javaagent.jar\\\"";
- final StringBuilder javaagentString = new StringBuilder(existingJavaagent);
-
- for (final String rawJavaagent : javaagents) {
- final String javaagent;
- final String args;
- int argsIdx = rawJavaagent.indexOf('=');
- if (argsIdx < 0) {
- argsIdx = rawJavaagent.indexOf('?');
- }
- if (argsIdx > 0) {
- javaagent = rawJavaagent.substring(0, argsIdx);
- args = rawJavaagent.substring(argsIdx);
- } else {
- javaagent = rawJavaagent;
- args = "";
- }
-
- String path = javaagent;
- if (!new File(javaagent).isFile()) {
- try {
- final File jar = mvnToFile(javaagent, "jar");
- if (persistJavaagents) {
- final File javaagentFolder = new File(catalinaBase, "javaagent");
- Files.mkdirs(javaagentFolder);
- final String name = jar.getName();
- path = "$CATALINA_HOME/javaagent/" + name;
- IO.copy(jar, new File(javaagentFolder, name));
- }
- strings.add("-javaagent:" + jar.getAbsolutePath() + args);
- } catch (final Exception e) {
- getLog().warn("Can't find " + javaagent);
- strings.add("-javaagent:" + javaagent);
- }
- } else {
- strings.add("-javaagent:" + javaagent);
- }
-
- if (persistJavaagents) {
- javaagentString.append(" -javaagent:").append(path).append(args);
- }
- }
-
- if (persistJavaagents) {
- try {
- {
- final File catalinaSh = new File(catalinaBase, "bin/catalina.sh");
- final String content = IO.slurp(catalinaSh).replace(existingJavaagent, javaagentString.toString());
- doWrite(catalinaSh, content);
- }
- {
- final File catalinaBat = new File(catalinaBase, "bin/catalina.bat");
- final String content = IO.slurp(catalinaBat)
- .replace(
- "\"-javaagent:%CATALINA_HOME%\\lib\\openejb-javaagent.jar\"",
- javaagentString.toString()
- .replace('\'', '"')
- .replace('/', '\\')
- .replace("$CATALINA_HOME", "%CATALINA_HOME%"));
-
- doWrite(catalinaBat, content);
- }
- } catch (final IOException ioe) {
- throw new OpenEJBRuntimeException(ioe);
- }
- }
- }
-
- private void forceDefaultForNiceWebAppDevelopment() {
- if (!deployOpenEjbApplication) {
- getLog().info("Forcing deployOpenEjbApplication=true to be able to type 'reload[ENTER]' when classes are updated");
- deployOpenEjbApplication = true;
- }
- if (!forceReloadable) {
- getLog().info("Forcing forceReloadable=true to be able to type 'reload[ENTER]' when classes are updated");
- forceReloadable = true;
- }
- if (!skipWarResources) {
- getLog().info("Forcing skipWarResources=true to be able to refresh resources with F5");
- skipWarResources = true;
- }
- if (docBases == null) {
- docBases = new ArrayList<File>();
- }
- if (docBases.isEmpty() && webappResources.exists()) {
- getLog().info("adding " + webappResources.toString() + " docBase");
- docBases.add(webappResources);
- }
- if (externalRepositories == null) {
- externalRepositories = new ArrayList<File>();
- }
- if (externalRepositories.isEmpty() && webappClasses.exists()) {
- getLog().info("adding " + webappClasses.toString() + " externalRepository");
- externalRepositories.add(webappClasses);
- }
- }
-
- private static String filesToString(final Collection<File> files) {
- final Collection<String> paths = new ArrayList<String>(files.size());
- for (final File path : files) { // don't use relative paths (toString())
- paths.add(path.getAbsolutePath());
- }
- return Join.join(",", paths);
- }
-
- protected Collection<String> availableCommands() {
- return Arrays.asList(QUIT_CMD, EXIT_CMD);
- }
-
- protected synchronized void stopServer(final CountDownLatch stopCondition) {
- if (server == null) {
- return;
- }
-
- try {
- server.stop();
- } catch (final Exception e) {
- // no-op
- }
- try {
- server.getServer().waitFor();
- getLog().info(container + " stopped");
- } catch (final Exception e) {
- getLog().error("Can't stop " + container, e);
- }
-
- server = null;
- stopCondition.countDown();
- }
-
- private static boolean isQuit(String line) {
- if (QUIT_CMD.equalsIgnoreCase(line) || EXIT_CMD.equalsIgnoreCase(line)) {
- return true;
- }
-
- //http://youtrack.jetbrains.com/issue/IDEA-94826
- line = new StringBuilder(line).reverse().toString();
-
- return QUIT_CMD.equalsIgnoreCase(line) || EXIT_CMD.equalsIgnoreCase(line);
- }
-
- protected boolean handleLine(final String line) {
- return false;
- }
-
- protected void serverCmd(final RemoteServer server, final List<String> strings) {
-
- final Process p = this.server.getServer();
-
- if (null == p) {
-
- try {
- server.start(strings, getCmd(), checkStarted);
- } catch (final Exception e) {
- //TODO - Optional server.destroy() call
- getLog().warn("Failed to check or track server startup on port: " + this.getTomeeHttpPortChecked());
- }
- }
-
- }
-
- protected void addShutdownHooks(final RemoteServer server) {
- // no-op
- }
-
- protected int getConnectAttempts() {
- return (tomeeShutdownAttempts == 0 ? 60 : tomeeShutdownAttempts);
- }
-
- protected boolean getWaitTomEE() {
- return true;
- }
-
- private File resolve() {
- if (!settings.isOffline()) {
- try {
- if ("snapshots".equals(apacheRepos) || "true".equals(apacheRepos)) {
- remoteRepos.add(new DefaultArtifactRepository("apache", "https://repository.apache.org/content/repositories/snapshots/",
- new DefaultRepositoryLayout(),
- new ArtifactRepositoryPolicy(true, UPDATE_POLICY_DAILY, CHECKSUM_POLICY_WARN),
- new ArtifactRepositoryPolicy(false, UPDATE_POLICY_NEVER, CHECKSUM_POLICY_WARN)));
- } else {
- try {
- new URI(apacheRepos); // to check it is a uri
- remoteRepos.add(new DefaultArtifactRepository("additional-repo-tomee-mvn-plugin", apacheRepos,
- new DefaultRepositoryLayout(),
- new ArtifactRepositoryPolicy(true, UPDATE_POLICY_DAILY, CHECKSUM_POLICY_WARN),
- new ArtifactRepositoryPolicy(true, UPDATE_POLICY_NEVER, CHECKSUM_POLICY_WARN)));
- } catch (final URISyntaxException e) {
- // ignored, use classical repos
- }
- }
- } catch (final UnsupportedOperationException uoe) {
- // can happen if remoterepos is unmodifiable (possible in complex builds)
- // no-op
- }
- } else if (remoteRepos != null && remoteRepos.isEmpty()) {
- remoteRepos = new ArrayList<ArtifactRepository>();
- }
-
- if ((tomeeClassifier != null && (tomeeClassifier.isEmpty() || tomeeClassifier.equals("ignore")))
- || ("org.apache.openejb".equals(tomeeGroupId) && "openejb-standalone".equals(tomeeArtifactId))) {
- tomeeClassifier = null;
- }
-
- try {
- final Artifact artifact = factory.createDependencyArtifact(tomeeGroupId, tomeeArtifactId, createFromVersion(tomeeVersion), tomeeType, tomeeClassifier, SCOPE_COMPILE);
- resolver.resolve(artifact, remoteRepos, local);
- return artifact.getFile();
- } catch (final Exception e) {
- getLog().error(e.getMessage(), e);
- throw new TomEEException(e.getMessage(), e);
- }
- }
-
- private void unzip(final File mvnTomEE) {
- ZipFile in = null;
- try {
- in = new ZipFile(mvnTomEE);
-
- final Enumeration<? extends ZipEntry> entries = in.entries();
- while (entries.hasMoreElements()) {
- final ZipEntry entry = entries.nextElement();
- String name = entry.getName();
- int idx = name.indexOf("/");
- if (idx < 0) {
- idx = name.indexOf(File.separator);
- }
- if (idx < 0) {
- continue;
- }
- name = name.substring(idx + 1);
- final File dest = new File(catalinaBase.getAbsolutePath(), name);
- if (!dest.exists()) {
- final File parent = dest.getParentFile();
- if ((!parent.exists() && !parent.mkdirs())
- || (!parent.canWrite() && !parent.setWritable(true))
- || (!parent.canRead() && !parent.setReadable(true))) {
- throw new RuntimeException("Failed to create or set permissions on: " + parent);
- }
- }
- if (entry.isDirectory()) {
- if (!dest.exists() && !dest.mkdir()) {
- throw new RuntimeException("Failed to create: " + dest);
- }
- } else {
- final FileOutputStream fos = new FileOutputStream(dest);
- try {
- copy(in.getInputStream(entry), fos);
- } catch (final IOException e) {
- // ignored
- }
- close(fos);
-
- if (!dest.canRead() && !dest.setReadable(true)) {
- throw new RuntimeException("Failed to set readable on: " + dest);
- }
- if (dest.getName().endsWith(".sh")) {
- if (!dest.canExecute() && !dest.setExecutable(true)) {
- throw new RuntimeException("Failed to set executable on: " + dest);
- }
- }
- }
- }
-
- File file = new File(catalinaBase, "conf/tomee.xml");
- if (file.exists()) {
- container = TOM_EE;
- } else {
- container = "OpenEJB";
- file = new File(catalinaBase, "conf/openejb.xml");
- if (file.exists()) {
- webappDir = "apps";
- }
- }
-
- ensureAppsFolderExistAndIsConfiguredByDefault(file);
-
- getLog().info(container + " was unzipped in '" + catalinaBase.getAbsolutePath() + "'");
- } catch (final Exception e) {
- throw new TomEEException(e.getMessage(), e);
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (final IOException e) {
- // no-op
- }
- }
- }
- }
-
- private void ensureAppsFolderExistAndIsConfiguredByDefault(final File file) throws IOException {
- if ("openejb".equals(container.toLowerCase(Locale.ENGLISH))
- || (file.exists()
- && (
- (apps != null && !apps.isEmpty())
- || (!"pom".equals(packaging) && !"war".equals(packaging))))) { // webapps doesn't need apps folder in tomee
- final FileWriter writer = new FileWriter(file);
- final String rootTag = container.toLowerCase(Locale.ENGLISH);
- writer.write("<?xml version=\"1.0\"?>\n" +
- "<" + rootTag + ">\n" +
- " <Deployments dir=\"apps\" />\n" +
- "</" + rootTag + ">\n");
- writer.close();
-
- final File appsFolder = new File(catalinaBase, "apps");
- if (!appsFolder.exists() && !appsFolder.mkdirs()) {
- throw new RuntimeException("Failed to create: " + appsFolder);
- }
- }
- }
-
- private static void doWrite(final File file, final String content) throws IOException {
- final FileWriter writer = new FileWriter(file);
- try {
- writer.write(content);
- } finally {
- IO.close(writer);
- }
- }
-
- public abstract String getCmd();
-}
+/*
+ * 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.openejb.maven.plugin;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.artifact.factory.ArtifactFactory;
+import org.apache.maven.artifact.repository.ArtifactRepository;
+import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
+import org.apache.maven.artifact.repository.DefaultArtifactRepository;
+import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
+import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
+import org.apache.maven.artifact.resolver.ArtifactResolutionException;
+import org.apache.maven.artifact.resolver.ArtifactResolver;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugins.annotations.Component;
+import org.apache.maven.plugins.annotations.Parameter;
+import org.apache.maven.project.MavenProject;
+import org.apache.maven.settings.Settings;
+import org.apache.openejb.OpenEJBRuntimeException;
+import org.apache.openejb.config.RemoteServer;
+import org.apache.openejb.loader.Files;
+import org.apache.openejb.loader.IO;
+import org.apache.openejb.loader.Zips;
+import org.apache.openejb.maven.plugin.cli.Args;
+import org.apache.openejb.util.Join;
+import org.apache.openejb.util.NetworkUtil;
+import org.apache.openejb.util.OpenEjbVersion;
+import org.apache.tomee.util.QuickServerXmlParser;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Scanner;
+import java.util.concurrent.CountDownLatch;
+import java.util.logging.SimpleFormatter;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import static org.apache.maven.artifact.Artifact.SCOPE_COMPILE;
+import static org.apache.maven.artifact.repository.ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN;
+import static org.apache.maven.artifact.repository.ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY;
+import static org.apache.maven.artifact.repository.ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER;
+import static org.apache.maven.artifact.versioning.VersionRange.createFromVersion;
+import static org.apache.openejb.util.JarExtractor.delete;
+import static org.codehaus.plexus.util.FileUtils.deleteDirectory;
+import static org.codehaus.plexus.util.IOUtil.close;
+import static org.codehaus.plexus.util.IOUtil.copy;
+
+public abstract class AbstractTomEEMojo extends AbstractAddressMojo {
+ // if we get let say > 5 patterns like it we should create a LocationAnalyzer
+ // for < 5 patterns it should be fine
+ private static final String NAME_STR = "?name=";
+ private static final String UNZIP_PREFIX = "unzip:";
+ private static final String REMOVE_PREFIX = "remove:";
+ public static final String QUIT_CMD = "quit";
+ public static final String EXIT_CMD = "exit";
+ public static final String TOM_EE = "TomEE";
+
+ @Component
+ protected ArtifactFactory factory;
+
+ @Component
+ protected ArtifactResolver resolver;
+
+ @Parameter(defaultValue = "${localRepository}", readonly = true)
+ protected ArtifactRepository local;
+
+ @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true)
+ protected List<ArtifactRepository> remoteRepos;
+
+ @Parameter(property = "tomee-plugin.skipCurrentProject", defaultValue = "false")
+ protected boolean skipCurrentProject;
+
+ @Parameter(property = "tomee-plugin.version", defaultValue = "-1")
+ protected String tomeeVersion;
+
+ @Parameter(property = "tomee-plugin.groupId", defaultValue = "org.apache.openejb")
+ protected String tomeeGroupId;
+
+ @Parameter(property = "tomee-plugin.artifactId", defaultValue = "apache-tomee")
+ protected String tomeeArtifactId;
+
+ /**
+ * while tar.gz is not managed it is readonly
+ */
+ @Parameter(property = "tomee-plugin.type", defaultValue = "zip", readonly = true)
+ protected String tomeeType;
+
+ @Parameter(property = "tomee-plugin.apache-repos", defaultValue = "snapshots")
+ protected String apacheRepos;
+
+ @Parameter(property = "tomee-plugin.classifier", defaultValue = "webprofile")
+ protected String tomeeClassifier;
+
+ @Parameter(property = "tomee-plugin.shutdown", defaultValue = "8005")
+ protected int tomeeShutdownPort;
+
+ @Parameter(property = "tomee-plugin.shutdown.attempts", defaultValue = "60")
+ protected int tomeeShutdownAttempts;
+
+ @Parameter(property = "tomee-plugin.shutdown-command", defaultValue = "SHUTDOWN")
+ protected String tomeeShutdownCommand;
+
+ @Parameter(property = "tomee-plugin.ajp", defaultValue = "8009")
+ protected int tomeeAjpPort;
+
+ @Parameter(property = "tomee-plugin.https")
+ protected Integer tomeeHttpsPort;
+
+ @Parameter(property = "tomee-plugin.args")
+ protected String args;
+
+ @Parameter(property = "tomee-plugin.debug", defaultValue = "false")
+ protected boolean debug;
+
+ @Parameter(property = "tomee-plugin.simple-log", defaultValue = "false")
+ protected boolean simpleLog;
+
+ @Parameter(property = "tomee-plugin.debugPort", defaultValue = "5005")
+ protected int debugPort;
+
+ @Parameter(defaultValue = "${project.basedir}/src/main/webapp", property = "tomee-plugin.webappResources")
+ protected File webappResources;
+
+ @Parameter(defaultValue = "${project.build.outputDirectory}", property = "tomee-plugin.webappClasses")
+ protected File webappClasses;
+
+ @Parameter(defaultValue = "${project.build.directory}/apache-tomee", property = "tomee-plugin.catalina-base")
+ protected File catalinaBase;
+
+ /**
+ * rename the current artifact
+ */
+ @Parameter
+ protected String context;
+
+ /**
+ * relative to tomee.base.
+ */
+ @Parameter(defaultValue = "webapps")
+ protected String webappDir;
+
+ /**
+ * relative to tomee.base.
+ */
+ @Parameter(defaultValue = "apps")
+ protected String appDir;
+
+ /**
+ * relative to tomee.base.
+ */
+ @Parameter(defaultValue = "lib")
+ protected String libDir;
+
+ @Parameter(defaultValue = "${project.basedir}/src/main")
+ protected File mainDir;
+
+ @Parameter(defaultValue = "${project.build.directory}")
+ protected File target;
+
+ @Parameter(property = "tomee-plugin.conf", defaultValue = "${project.basedir}/src/main/tomee/conf")
+ protected File config;
+
+ @Parameter(property = "tomee-plugin.bin", defaultValue = "${project.basedir}/src/main/tomee/bin")
+ protected File bin;
+
+ @Parameter(property = "tomee-plugin.lib", defaultValue = "${project.basedir}/src/main/tomee/lib")
+ protected File lib;
+
+ @Parameter
+ protected Map<String, String> systemVariables;
+
+ @Parameter
+ private List<String> classpaths;
+
+ /**
+ * forcing nice default for war development (WEB-INF/classes and web resources)
+ */
+ @Parameter(property = "tomee-plugin.webappDefaultConfig", defaultValue = "false")
+ protected boolean webappDefaultConfig;
+
+ /**
+ * use a real random instead of secure random. saves few ms at startup.
+ */
+ @Parameter(property = "tomee-plugin.quick-session", defaultValue = "true")
+ protected boolean quickSession;
+
+ @Parameter
+ protected List<String> customizers;
+
+ @Parameter(defaultValue = "${project}", readonly = true, required = true)
+ protected MavenProject project;
+
+ /**
+ * force webapp to be reloadable
+ */
+ @Parameter(property = "tomee-plugin.force-reloadable", defaultValue = "false")
+ protected boolean forceReloadable;
+
+ /**
+ * supported formats:
+ * --> groupId:artifactId:version...
+ * --> unzip:groupId:artifactId:version...
+ * --> remove:prefix (often prefix = artifactId)
+ */
+ @Parameter
+ protected List<String> libs;
+
+ @Parameter
+ protected List<String> endorsedLibs;
+
+ @Parameter
+ protected List<String> javaagents;
+
+ @Parameter(property = "tomee-plugin.persist-javaagents", defaultValue = "false")
+ protected boolean persistJavaagents;
+
+ @Parameter
+ protected List<String> webapps;
+
+ @Parameter
+ protected List<String> apps;
+
+ @Parameter(property = "tomee-plugin.classes", defaultValue = "${project.build.outputDirectory}", readonly = true)
+ protected File classes;
+
+ @Parameter(defaultValue = "${project.build.directory}/${project.build.finalName}.${project.packaging}")
+ protected File warFile;
+
+ @Parameter(property = "tomee-plugin.remove-default-webapps", defaultValue = "true")
+ protected boolean removeDefaultWebapps;
+
+ @Parameter(property = "tomee-plugin.deploy-openejb-internal-application", defaultValue = "false")
+ protected boolean deployOpenEjbApplication;
+
+ @Parameter(property = "tomee-plugin.remove-tomee-webapps", defaultValue = "true")
+ protected boolean removeTomeeWebapp;
+
+ @Parameter(property = "tomee-plugin.ejb-remote", defaultValue = "true")
+ protected boolean ejbRemote;
+
+ @Parameter(defaultValue = "${project.packaging}", readonly = true)
+ protected String packaging;
+
+ @Parameter(property = "tomee-plugin.keep-server-xml", defaultValue = "false")
+ protected boolean keepServerXmlAsthis;
+
+ @Parameter(property = "tomee-plugin.check-started", defaultValue = "false")
+ protected boolean checkStarted;
+
+ @Parameter(property = "tomee-plugin.use-console", defaultValue = "true")
+ protected boolean useConsole;
+
+ @Parameter(property = "tomee-plugin.exiting", defaultValue = "false")
+ protected boolean tomeeAlreadyInstalled;
+
+ /**
+ * The current user system settings for use in Maven.
+ */
+ @Parameter(defaultValue = "${settings}", readonly = true)
+ protected Settings settings;
+
+ /**
+ * use openejb-standalone automatically instead of TomEE
+ */
+ @Parameter(property = "tomee-plugin.openejb", defaultValue = "false")
+ protected boolean useOpenEJB;
+
+ /**
+ * for TomEE and wars only, which docBase to use for this war.
+ */
+ @Parameter
+ protected List<File> docBases;
+
+ /**
+ * for TomEE and wars only, add some external repositories to classloader.
+ */
+ @Parameter
+ protected List<File> externalRepositories;
+
+ /**
+ * when you set docBases to src/main/webapp setting it to true will allow hot refresh.
+ */
+ @Parameter(property = "tomee-plugin.skipWarResources", defaultValue = "false")
+ protected boolean skipWarResources = false;
+
+ protected File deployedFile = null;
+ protected RemoteServer server = null;
+ protected String container = TOM_EE;
+
+ @Override
+ public void execute() throws MojoExecutionException, MojoFailureException {
+ fixConfig();
+
+ if ("-1".equals(tomeeVersion)) {
+ final String version = OpenEjbVersion.get().getVersion();
+ tomeeVersion = "1" + version.substring(1, version.length());
+ }
+
+ if (!tomeeAlreadyInstalled) {
+ final Collection<String> existingWebapps; // added before using the plugin with maven dependency plugin or sthg like that
+ if (removeDefaultWebapps) {
+ existingWebapps = webappsAlreadyAdded();
+ } else {
+ existingWebapps = Collections.emptyList();
+ }
+
+ unzip(resolve());
+ if (removeDefaultWebapps) { // do it first to let add other war
+ removeDefaultWebapps(removeTomeeWebapp, existingWebapps);
+ }
+ copyLibs(libs, new File(catalinaBase, libDir), "jar");
+ copyLibs(endorsedLibs, new File(catalinaBase, "endorsed"), "jar");
+ copyLibs(webapps, new File(catalinaBase, webappDir), "war");
+ copyLibs(apps, new File(catalinaBase, appDir), "jar");
+ overrideConf(config, "conf");
+ overrideConf(lib, "lib");
+ final Collection<File> copied = overrideConf(bin, "bin");
+
+ for (final File copy : copied) {
+ if (copy.getName().endsWith(".bat") || copy.getName().endsWith(".sh")) {
+ if (!copy.setExecutable(true)) {
+ getLog().warn("can't make " + copy.getPath() + " executable");
+ }
+ }
+ }
+
+ if (classpaths == null) { // NPE protection for activateSimpleLog() and run()
+ classpaths = new ArrayList<String>();
+ }
+ if (simpleLog) {
+ activateSimpleLog();
+ }
+
+ if (!keepServerXmlAsthis) {
+ overrideAddresses();
+ }
+ if (!skipCurrentProject) {
+ copyWar();
+ }
+
+ if (customizers != null) {
+ final Thread thread = Thread.currentThread();
+ final ClassLoader currentLoader = thread.getContextClassLoader();
+ final ClassLoader tccl = createClassLoader(currentLoader);
+ thread.setContextClassLoader(tccl);
+ try {
+ // a customizer is a Runnable with or without a constructor taking a File as parameter (catalina base)
+ // one goal is to avoid coupling as much as possible with this plugin
+ //
+ // if really needed we could introduce a Customizer interface but then it has more impacts on your packaging/config
+ for (final String customizer : customizers) {
+ try {
+ final Class<?> clazz = tccl.loadClass(customizer);
+ try {
+ final Constructor<?> cons = clazz.getConstructor(File.class);
+ Runnable.class.cast(cons.newInstance(catalinaBase)).run();
+ } catch (final NoSuchMethodException e) {
+ try {
+ Runnable.class.cast(clazz.newInstance()).run();
+ } catch (final Exception e1) {
+ throw new MojoExecutionException("can't create customizer: " + currentLoader, e);
+ }
+ }
+ } catch (final ClassNotFoundException e) {
+ throw new MojoExecutionException("can't find customizer: " + currentLoader, e);
+ } catch (final InvocationTargetException e) {
+ throw new MojoExecutionException("can't create customizer: " + currentLoader, e);
+ } catch (final InstantiationException e) {
+ throw new MojoExecutionException("can't create customizer: " + currentLoader, e);
+ } catch (final IllegalAccessException e) {
+ throw new MojoExecutionException("can't create customizer: " + currentLoader, e);
+ }
+ }
+ } finally {
+ try {
+ if (tccl != null && Closeable.class.isInstance(tccl)) {
+ Closeable.class.cast(tccl).close();
+ }
+ } catch (final IOException e) {
+ // no-op
+ }
+ thread.setContextClassLoader(currentLoader);
+ }
+ }
+ }
+
+ run();
+ }
+
+ @SuppressWarnings("unchecked")
+ private ClassLoader createClassLoader(final ClassLoader parent) {
+ final List<URL> urls = new ArrayList<URL>();
+ for (final Artifact artifact : (Collection<Artifact>) project.getArtifacts()) {
+ try {
+ urls.add(artifact.getFile().toURI().toURL());
+ } catch (final MalformedURLException e) {
+ getLog().warn("can't use artifact " + artifact.toString());
+ }
+ }
+ if (classes != null && classes.exists()) {
+ try {
+ urls.add(classes.toURI().toURL());
+ } catch (final MalformedURLException e) {
+ getLog().warn("can't use path " + classes.getAbsolutePath());
+ }
+ }
+ return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
+ }
+
+ protected void fixConfig() {
+ if (useOpenEJB) {
+ tomeeGroupId = "org.apache.openejb";
+ tomeeArtifactId = "openejb-standalone";
+ tomeeClassifier = null;
+ tomeeShutdownCommand = "Q";
+ if (8005 == tomeeShutdownPort) { // default admin port
+ tomeeShutdownPort = 4200;
+ }
+ if (tomeeVersion.startsWith("1.")) {
+ tomeeVersion = OpenEjbVersion.get().getVersion();
+ }
+
+ if (catalinaBase.getName().equals("apache-tomee") && catalinaBase.getParentFile().equals(target)) {
+ catalinaBase = new File(target, "apache-openejb");
+ }
+ if (config.getParentFile().getName().equals("tomee") && config.getParentFile().getParentFile().equals(mainDir)) {
+ config = new File(mainDir, "openejb/conf");
+ }
+ if (lib.getParentFile().getName().equals("tomee") && lib.getParentFile().getParentFile().equals(mainDir)) {
+ lib = new File(mainDir, "openejb/lib");
+ }
+ if (bin.getParentFile().getName().equals("tomee") && bin.getParentFile().getParentFile().equals(mainDir)) {
+ bin = new File(mainDir, "openejb/bin");
+ }
+ }
+ }
+
+ protected String getAdditionalClasspath() {
+ if (!classpaths.isEmpty()) {
+ final StringBuilder cpBuilder = new StringBuilder();
+ for (final String cp : classpaths) {
+ cpBuilder.append(cp);
+ cpBuilder.append(File.pathSeparatorChar);
+ }
+ return cpBuilder.substring(0, cpBuilder.length() - 1); // Dump the final path separator
+ }
+ return null;
+ }
+
+ private List<String> webappsAlreadyAdded() {
+ final List<String> list = new ArrayList<String>();
+ final File webapps = new File(catalinaBase, webappDir);
+ if (webapps.exists() && webapps.isDirectory()) {
+ final File[] files = webapps.listFiles();
+ if (files != null) {
+ for (final File f : files) {
+ list.add(f.getName());
+ }
+ }
+ }
+ return list;
+ }
+
+ private void activateSimpleLog() {
+ // replacing java.util.logging.SimpleFormatter by SimpleTomEEFormatter
+ final File loggingProperties = new File(catalinaBase, "conf/logging.properties");
+ if (loggingProperties.exists() && !new File(config, "conf/logging.properties").exists()) {
+ try {
+ String content = IO.slurp(loggingProperties);
+ if (!content.contains("java.util.logging.ConsoleHandler.formatter")) {
+ content += System.getProperty("line.separator") + "java.util.logging.ConsoleHandler.formatter = org.apache.tomee.jul.formatter.SimpleTomEEFormatter";
+ } else {
+ content = content.replace(SimpleFormatter.class.getName(), "org.apache.tomee.jul.formatter.SimpleTomEEFormatter");
+ }
+
+ doWrite(loggingProperties, content);
+ } catch (final Exception e) {
+ getLog().error("Can't set SimpleTomEEFormatter", e);
+ }
+ }
+ }
+
+ private void removeDefaultWebapps(final boolean removeTomee, final Collection<String> providedWebapps) {
+ final File webapps = new File(catalinaBase, webappDir);
+ if (webapps.isDirectory()) {
+ final File[] files = webapps.listFiles();
+ if (null != files) {
+ for (final File webapp : files) {
+ final String name = webapp.getName();
+ if (webapp.isDirectory() && !providedWebapps.contains(name) && (removeTomee || !name.equals("tomee"))) {
+ try {
+ deleteDirectory(webapp);
+ } catch (final IOException ignored) {
+ // no-op
+ }
+ }
+ }
+ }
+ }
+
+ getLog().info("Removed not mandatory default webapps");
+ }
+
+ private void copyLibs(final List<String> files, final File destParent, final String defaultType) {
+ if (files == null || files.isEmpty()) {
+ return;
+ }
+
+ if (!destParent.exists() && !destParent.mkdirs()) {
+ getLog().warn("can't create '" + destParent.getPath() + "'");
+ }
+
+ for (final String file : files) {
+ updateLib(file, destParent, defaultType);
+ }
+ }
+
+ private void updateLib(final String rawLib, final File destParent, final String defaultType) {
+ InputStream is = null;
+ OutputStream os = null;
+
+ // special hook to get more info
+ String lib = rawLib;
+ String extractedName = null;
+ if (lib.contains(NAME_STR)) {
+ lib = lib.substring(0, rawLib.indexOf(NAME_STR));
+ extractedName = rawLib.substring(rawLib.indexOf(NAME_STR) + NAME_STR.length(), rawLib.length());
+ if (!extractedName.endsWith(".jar") && !extractedName.endsWith(".war")
+ && !extractedName.endsWith(".ear") && !extractedName.endsWith(".rar")) {
+ extractedName = extractedName + "." + defaultType;
+ }
+ }
+
+ boolean unzip = false;
+ if (lib.startsWith(UNZIP_PREFIX)) {
+ lib = lib.substring(UNZIP_PREFIX.length());
+ unzip = true;
+ }
+
+ if (lib.startsWith(REMOVE_PREFIX)) {
+ final String prefix = lib.substring(REMOVE_PREFIX.length());
+ final File[] files = destParent.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(final File dir, final String name) {
+ return name.startsWith(prefix);
+ }
+ });
+ if (files != null) {
+ for (final File file : files) {
+ if (!IO.delete(file)) {
+ file.deleteOnExit();
+ }
+ getLog().info("Deleted " + file.getPath());
+ }
+ }
+ } else {
+ try {
+ final File file = mvnToFile(lib, defaultType);
+ if (!unzip) {
+ final File dest;
+ if (extractedName == null) {
+ dest = new File(destParent, file.getName());
+ } else {
+ dest = new File(destParent, extractedName);
+ }
+
+ is = new BufferedInputStream(new FileInputStream(file));
+ os = new BufferedOutputStream(new FileOutputStream(dest));
+ copy(is, os);
+
+ getLog().info("Copied '" + lib + "' in '" + dest.getAbsolutePath());
+ } else {
+ Zips.unzip(file, destParent, true);
+
+ getLog().info("Unzipped '" + lib + "' in '" + destParent.getAbsolutePath());
+ }
+ } catch (final Exception e) {
+ getLog().error(e.getMessage(), e);
+ throw new TomEEException(e.getMessage(), e);
+ } finally {
+ close(is);
+ close(os);
+ }
+ }
+ }
+
+ private File mvnToFile(final String lib, final String defaultType) throws ArtifactResolutionException, ArtifactNotFoundException {
+ final String[] infos = lib.split(":");
+ final String classifier;
+ final String type;
+ if (infos.length < 3) {
+ throw new TomEEException("format for librairies should be <groupId>:<artifactId>:<version>[:<type>[:<classifier>]]");
+ }
+ if (infos.length >= 4) {
+ type = infos[3];
+ } else {
+ type = defaultType;
+ }
+ if (infos.length == 5) {
+ classifier = infos[4];
+ } else {
+ classifier = null;
+ }
+
+ final Artifact artifact = factory.createDependencyArtifact(infos[0], infos[1], createFromVersion(infos[2]), type, classifier, SCOPE_COMPILE);
+ resolver.resolve(artifact, remoteRepos, local);
+ return artifact.getFile();
+ }
+
+ private void copyWar() {
+ if ("pom".equals(packaging)) {
+ return;
+ }
+
+ final boolean war = "war".equals(packaging);
+ final String name = destinationName();
+ final File out;
+ if (war) {
+ out = new File(catalinaBase, webappDir + "/" + name);
+ } else {
+ final File parent = new File(catalinaBase, appDir);
+ if (!parent.exists() && !parent.mkdirs()) {
+ getLog().warn("can't create '" + parent.getPath() + "'");
+ }
+ out = new File(parent, name);
+ }
+ delete(out);
+ if (!warFile.isDirectory() && name.endsWith("." + packaging)) {
+ final String dir = name.substring(0, name.lastIndexOf('.'));
+ final File unpacked;
+ if (war) {
+ unpacked = new File(catalinaBase, webappDir + "/" + dir);
+ } else {
+ unpacked = new File(catalinaBase, appDir + "/" + dir);
+ }
+ delete(unpacked);
+ }
+
+ if (warFile.exists() && warFile.isDirectory()) {
+ try {
+ IO.copyDirectory(warFile, out);
+ } catch (final IOException e) {
+ throw new TomEEException(e.getMessage(), e);
+ }
+ } else if (warFile.exists()) {
+ InputStream is = null;
+ OutputStream os = null;
+ try {
+ is = new FileInputStream(warFile);
+ os = new FileOutputStream(out);
+ copy(is, os);
+
+ getLog().info("Installed '" + warFile.getAbsolutePath() + "' in " + out.getAbsolutePath());
+ } catch (final Exception e) {
+ throw new TomEEException(e.getMessage(), e);
+ } finally {
+ close(is);
+ close(os);
+ }
+ } else {
+ getLog().warn("'" + warFile + "' doesn't exist, ignoring (maybe run mvn package before this plugin)");
+ }
+
+ deployedFile = out;
+ }
+
+ protected String destinationName() {
+ if (context != null) {
+ if (!context.contains(".") && !warFile.isDirectory()) {
+ return context + "." + packaging;
+ }
+ return context;
+ }
+ return warFile.getName();
+ }
+
+ private void overrideAddresses() {
+ final File serverXml = new File(catalinaBase, "conf/server.xml");
+ if (!serverXml.exists()) { // openejb
+ return;
+ }
+
+ final QuickServerXmlParser parser = QuickServerXmlParser.parse(serverXml);
+
+ String value = read(serverXml);
+
+ File keystoreFile = new File(parser.keystore());
+
+ if (!keystoreFile.exists()) {
+ keystoreFile = new File(System.getProperty("user.home"), ".keystore");
+ }
+
+ if (!keystoreFile.exists()) {
+ keystoreFile = new File("target", ".keystore");
+ }
+
+ final String keystoreFilePath = (keystoreFile.exists() ? keystoreFile.getAbsolutePath() : "");
+
+
+ if (tomeeHttpsPort != null && tomeeHttpsPort > 0 && parser.value("HTTPS", null) == null) {
+ // ensure connector is not commented
+ value = value.replace("<Service name=\"Catalina\">", "<Service name=\"Catalina\">\n"
+ + " <Connector port=\"" + tomeeHttpsPort + "\" protocol=\"HTTP/1.1\" SSLEnabled=\"true\"\n" +
+ " scheme=\"https\" secure=\"true\"\n" +
+ " clientAuth=\"false\" sslProtocol=\"TLS\" keystoreFile=\"" + keystoreFilePath + "\" />\n");
+ }
+
+ if (tomeeHttpsPort == null) {
+ // avoid NPE
+ tomeeHttpsPort = 8443;
+ }
+
+ FileWriter writer = null;
+ try {
+ writer = new FileWriter(serverXml);
+ writer.write(value
+ .replace(parser.http(), Integer.toString(this.getTomeeHttpPortChecked()))
+ .replace(parser.https(), Integer.toString(this.getTomeeHttpsPortChecked()))
+ .replace(parser.ajp(), Integer.toString(tomeeAjpPort))
+ .replace(parser.stop(), Integer.toString(this.getTomeeShutdownPortChecked()))
+ .replace(parser.host(), tomeeHost)
+ .replace(parser.appBase(), webappDir));
+ } catch (final IOException e) {
+ throw new TomEEException(e.getMessage(), e);
+ } finally {
+ close(writer);
+ }
+ }
+
+ private static String read(final File file) {
+ FileInputStream in = null;
+ try {
+ in = new FileInputStream(file);
+ final StringBuilder sb = new StringBuilder();
+ int i = in.read();
+ while (i != -1) {
+ sb.append((char) i);
+ i = in.read();
+ }
+ return sb.toString();
+ } catch (final Exception e) {
+ throw new TomEEException(e.getMessage(), e);
+ } finally {
+ close(in);
+ }
+ }
+
+ private Collection<File> overrideConf(final File dir, final String baseDir) {
+ if (!dir.exists()) {
+ return Collections.emptyList();
+ }
+
+ final File[] files = dir.listFiles();
+ if (files != null) {
+ final Collection<File> copied = new ArrayList<File>();
+ for (final File f : files) {
+ if (f.isHidden()) {
+ continue;
+ }
+
+ final String file = baseDir + "/" + f.getName();
+ final File destination = new File(catalinaBase, file);
+ if (f.isDirectory()) {
+ Files.mkdirs(destination);
+ try {
+ IO.copyDirectory(f, destination);
+ } catch (final IOException e) {
+ throw new TomEEException(e.getMessage(), e);
+ }
+ } else {
+ InputStream in = null;
+ OutputStream out = null;
+ try {
+ in = new FileInputStream(f);
+ out = new FileOutputStream(destination);
+ co
<TRUNCATED>
[06/12] tomee git commit: EOL
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/OpenEJBEJBInvoker.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/OpenEJBEJBInvoker.java b/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/OpenEJBEJBInvoker.java
index 967c6ac..a23bcca 100644
--- a/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/OpenEJBEJBInvoker.java
+++ b/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/OpenEJBEJBInvoker.java
@@ -1,115 +1,115 @@
-/*
- * 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.openejb.server.cxf.rs;
-
-import org.apache.cxf.jaxrs.JAXRSInvoker;
-import org.apache.cxf.message.Exchange;
-import org.apache.openejb.ApplicationException;
-import org.apache.openejb.BeanContext;
-import org.apache.openejb.InvalidateReferenceException;
-import org.apache.openejb.core.interceptor.InterceptorData;
-import org.apache.openejb.monitoring.StatsInterceptor;
-import org.apache.openejb.util.proxy.BeanContextInvocationHandler;
-import org.apache.openejb.util.proxy.LocalBeanProxyFactory;
-import org.apache.openejb.util.proxy.ProxyManager;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.rmi.RemoteException;
-import java.util.*;
-import javax.ejb.EJBException;
-
-public class OpenEJBEJBInvoker extends JAXRSInvoker {
- private final Map<Class<?>, Collection<Class<?>>> contextTypes = new HashMap<Class<?>, Collection<Class<?>>>();
-
- public OpenEJBEJBInvoker(final Collection<BeanContext> restEjbs) {
- for (final BeanContext context : restEjbs) {
- final Collection<Class<?>> classes = new HashSet<Class<?>>();
- Contexts.findContextFields(context.getBeanClass(), classes);
- for (final Collection<InterceptorData> list :
- Arrays.asList(
- context.getInterceptorData(),
- context.getInstanceScopedInterceptors(),
- context.getCallbackInterceptors())) {
- for (final InterceptorData id : list) {
- final Class<?> interceptorClass = id.getInterceptorClass();
- if (!StatsInterceptor.class.equals(interceptorClass)) {
- Contexts.findContextFields(interceptorClass, classes);
- }
- }
- }
- contextTypes.put(context.getBeanClass(), classes);
- }
- }
-
- @Override
- public Object invoke(final Exchange exchange, final Object request, final Object resourceObject) {
- Contexts.bind(exchange, getContextTypes(resourceObject));
- return super.invoke(exchange, request, resourceObject);
- }
-
- private Collection<Class<?>> getContextTypes(final Object resourceObject) {
- if (!ProxyManager.isProxyClass(resourceObject.getClass())
- && !LocalBeanProxyFactory.isProxy(resourceObject.getClass())) {
- return Collections.emptySet();
- }
-
- final InvocationHandler handler = ProxyManager.getInvocationHandler(resourceObject);
- if (!(handler instanceof BeanContextInvocationHandler)) {
- return Collections.emptySet();
- }
-
- final BeanContext beanContext = ((BeanContextInvocationHandler) handler).getBeanContext();
-
- if (beanContext == null) {
- return Collections.emptySet();
- }
- return contextTypes.get(beanContext.getBeanClass());
- }
-
- @Override
- protected Object performInvocation(final Exchange exchange, final Object serviceObject,
- final Method m, final Object[] paramArray) throws Exception {
- try {
- final Object[] args = super.insertExchange(m, paramArray, exchange);
- return m.invoke(serviceObject, args);
- } catch (final InvocationTargetException ite) {
- Throwable cause = ite.getTargetException();
- // unwrap to get ExceptionMapper working
- if (cause instanceof InvalidateReferenceException) {
- cause = cause.getCause();
- if (cause instanceof RemoteException) {
- cause = cause.getCause();
- }
- }
-
- if (EJBException.class.isInstance(cause)) {
- cause = EJBException.class.cast(cause).getCause();
- }
-
- if (ApplicationException.class.isInstance(cause) && Exception.class.isInstance(cause.getCause())) {
- throw Exception.class.cast(ApplicationException.class.cast(cause).getCause());
- }
-
- if (cause instanceof Exception) {
- throw (Exception) cause;
- }
- throw ite;
- }
- }
-}
+/*
+ * 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.openejb.server.cxf.rs;
+
+import org.apache.cxf.jaxrs.JAXRSInvoker;
+import org.apache.cxf.message.Exchange;
+import org.apache.openejb.ApplicationException;
+import org.apache.openejb.BeanContext;
+import org.apache.openejb.InvalidateReferenceException;
+import org.apache.openejb.core.interceptor.InterceptorData;
+import org.apache.openejb.monitoring.StatsInterceptor;
+import org.apache.openejb.util.proxy.BeanContextInvocationHandler;
+import org.apache.openejb.util.proxy.LocalBeanProxyFactory;
+import org.apache.openejb.util.proxy.ProxyManager;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.rmi.RemoteException;
+import java.util.*;
+import javax.ejb.EJBException;
+
+public class OpenEJBEJBInvoker extends JAXRSInvoker {
+ private final Map<Class<?>, Collection<Class<?>>> contextTypes = new HashMap<Class<?>, Collection<Class<?>>>();
+
+ public OpenEJBEJBInvoker(final Collection<BeanContext> restEjbs) {
+ for (final BeanContext context : restEjbs) {
+ final Collection<Class<?>> classes = new HashSet<Class<?>>();
+ Contexts.findContextFields(context.getBeanClass(), classes);
+ for (final Collection<InterceptorData> list :
+ Arrays.asList(
+ context.getInterceptorData(),
+ context.getInstanceScopedInterceptors(),
+ context.getCallbackInterceptors())) {
+ for (final InterceptorData id : list) {
+ final Class<?> interceptorClass = id.getInterceptorClass();
+ if (!StatsInterceptor.class.equals(interceptorClass)) {
+ Contexts.findContextFields(interceptorClass, classes);
+ }
+ }
+ }
+ contextTypes.put(context.getBeanClass(), classes);
+ }
+ }
+
+ @Override
+ public Object invoke(final Exchange exchange, final Object request, final Object resourceObject) {
+ Contexts.bind(exchange, getContextTypes(resourceObject));
+ return super.invoke(exchange, request, resourceObject);
+ }
+
+ private Collection<Class<?>> getContextTypes(final Object resourceObject) {
+ if (!ProxyManager.isProxyClass(resourceObject.getClass())
+ && !LocalBeanProxyFactory.isProxy(resourceObject.getClass())) {
+ return Collections.emptySet();
+ }
+
+ final InvocationHandler handler = ProxyManager.getInvocationHandler(resourceObject);
+ if (!(handler instanceof BeanContextInvocationHandler)) {
+ return Collections.emptySet();
+ }
+
+ final BeanContext beanContext = ((BeanContextInvocationHandler) handler).getBeanContext();
+
+ if (beanContext == null) {
+ return Collections.emptySet();
+ }
+ return contextTypes.get(beanContext.getBeanClass());
+ }
+
+ @Override
+ protected Object performInvocation(final Exchange exchange, final Object serviceObject,
+ final Method m, final Object[] paramArray) throws Exception {
+ try {
+ final Object[] args = super.insertExchange(m, paramArray, exchange);
+ return m.invoke(serviceObject, args);
+ } catch (final InvocationTargetException ite) {
+ Throwable cause = ite.getTargetException();
+ // unwrap to get ExceptionMapper working
+ if (cause instanceof InvalidateReferenceException) {
+ cause = cause.getCause();
+ if (cause instanceof RemoteException) {
+ cause = cause.getCause();
+ }
+ }
+
+ if (EJBException.class.isInstance(cause)) {
+ cause = EJBException.class.cast(cause).getCause();
+ }
+
+ if (ApplicationException.class.isInstance(cause) && Exception.class.isInstance(cause.getCause())) {
+ throw Exception.class.cast(ApplicationException.class.cast(cause).getCause());
+ }
+
+ if (cause instanceof Exception) {
+ throw (Exception) cause;
+ }
+ throw ite;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/DynamicSubclassEjbDeploymentTest.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/DynamicSubclassEjbDeploymentTest.java b/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/DynamicSubclassEjbDeploymentTest.java
index 626919e..e86d3a6 100644
--- a/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/DynamicSubclassEjbDeploymentTest.java
+++ b/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/DynamicSubclassEjbDeploymentTest.java
@@ -1,130 +1,130 @@
-/*
- * 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.openejb.server.cxf.rs;
-
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.openejb.OpenEjbContainer;
-import org.apache.openejb.config.DeploymentFilterable;
-import org.apache.openejb.server.cxf.rs.beans.SimpleEJB;
-import org.apache.openejb.util.NetworkUtil;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.ejb.embeddable.EJBContainer;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Request;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-public class DynamicSubclassEjbDeploymentTest {
-
- private static EJBContainer container;
- private static RESTIsVeryCool service;
- private static int port = -1;
-
- @BeforeClass
- public static void start() throws Exception {
- port = NetworkUtil.getNextAvailablePort();
- final Properties properties = new Properties();
- properties.setProperty("httpejbd.port", Integer.toString(port));
- properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf-rs.*");
- properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "true");
- container = EJBContainer.createEJBContainer(properties);
- service = (RESTIsVeryCool) container.getContext().lookup("java:/global/openejb-cxf-rs/RESTIsVeryCool");
- }
-
- @AfterClass
- public static void close() throws Exception {
- if (container != null) {
- container.close();
- }
- }
-
- @Test
- public void normal() {
- assertNotNull(service);
- assertEquals("ok", service.normal());
- }
-
- @Test
- public void rest() {
- final String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/rest").get(String.class);
- assertEquals("ok", response);
- }
-
- @Test
- public void restParameterInjected() {
- String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/param").get(String.class);
- assertEquals("true", response);
-
- response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/param").query("arg", "foo").get(String.class);
- assertEquals("foo", response);
- }
-
- @Test
- public void restFieldInjected() {
- final Boolean response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/field").get(Boolean.class);
- assertEquals(true, response);
- }
-
- @Stateless
- @Path("/ejb")
- public abstract static class RESTIsVeryCool implements InvocationHandler {
-
- @EJB
- private SimpleEJB simpleEJB;
-
- @javax.ws.rs.core.Context
- Request request;
-
- @Path("/normal")
- @GET
- public abstract String normal();
-
- @Path("/rest")
- @GET
- public abstract String rest();
-
- @Path("/param")
- @GET
- public String param(@QueryParam("arg") @DefaultValue("true") final String p) {
- return p;
- }
-
- @Path("/field")
- @GET
- public boolean field() {
- return "GET".equals(request.getMethod());
- }
-
- @Override
- public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
- return simpleEJB.ok();
- }
- }
-}
+/*
+ * 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.openejb.server.cxf.rs;
+
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.openejb.OpenEjbContainer;
+import org.apache.openejb.config.DeploymentFilterable;
+import org.apache.openejb.server.cxf.rs.beans.SimpleEJB;
+import org.apache.openejb.util.NetworkUtil;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.ejb.embeddable.EJBContainer;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Request;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.util.Properties;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+public class DynamicSubclassEjbDeploymentTest {
+
+ private static EJBContainer container;
+ private static RESTIsVeryCool service;
+ private static int port = -1;
+
+ @BeforeClass
+ public static void start() throws Exception {
+ port = NetworkUtil.getNextAvailablePort();
+ final Properties properties = new Properties();
+ properties.setProperty("httpejbd.port", Integer.toString(port));
+ properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf-rs.*");
+ properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "true");
+ container = EJBContainer.createEJBContainer(properties);
+ service = (RESTIsVeryCool) container.getContext().lookup("java:/global/openejb-cxf-rs/RESTIsVeryCool");
+ }
+
+ @AfterClass
+ public static void close() throws Exception {
+ if (container != null) {
+ container.close();
+ }
+ }
+
+ @Test
+ public void normal() {
+ assertNotNull(service);
+ assertEquals("ok", service.normal());
+ }
+
+ @Test
+ public void rest() {
+ final String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/rest").get(String.class);
+ assertEquals("ok", response);
+ }
+
+ @Test
+ public void restParameterInjected() {
+ String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/param").get(String.class);
+ assertEquals("true", response);
+
+ response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/param").query("arg", "foo").get(String.class);
+ assertEquals("foo", response);
+ }
+
+ @Test
+ public void restFieldInjected() {
+ final Boolean response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/field").get(Boolean.class);
+ assertEquals(true, response);
+ }
+
+ @Stateless
+ @Path("/ejb")
+ public abstract static class RESTIsVeryCool implements InvocationHandler {
+
+ @EJB
+ private SimpleEJB simpleEJB;
+
+ @javax.ws.rs.core.Context
+ Request request;
+
+ @Path("/normal")
+ @GET
+ public abstract String normal();
+
+ @Path("/rest")
+ @GET
+ public abstract String rest();
+
+ @Path("/param")
+ @GET
+ public String param(@QueryParam("arg") @DefaultValue("true") final String p) {
+ return p;
+ }
+
+ @Path("/field")
+ @GET
+ public boolean field() {
+ return "GET".equals(request.getMethod());
+ }
+
+ @Override
+ public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
+ return simpleEJB.ok();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EJBAccessExceptionMapperTest.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EJBAccessExceptionMapperTest.java b/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EJBAccessExceptionMapperTest.java
index dba3957..2841ec7 100644
--- a/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EJBAccessExceptionMapperTest.java
+++ b/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EJBAccessExceptionMapperTest.java
@@ -1,110 +1,110 @@
-/*
- * 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.openejb.server.cxf.rs;
-
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.openejb.OpenEjbContainer;
-import org.apache.openejb.config.DeploymentFilterable;
-import org.apache.openejb.server.cxf.rs.beans.SimpleEJB;
-import org.apache.openejb.util.NetworkUtil;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import javax.annotation.security.RolesAllowed;
-import javax.ejb.EJB;
-import javax.ejb.Lock;
-import javax.ejb.LockType;
-import javax.ejb.Singleton;
-import javax.ejb.embeddable.EJBContainer;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-
-@SuppressWarnings("FieldCanBeLocal")
-public class EJBAccessExceptionMapperTest {
- private static EJBContainer container;
- private static RESTIsCoolOne service;
- private static int port = -1;
-
- @BeforeClass
- public static void start() throws Exception {
- port = NetworkUtil.getNextAvailablePort();
- final Properties properties = new Properties();
- properties.setProperty("httpejbd.port", Integer.toString(port));
- properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf-rs.*");
- properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "true");
- container = EJBContainer.createEJBContainer(properties);
- service = (RESTIsCoolOne) container.getContext().lookup("java:/global/openejb-cxf-rs/RESTIsCoolOne");
- }
-
- @AfterClass
- public static void close() throws Exception {
- if (container != null) {
- container.close();
- }
- }
-
-
- @Test
- public void rest() {
- final Response response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejbsecu/rest").get();
- assertEquals(403, response.getStatus());
- }
-
-
- @Singleton
- @RolesAllowed("Something that does not exit at all")
- @Lock(LockType.READ)
- @Path("/ejbsecu")
- public static class RESTIsCoolOne {
- @EJB
- private SimpleEJB simpleEJB;
- @javax.ws.rs.core.Context
- Request request;
-
- @Path("/normal")
- @GET
- public String normal() {
- return simpleEJB.ok();
- }
-
- @Path("/rest")
- @GET
- public String rest() {
- return simpleEJB.ok();
- }
-
- @Path("/param")
- @GET
- public String param(@QueryParam("arg") @DefaultValue("true") final String p) {
- return p;
- }
-
- @Path("/field")
- @GET
- public boolean field() {
- return "GET".equals(request.getMethod());
- }
- }
-}
+/*
+ * 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.openejb.server.cxf.rs;
+
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.openejb.OpenEjbContainer;
+import org.apache.openejb.config.DeploymentFilterable;
+import org.apache.openejb.server.cxf.rs.beans.SimpleEJB;
+import org.apache.openejb.util.NetworkUtil;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.annotation.security.RolesAllowed;
+import javax.ejb.EJB;
+import javax.ejb.Lock;
+import javax.ejb.LockType;
+import javax.ejb.Singleton;
+import javax.ejb.embeddable.EJBContainer;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Request;
+import javax.ws.rs.core.Response;
+import java.util.Properties;
+
+import static org.junit.Assert.assertEquals;
+
+@SuppressWarnings("FieldCanBeLocal")
+public class EJBAccessExceptionMapperTest {
+ private static EJBContainer container;
+ private static RESTIsCoolOne service;
+ private static int port = -1;
+
+ @BeforeClass
+ public static void start() throws Exception {
+ port = NetworkUtil.getNextAvailablePort();
+ final Properties properties = new Properties();
+ properties.setProperty("httpejbd.port", Integer.toString(port));
+ properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf-rs.*");
+ properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "true");
+ container = EJBContainer.createEJBContainer(properties);
+ service = (RESTIsCoolOne) container.getContext().lookup("java:/global/openejb-cxf-rs/RESTIsCoolOne");
+ }
+
+ @AfterClass
+ public static void close() throws Exception {
+ if (container != null) {
+ container.close();
+ }
+ }
+
+
+ @Test
+ public void rest() {
+ final Response response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejbsecu/rest").get();
+ assertEquals(403, response.getStatus());
+ }
+
+
+ @Singleton
+ @RolesAllowed("Something that does not exit at all")
+ @Lock(LockType.READ)
+ @Path("/ejbsecu")
+ public static class RESTIsCoolOne {
+ @EJB
+ private SimpleEJB simpleEJB;
+ @javax.ws.rs.core.Context
+ Request request;
+
+ @Path("/normal")
+ @GET
+ public String normal() {
+ return simpleEJB.ok();
+ }
+
+ @Path("/rest")
+ @GET
+ public String rest() {
+ return simpleEJB.ok();
+ }
+
+ @Path("/param")
+ @GET
+ public String param(@QueryParam("arg") @DefaultValue("true") final String p) {
+ return p;
+ }
+
+ @Path("/field")
+ @GET
+ public boolean field() {
+ return "GET".equals(request.getMethod());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EjbDeploymentTest.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EjbDeploymentTest.java b/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EjbDeploymentTest.java
index 94816ba..2eb9a87 100644
--- a/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EjbDeploymentTest.java
+++ b/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/EjbDeploymentTest.java
@@ -1,123 +1,123 @@
-/*
- * 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.openejb.server.cxf.rs;
-
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.openejb.OpenEjbContainer;
-import org.apache.openejb.config.DeploymentFilterable;
-import org.apache.openejb.server.cxf.rs.beans.SimpleEJB;
-import org.apache.openejb.util.NetworkUtil;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.ejb.embeddable.EJBContainer;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Request;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-public class EjbDeploymentTest {
- private static EJBContainer container;
- private static RESTIsCoolTwo service;
- private static int port = -1;
-
- @BeforeClass
- public static void start() throws Exception {
- port = NetworkUtil.getNextAvailablePort();
- final Properties properties = new Properties();
- properties.setProperty("httpejbd.port", Integer.toString(port));
- properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf-rs.*");
- properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "true");
- container = EJBContainer.createEJBContainer(properties);
- service = (RESTIsCoolTwo) container.getContext().lookup("java:/global/openejb-cxf-rs/RESTIsCoolTwo");
- }
-
- @AfterClass
- public static void close() throws Exception {
- if (container != null) {
- container.close();
- }
- }
-
- @Test
- public void normal() {
- assertNotNull(service);
- assertEquals("ok", service.normal());
- }
-
- @Test
- public void rest() {
- final String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/rest").get(String.class);
- assertEquals("ok", response);
- }
-
- @Test
- public void restParameterInjected() {
- String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/param").get(String.class);
- assertEquals("true", response);
-
- response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/param").query("arg", "foo").get(String.class);
- assertEquals("foo", response);
- }
-
- @Test
- public void restFieldInjected() {
- final Boolean response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/field").get(Boolean.class);
- assertEquals(true, response);
- }
-
- @Stateless
- @Path("/ejb")
- public static class RESTIsCoolTwo {
- @EJB
- private SimpleEJB simpleEJB;
- @javax.ws.rs.core.Context
- Request request;
-
- @Path("/normal")
- @GET
- public String normal() {
- return simpleEJB.ok();
- }
-
- @Path("/rest")
- @GET
- public String rest() {
- return simpleEJB.ok();
- }
-
- @Path("/param")
- @GET
- public String param(@QueryParam("arg") @DefaultValue("true") final String p) {
- return p;
- }
-
- @Path("/field")
- @GET
- public boolean field() {
- return "GET".equals(request.getMethod());
- }
- }
-}
+/*
+ * 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.openejb.server.cxf.rs;
+
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.openejb.OpenEjbContainer;
+import org.apache.openejb.config.DeploymentFilterable;
+import org.apache.openejb.server.cxf.rs.beans.SimpleEJB;
+import org.apache.openejb.util.NetworkUtil;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.ejb.embeddable.EJBContainer;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Request;
+import java.util.Properties;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+public class EjbDeploymentTest {
+ private static EJBContainer container;
+ private static RESTIsCoolTwo service;
+ private static int port = -1;
+
+ @BeforeClass
+ public static void start() throws Exception {
+ port = NetworkUtil.getNextAvailablePort();
+ final Properties properties = new Properties();
+ properties.setProperty("httpejbd.port", Integer.toString(port));
+ properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf-rs.*");
+ properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "true");
+ container = EJBContainer.createEJBContainer(properties);
+ service = (RESTIsCoolTwo) container.getContext().lookup("java:/global/openejb-cxf-rs/RESTIsCoolTwo");
+ }
+
+ @AfterClass
+ public static void close() throws Exception {
+ if (container != null) {
+ container.close();
+ }
+ }
+
+ @Test
+ public void normal() {
+ assertNotNull(service);
+ assertEquals("ok", service.normal());
+ }
+
+ @Test
+ public void rest() {
+ final String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/rest").get(String.class);
+ assertEquals("ok", response);
+ }
+
+ @Test
+ public void restParameterInjected() {
+ String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/param").get(String.class);
+ assertEquals("true", response);
+
+ response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/param").query("arg", "foo").get(String.class);
+ assertEquals("foo", response);
+ }
+
+ @Test
+ public void restFieldInjected() {
+ final Boolean response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/ejb/field").get(Boolean.class);
+ assertEquals(true, response);
+ }
+
+ @Stateless
+ @Path("/ejb")
+ public static class RESTIsCoolTwo {
+ @EJB
+ private SimpleEJB simpleEJB;
+ @javax.ws.rs.core.Context
+ Request request;
+
+ @Path("/normal")
+ @GET
+ public String normal() {
+ return simpleEJB.ok();
+ }
+
+ @Path("/rest")
+ @GET
+ public String rest() {
+ return simpleEJB.ok();
+ }
+
+ @Path("/param")
+ @GET
+ public String param(@QueryParam("arg") @DefaultValue("true") final String p) {
+ return p;
+ }
+
+ @Path("/field")
+ @GET
+ public boolean field() {
+ return "GET".equals(request.getMethod());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/PathParamAtClassLevelTest.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/PathParamAtClassLevelTest.java b/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/PathParamAtClassLevelTest.java
index 3d6de65..86b0efc 100644
--- a/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/PathParamAtClassLevelTest.java
+++ b/server/openejb-cxf-rs/src/test/java/org/apache/openejb/server/cxf/rs/PathParamAtClassLevelTest.java
@@ -1,74 +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.openejb.server.cxf.rs;
-
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.openejb.OpenEjbContainer;
-import org.apache.openejb.config.DeploymentFilterable;
-import org.apache.openejb.util.NetworkUtil;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import javax.ejb.Stateless;
-import javax.ejb.embeddable.EJBContainer;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-
-public class PathParamAtClassLevelTest {
- private static EJBContainer container;
-
- private static int port = -1;
-
- @BeforeClass
- public static void start() throws Exception {
- port = NetworkUtil.getNextAvailablePort();
- final Properties properties = new Properties();
- properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf-rs.*");
- properties.setProperty("httpejbd.port", Integer.toString(port));
- properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "true");
- container = EJBContainer.createEJBContainer(properties);
- }
-
- @AfterClass
- public static void close() throws Exception {
- if (container != null) {
- container.close();
- }
- }
-
- @Test
- public void rest() {
- final String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/match/openejb/test/normal").get(String.class);
- assertEquals("openejb", response);
- }
-
- @Stateless
- @Path("/match/{name}/test")
- public static class DoesItMatchWithPathParamAtClassLevel {
- @Path("/normal")
- @GET
- public String normal(@PathParam("name") final String name) {
- return name;
- }
- }
-}
+/*
+ * 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.openejb.server.cxf.rs;
+
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.openejb.OpenEjbContainer;
+import org.apache.openejb.config.DeploymentFilterable;
+import org.apache.openejb.util.NetworkUtil;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.ejb.Stateless;
+import javax.ejb.embeddable.EJBContainer;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import java.util.Properties;
+
+import static org.junit.Assert.assertEquals;
+
+public class PathParamAtClassLevelTest {
+ private static EJBContainer container;
+
+ private static int port = -1;
+
+ @BeforeClass
+ public static void start() throws Exception {
+ port = NetworkUtil.getNextAvailablePort();
+ final Properties properties = new Properties();
+ properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf-rs.*");
+ properties.setProperty("httpejbd.port", Integer.toString(port));
+ properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, "true");
+ container = EJBContainer.createEJBContainer(properties);
+ }
+
+ @AfterClass
+ public static void close() throws Exception {
+ if (container != null) {
+ container.close();
+ }
+ }
+
+ @Test
+ public void rest() {
+ final String response = WebClient.create("http://localhost:" + port + "/openejb-cxf-rs").path("/match/openejb/test/normal").get(String.class);
+ assertEquals("openejb", response);
+ }
+
+ @Stateless
+ @Path("/match/{name}/test")
+ public static class DoesItMatchWithPathParamAtClassLevel {
+ @Path("/normal")
+ @GET
+ public String normal(@PathParam("name") final String name) {
+ return name;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/WSSPassThroughInterceptor.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/WSSPassThroughInterceptor.java b/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/WSSPassThroughInterceptor.java
index 058a9b0..1d05d9c 100644
--- a/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/WSSPassThroughInterceptor.java
+++ b/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/WSSPassThroughInterceptor.java
@@ -1,66 +1,66 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.openejb.server.cxf;
-
-import org.apache.cxf.binding.soap.SoapMessage;
-import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
-import org.apache.cxf.phase.Phase;
-import org.apache.ws.security.WSConstants;
-
-import javax.xml.namespace.QName;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * When using JAX-WS Handler, the {@link org.apache.openejb.server.cxf.ejb.EjbInterceptor}
- * adds the {@link org.apache.cxf.binding.soap.interceptor.MustUnderstandInterceptor}. OpenEJB now supports
- * WS Security out of the box, so it must indicates WS Security headers have been treated. That is simply done
- * using that fake interceptor.
- * <p/>
- * $Id$
- */
-public class WSSPassThroughInterceptor extends AbstractSoapInterceptor {
- private static final Set<QName> HEADERS = new HashSet<QName>();
-
- static {
- HEADERS.add(new QName(WSConstants.WSSE_NS, WSConstants.WSSE_LN));
- HEADERS.add(new QName(WSConstants.WSSE11_NS, WSConstants.WSSE_LN));
- HEADERS.add(new QName(WSConstants.ENC_NS, WSConstants.ENC_DATA_LN));
- }
-
- public WSSPassThroughInterceptor() {
- super(Phase.PRE_PROTOCOL);
- }
-
- public WSSPassThroughInterceptor(final String phase) {
- super(phase);
- }
-
- @Override
- public Set<QName> getUnderstoodHeaders() {
- return HEADERS;
- }
-
- public void handleMessage(final SoapMessage soapMessage) {
- // do nothing
-
- // this interceptor simply returns all WS-Security headers in its getUnderstoodHeaders()
- // method, so that CXF does not complain that they have not been "processed"
- // this is useful if you only need to look at the non-encrypted XML
- }
-
-}
+/**
+ * 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.openejb.server.cxf;
+
+import org.apache.cxf.binding.soap.SoapMessage;
+import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
+import org.apache.cxf.phase.Phase;
+import org.apache.ws.security.WSConstants;
+
+import javax.xml.namespace.QName;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * When using JAX-WS Handler, the {@link org.apache.openejb.server.cxf.ejb.EjbInterceptor}
+ * adds the {@link org.apache.cxf.binding.soap.interceptor.MustUnderstandInterceptor}. OpenEJB now supports
+ * WS Security out of the box, so it must indicates WS Security headers have been treated. That is simply done
+ * using that fake interceptor.
+ * <p/>
+ * $Id$
+ */
+public class WSSPassThroughInterceptor extends AbstractSoapInterceptor {
+ private static final Set<QName> HEADERS = new HashSet<QName>();
+
+ static {
+ HEADERS.add(new QName(WSConstants.WSSE_NS, WSConstants.WSSE_LN));
+ HEADERS.add(new QName(WSConstants.WSSE11_NS, WSConstants.WSSE_LN));
+ HEADERS.add(new QName(WSConstants.ENC_NS, WSConstants.ENC_DATA_LN));
+ }
+
+ public WSSPassThroughInterceptor() {
+ super(Phase.PRE_PROTOCOL);
+ }
+
+ public WSSPassThroughInterceptor(final String phase) {
+ super(phase);
+ }
+
+ @Override
+ public Set<QName> getUnderstoodHeaders() {
+ return HEADERS;
+ }
+
+ public void handleMessage(final SoapMessage soapMessage) {
+ // do nothing
+
+ // this interceptor simply returns all WS-Security headers in its getUnderstoodHeaders()
+ // method, so that CXF does not complain that they have not been "processed"
+ // this is useful if you only need to look at the non-encrypted XML
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/ejb/EjbMessageContext.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/ejb/EjbMessageContext.java b/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/ejb/EjbMessageContext.java
index 9c09ca0..9c89346 100644
--- a/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/ejb/EjbMessageContext.java
+++ b/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/ejb/EjbMessageContext.java
@@ -1,62 +1,62 @@
-/**
- * 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.openejb.server.cxf.ejb;
-
-import javax.xml.ws.EndpointReference;
-import javax.xml.ws.WebServiceException;
-import javax.xml.ws.wsaddressing.W3CEndpointReference;
-import javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder;
-
-import org.apache.cxf.endpoint.Endpoint;
-import org.apache.cxf.jaxws.context.WrappedMessageContext;
-import org.apache.cxf.message.Message;
-import org.apache.openejb.core.webservices.AddressingSupport;
-import org.w3c.dom.Element;
-
-public class EjbMessageContext extends WrappedMessageContext implements AddressingSupport {
-
- public EjbMessageContext(final Message m, final Scope defScope) {
- super(m, defScope);
- }
-
- public EndpointReference getEndpointReference(final Element... referenceParameters) {
- final org.apache.cxf.message.Message msg = getWrappedMessage();
- final Endpoint ep = msg.getExchange().get(Endpoint.class);
-
- final W3CEndpointReferenceBuilder builder = new W3CEndpointReferenceBuilder();
- builder.address(ep.getEndpointInfo().getAddress());
- builder.serviceName(ep.getService().getName());
- builder.endpointName(ep.getEndpointInfo().getName());
-
- if (referenceParameters != null) {
- for (final Element referenceParameter : referenceParameters) {
- builder.referenceParameter(referenceParameter);
- }
- }
-
- return builder.build();
- }
-
- public <T extends EndpointReference> T getEndpointReference(final Class<T> clazz, final Element... referenceParameters) {
- if (W3CEndpointReference.class.isAssignableFrom(clazz)) {
- return clazz.cast(getEndpointReference(referenceParameters));
- } else {
- throw new WebServiceException("Endpoint reference type not supported: " + clazz);
- }
- }
-
-}
+/**
+ * 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.openejb.server.cxf.ejb;
+
+import javax.xml.ws.EndpointReference;
+import javax.xml.ws.WebServiceException;
+import javax.xml.ws.wsaddressing.W3CEndpointReference;
+import javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder;
+
+import org.apache.cxf.endpoint.Endpoint;
+import org.apache.cxf.jaxws.context.WrappedMessageContext;
+import org.apache.cxf.message.Message;
+import org.apache.openejb.core.webservices.AddressingSupport;
+import org.w3c.dom.Element;
+
+public class EjbMessageContext extends WrappedMessageContext implements AddressingSupport {
+
+ public EjbMessageContext(final Message m, final Scope defScope) {
+ super(m, defScope);
+ }
+
+ public EndpointReference getEndpointReference(final Element... referenceParameters) {
+ final org.apache.cxf.message.Message msg = getWrappedMessage();
+ final Endpoint ep = msg.getExchange().get(Endpoint.class);
+
+ final W3CEndpointReferenceBuilder builder = new W3CEndpointReferenceBuilder();
+ builder.address(ep.getEndpointInfo().getAddress());
+ builder.serviceName(ep.getService().getName());
+ builder.endpointName(ep.getEndpointInfo().getName());
+
+ if (referenceParameters != null) {
+ for (final Element referenceParameter : referenceParameters) {
+ builder.referenceParameter(referenceParameter);
+ }
+ }
+
+ return builder.build();
+ }
+
+ public <T extends EndpointReference> T getEndpointReference(final Class<T> clazz, final Element... referenceParameters) {
+ if (W3CEndpointReference.class.isAssignableFrom(clazz)) {
+ return clazz.cast(getEndpointReference(referenceParameters));
+ } else {
+ throw new WebServiceException("Endpoint reference type not supported: " + clazz);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/CxfJaxWsProviderTest.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/CxfJaxWsProviderTest.java b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/CxfJaxWsProviderTest.java
index b63a211..13a5289 100644
--- a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/CxfJaxWsProviderTest.java
+++ b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/CxfJaxWsProviderTest.java
@@ -1,137 +1,137 @@
-/**
- * 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.openejb.server.cxf;
-
-import junit.framework.TestCase;
-import org.apache.openejb.config.DeploymentFilterable;
-import org.apache.openejb.server.cxf.fault.AuthenticatorService;
-import org.apache.openejb.server.cxf.fault.WrongPasswordException;
-import org.apache.openejb.server.cxf.fault.WrongPasswordRuntimeException;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.xml.namespace.QName;
-import javax.xml.ws.Service;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URL;
-import java.util.Properties;
-
-/**
- * @version $Rev$
- */
-public class CxfJaxWsProviderTest extends TestCase {
-
- //START SNIPPET: setup
- private InitialContext initialContext;
-
- //Random port to avoid test conflicts
- private static final int port = Integer.parseInt(System.getProperty("httpejbd.port", "" + org.apache.openejb.util.NetworkUtil.getNextAvailablePort()));
-
- protected void setUp() throws Exception {
- final Properties properties = new Properties();
- properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf.*");
- properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
- properties.setProperty("openejb.embedded.remotable", "true");
-
- //Just for this test we change the default port from 4204 to avoid conflicts
- properties.setProperty("httpejbd.port", "" + port);
-
- initialContext = new InitialContext(properties);
- }
- //END SNIPPET: setup
-
- public void test00_runCheckedException() {
- try {
- final AuthenticatorService withHandler = Service.create(
- new URL("http://localhost:" + port + "/openejb-cxf/AuthenticatorServiceBean?wsdl"),
- new QName("http://superbiz.org/wsdl", "AuthenticatorServiceBeanService"))
- .getPort(AuthenticatorService.class);
- assertNotNull(withHandler);
-
- final AuthenticatorService noHandler = Service.create(
- new URL("http://localhost:" + port + "/openejb-cxf/AuthenticatorServiceBeanNoHandler?wsdl"),
- new QName("http://superbiz.org/wsdl", "AuthenticatorServiceBeanNoHandlerService"))
- .getPort(AuthenticatorService.class);
- assertNotNull(noHandler);
-
- try {
- withHandler.authenticate("John", "Doe");
- } catch (final WrongPasswordException e) {
- System.out.println("My lovely checked exception...");
- } catch (final Throwable e) {
- e.printStackTrace();
- fail("A throwable instead of a checked exception...");
- }
-
- try {
- noHandler.authenticate("John", "Doe");
- } catch (final WrongPasswordException e) {
- System.out.println("My lovely checked exception...");
- } catch (final Throwable e) {
- e.printStackTrace();
- fail("A throwable instead of a checked exception...");
- }
-
- } catch (final MalformedURLException e) {
- e.printStackTrace();
- fail("?!? invalid URL ???");
- }
-
- }
-
- public void test01_runRuntimeException() {
- try {
- final AuthenticatorService withHandler = Service.create(
- new URL("http://localhost:" + port + "/openejb-cxf/AuthenticatorServiceBean?wsdl"),
- new QName("http://superbiz.org/wsdl", "AuthenticatorServiceBeanService"))
- .getPort(AuthenticatorService.class);
- assertNotNull(withHandler);
-
- final AuthenticatorService noHandler = Service.create(
- new URL("http://localhost:" + port + "/openejb-cxf/AuthenticatorServiceBeanNoHandler?wsdl"),
- new QName("http://superbiz.org/wsdl", "AuthenticatorServiceBeanNoHandlerService"))
- .getPort(AuthenticatorService.class);
- assertNotNull(noHandler);
-
- try {
- withHandler.authenticateRuntime("John", "Doe");
- } catch (final WrongPasswordRuntimeException e) {
- e.printStackTrace();
- fail("My checked exception instead of a throwableS...");
- } catch (final Throwable e) {
- System.out.println("A throwable exception...");
- }
-
-
- try {
- noHandler.authenticateRuntime("John", "Doe");
- } catch (final WrongPasswordRuntimeException e) {
- e.printStackTrace();
- fail("My checked exception instead of a throwableS...");
- } catch (final Throwable e) {
- System.out.println("A throwable exception...");
- }
-
- } catch (final MalformedURLException e) {
- e.printStackTrace();
- fail("?!? invalid URL ???");
- }
-
- }
-
-}
+/**
+ * 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.openejb.server.cxf;
+
+import junit.framework.TestCase;
+import org.apache.openejb.config.DeploymentFilterable;
+import org.apache.openejb.server.cxf.fault.AuthenticatorService;
+import org.apache.openejb.server.cxf.fault.WrongPasswordException;
+import org.apache.openejb.server.cxf.fault.WrongPasswordRuntimeException;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.xml.namespace.QName;
+import javax.xml.ws.Service;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.util.Properties;
+
+/**
+ * @version $Rev$
+ */
+public class CxfJaxWsProviderTest extends TestCase {
+
+ //START SNIPPET: setup
+ private InitialContext initialContext;
+
+ //Random port to avoid test conflicts
+ private static final int port = Integer.parseInt(System.getProperty("httpejbd.port", "" + org.apache.openejb.util.NetworkUtil.getNextAvailablePort()));
+
+ protected void setUp() throws Exception {
+ final Properties properties = new Properties();
+ properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, ".*openejb-cxf.*");
+ properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
+ properties.setProperty("openejb.embedded.remotable", "true");
+
+ //Just for this test we change the default port from 4204 to avoid conflicts
+ properties.setProperty("httpejbd.port", "" + port);
+
+ initialContext = new InitialContext(properties);
+ }
+ //END SNIPPET: setup
+
+ public void test00_runCheckedException() {
+ try {
+ final AuthenticatorService withHandler = Service.create(
+ new URL("http://localhost:" + port + "/openejb-cxf/AuthenticatorServiceBean?wsdl"),
+ new QName("http://superbiz.org/wsdl", "AuthenticatorServiceBeanService"))
+ .getPort(AuthenticatorService.class);
+ assertNotNull(withHandler);
+
+ final AuthenticatorService noHandler = Service.create(
+ new URL("http://localhost:" + port + "/openejb-cxf/AuthenticatorServiceBeanNoHandler?wsdl"),
+ new QName("http://superbiz.org/wsdl", "AuthenticatorServiceBeanNoHandlerService"))
+ .getPort(AuthenticatorService.class);
+ assertNotNull(noHandler);
+
+ try {
+ withHandler.authenticate("John", "Doe");
+ } catch (final WrongPasswordException e) {
+ System.out.println("My lovely checked exception...");
+ } catch (final Throwable e) {
+ e.printStackTrace();
+ fail("A throwable instead of a checked exception...");
+ }
+
+ try {
+ noHandler.authenticate("John", "Doe");
+ } catch (final WrongPasswordException e) {
+ System.out.println("My lovely checked exception...");
+ } catch (final Throwable e) {
+ e.printStackTrace();
+ fail("A throwable instead of a checked exception...");
+ }
+
+ } catch (final MalformedURLException e) {
+ e.printStackTrace();
+ fail("?!? invalid URL ???");
+ }
+
+ }
+
+ public void test01_runRuntimeException() {
+ try {
+ final AuthenticatorService withHandler = Service.create(
+ new URL("http://localhost:" + port + "/openejb-cxf/AuthenticatorServiceBean?wsdl"),
+ new QName("http://superbiz.org/wsdl", "AuthenticatorServiceBeanService"))
+ .getPort(AuthenticatorService.class);
+ assertNotNull(withHandler);
+
+ final AuthenticatorService noHandler = Service.create(
+ new URL("http://localhost:" + port + "/openejb-cxf/AuthenticatorServiceBeanNoHandler?wsdl"),
+ new QName("http://superbiz.org/wsdl", "AuthenticatorServiceBeanNoHandlerService"))
+ .getPort(AuthenticatorService.class);
+ assertNotNull(noHandler);
+
+ try {
+ withHandler.authenticateRuntime("John", "Doe");
+ } catch (final WrongPasswordRuntimeException e) {
+ e.printStackTrace();
+ fail("My checked exception instead of a throwableS...");
+ } catch (final Throwable e) {
+ System.out.println("A throwable exception...");
+ }
+
+
+ try {
+ noHandler.authenticateRuntime("John", "Doe");
+ } catch (final WrongPasswordRuntimeException e) {
+ e.printStackTrace();
+ fail("My checked exception instead of a throwableS...");
+ } catch (final Throwable e) {
+ System.out.println("A throwable exception...");
+ }
+
+ } catch (final MalformedURLException e) {
+ e.printStackTrace();
+ fail("?!? invalid URL ???");
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBean.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBean.java b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBean.java
index 807d73c..5a8ed5a 100644
--- a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBean.java
+++ b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBean.java
@@ -1,43 +1,43 @@
-/**
- * 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.openejb.server.cxf.fault;
-
-import javax.ejb.Stateless;
-import javax.jws.HandlerChain;
-import javax.jws.WebService;
-
-/**
- * @version $Rev$
- */
-@Stateless
-@WebService(targetNamespace = "http://superbiz.org/wsdl")
-@HandlerChain(file = "handler.xml")
-public class AuthenticatorServiceBean implements AuthenticatorService {
-
- public boolean authenticate(final String name, final String password) throws WrongPasswordException {
- System.out.println(String.format("AuthenticatorServiceBean.authenticate(%s, %s)",
- name, password));
- throw new WrongPasswordException("Checked exception");
- }
-
- public boolean authenticateRuntime(final String name, final String password) {
- System.out.println(String.format("AuthenticatorServiceBean.authenticateRuntime(%s, %s)",
- name, password));
- throw new WrongPasswordRuntimeException("Runtime exception");
- }
-
+/**
+ * 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.openejb.server.cxf.fault;
+
+import javax.ejb.Stateless;
+import javax.jws.HandlerChain;
+import javax.jws.WebService;
+
+/**
+ * @version $Rev$
+ */
+@Stateless
+@WebService(targetNamespace = "http://superbiz.org/wsdl")
+@HandlerChain(file = "handler.xml")
+public class AuthenticatorServiceBean implements AuthenticatorService {
+
+ public boolean authenticate(final String name, final String password) throws WrongPasswordException {
+ System.out.println(String.format("AuthenticatorServiceBean.authenticate(%s, %s)",
+ name, password));
+ throw new WrongPasswordException("Checked exception");
+ }
+
+ public boolean authenticateRuntime(final String name, final String password) {
+ System.out.println(String.format("AuthenticatorServiceBean.authenticateRuntime(%s, %s)",
+ name, password));
+ throw new WrongPasswordRuntimeException("Runtime exception");
+ }
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBeanNoHandler.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBeanNoHandler.java b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBeanNoHandler.java
index 3a3cb43..41b82ae 100644
--- a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBeanNoHandler.java
+++ b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorServiceBeanNoHandler.java
@@ -1,42 +1,42 @@
-/**
- * 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.openejb.server.cxf.fault;
-
-import javax.ejb.Stateless;
-import javax.jws.WebService;
-
-/**
- * @version $Rev$
- */
-@Stateless
-@WebService(targetNamespace = "http://superbiz.org/wsdl")
-// @HandlerChain(file="handler.xml")
-public class AuthenticatorServiceBeanNoHandler implements AuthenticatorService {
-
- public boolean authenticate(final String name, final String password) throws WrongPasswordException {
- System.out.println(String.format("AuthenticatorServiceBeanNoHandler.authenticate(%s, %s)",
- name, password));
- throw new WrongPasswordException("Checked exception");
- }
-
- public boolean authenticateRuntime(final String name, final String password) {
- System.out.println(String.format("AuthenticatorServiceBeanNoHandler.authenticateRuntime(%s, %s)",
- name, password));
- throw new WrongPasswordRuntimeException("Runtime exception");
- }
-
+/**
+ * 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.openejb.server.cxf.fault;
+
+import javax.ejb.Stateless;
+import javax.jws.WebService;
+
+/**
+ * @version $Rev$
+ */
+@Stateless
+@WebService(targetNamespace = "http://superbiz.org/wsdl")
+// @HandlerChain(file="handler.xml")
+public class AuthenticatorServiceBeanNoHandler implements AuthenticatorService {
+
+ public boolean authenticate(final String name, final String password) throws WrongPasswordException {
+ System.out.println(String.format("AuthenticatorServiceBeanNoHandler.authenticate(%s, %s)",
+ name, password));
+ throw new WrongPasswordException("Checked exception");
+ }
+
+ public boolean authenticateRuntime(final String name, final String password) {
+ System.out.println(String.format("AuthenticatorServiceBeanNoHandler.authenticateRuntime(%s, %s)",
+ name, password));
+ throw new WrongPasswordRuntimeException("Runtime exception");
+ }
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/DummyInterceptor.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/DummyInterceptor.java b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/DummyInterceptor.java
index d12465b..e1e54b7 100644
--- a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/DummyInterceptor.java
+++ b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/DummyInterceptor.java
@@ -1,49 +1,49 @@
-/**
- * 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.openejb.server.cxf.fault;
-
-import java.util.Collections;
-import java.util.Set;
-
-import javax.xml.namespace.QName;
-import javax.xml.ws.handler.MessageContext;
-import javax.xml.ws.handler.soap.SOAPHandler;
-import javax.xml.ws.handler.soap.SOAPMessageContext;
-
-/**
- * @version $Rev$
- */
-public class DummyInterceptor implements SOAPHandler<SOAPMessageContext> {
- public DummyInterceptor() {
- super();
- }
-
- public Set<QName> getHeaders() {
- return Collections.emptySet();
- }
-
- public void close(final MessageContext mc) {
- }
-
- public boolean handleFault(final SOAPMessageContext mc) {
- return true;
- }
-
- public boolean handleMessage(final SOAPMessageContext mc) {
- return true;
- }
+/**
+ * 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.openejb.server.cxf.fault;
+
+import java.util.Collections;
+import java.util.Set;
+
+import javax.xml.namespace.QName;
+import javax.xml.ws.handler.MessageContext;
+import javax.xml.ws.handler.soap.SOAPHandler;
+import javax.xml.ws.handler.soap.SOAPMessageContext;
+
+/**
+ * @version $Rev$
+ */
+public class DummyInterceptor implements SOAPHandler<SOAPMessageContext> {
+ public DummyInterceptor() {
+ super();
+ }
+
+ public Set<QName> getHeaders() {
+ return Collections.emptySet();
+ }
+
+ public void close(final MessageContext mc) {
+ }
+
+ public boolean handleFault(final SOAPMessageContext mc) {
+ return true;
+ }
+
+ public boolean handleMessage(final SOAPMessageContext mc) {
+ return true;
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordException.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordException.java b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordException.java
index beacfe8..10bcf7a 100644
--- a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordException.java
+++ b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordException.java
@@ -1,42 +1,42 @@
-/**
- * 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.openejb.server.cxf.fault;
-
-import javax.xml.ws.WebFault;
-
-/**
- * @version $Rev$
- */
-@WebFault
-public class WrongPasswordException extends Exception {
-
- public WrongPasswordException() {
- super();
- }
-
- public WrongPasswordException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
- public WrongPasswordException(final String message) {
- super(message);
- }
-
- public WrongPasswordException(final Throwable cause) {
- super(cause);
- }
+/**
+ * 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.openejb.server.cxf.fault;
+
+import javax.xml.ws.WebFault;
+
+/**
+ * @version $Rev$
+ */
+@WebFault
+public class WrongPasswordException extends Exception {
+
+ public WrongPasswordException() {
+ super();
+ }
+
+ public WrongPasswordException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+ public WrongPasswordException(final String message) {
+ super(message);
+ }
+
+ public WrongPasswordException(final Throwable cause) {
+ super(cause);
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordRuntimeException.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordRuntimeException.java b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordRuntimeException.java
index 5900996..b02a40b 100644
--- a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordRuntimeException.java
+++ b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/WrongPasswordRuntimeException.java
@@ -1,43 +1,43 @@
-/**
- * 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.openejb.server.cxf.fault;
-
-import javax.ejb.ApplicationException;
-
-/**
- * @version $Rev$
- */
-@ApplicationException
-// @WebFault // Not possible: a web fault must by a checked exception
-public class WrongPasswordRuntimeException extends RuntimeException {
-
- public WrongPasswordRuntimeException() {
- super();
- }
-
- public WrongPasswordRuntimeException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
- public WrongPasswordRuntimeException(final String message) {
- super(message);
- }
-
- public WrongPasswordRuntimeException(final Throwable cause) {
- super(cause);
- }
+/**
+ * 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.openejb.server.cxf.fault;
+
+import javax.ejb.ApplicationException;
+
+/**
+ * @version $Rev$
+ */
+@ApplicationException
+// @WebFault // Not possible: a web fault must by a checked exception
+public class WrongPasswordRuntimeException extends RuntimeException {
+
+ public WrongPasswordRuntimeException() {
+ super();
+ }
+
+ public WrongPasswordRuntimeException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+ public WrongPasswordRuntimeException(final String message) {
+ super(message);
+ }
+
+ public WrongPasswordRuntimeException(final Throwable cause) {
+ super(cause);
+ }
}
\ No newline at end of file
[09/12] tomee git commit: EOL
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/maven/tomee-maven-plugin/src/test/java/org/apache/openejb/maven/plugin/test/TomEEMavenPluginTest.java
----------------------------------------------------------------------
diff --git a/maven/tomee-maven-plugin/src/test/java/org/apache/openejb/maven/plugin/test/TomEEMavenPluginTest.java b/maven/tomee-maven-plugin/src/test/java/org/apache/openejb/maven/plugin/test/TomEEMavenPluginTest.java
index 2e2584e..7e33e25 100644
--- a/maven/tomee-maven-plugin/src/test/java/org/apache/openejb/maven/plugin/test/TomEEMavenPluginTest.java
+++ b/maven/tomee-maven-plugin/src/test/java/org/apache/openejb/maven/plugin/test/TomEEMavenPluginTest.java
@@ -1,69 +1,69 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.openejb.maven.plugin.test;
-
-import org.apache.openejb.loader.IO;
-import org.apache.openejb.maven.plugin.TomEEMavenPluginRule;
-import org.apache.openejb.maven.plugin.Url;
-import org.junit.Rule;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.net.URI;
-import java.net.URL;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertThat;
-
-public class TomEEMavenPluginTest {
-
- private final Logger logger = Logger.getLogger(TomEEMavenPluginTest.class.getName());
-
- @Rule
- public TomEEMavenPluginRule TMPRule = new TomEEMavenPluginRule();
-
- @Url
- private String url;
-
- @Test
- public void simpleStart() throws Exception {
- final String slurp = slurp(URI.create(url + "/docs").toURL(), 5);
- assertThat(slurp, containsString("Apache Tomcat"));
- }
-
- private String slurp(final URL url, int attempts) throws IOException {
- try {
- return IO.slurp(url);
- } catch (final IOException e) {
- if (attempts < 1) {
- logger.log(Level.SEVERE, "Failed to connect to: " + url, e);
- throw e;
- } else {
- try {
- Thread.sleep(1000);
- return slurp(url, --attempts);
- } catch (final InterruptedException ie) {
- //
- }
- }
- }
-
- return "";
- }
-}
+/*
+ * 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.openejb.maven.plugin.test;
+
+import org.apache.openejb.loader.IO;
+import org.apache.openejb.maven.plugin.TomEEMavenPluginRule;
+import org.apache.openejb.maven.plugin.Url;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URL;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertThat;
+
+public class TomEEMavenPluginTest {
+
+ private final Logger logger = Logger.getLogger(TomEEMavenPluginTest.class.getName());
+
+ @Rule
+ public TomEEMavenPluginRule TMPRule = new TomEEMavenPluginRule();
+
+ @Url
+ private String url;
+
+ @Test
+ public void simpleStart() throws Exception {
+ final String slurp = slurp(URI.create(url + "/docs").toURL(), 5);
+ assertThat(slurp, containsString("Apache Tomcat"));
+ }
+
+ private String slurp(final URL url, int attempts) throws IOException {
+ try {
+ return IO.slurp(url);
+ } catch (final IOException e) {
+ if (attempts < 1) {
+ logger.log(Level.SEVERE, "Failed to connect to: " + url, e);
+ throw e;
+ } else {
+ try {
+ Thread.sleep(1000);
+ return slurp(url, --attempts);
+ } catch (final InterruptedException ie) {
+ //
+ }
+ }
+ }
+
+ return "";
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-client/src/main/java/org/apache/openejb/client/ClientSecurity.java
----------------------------------------------------------------------
diff --git a/server/openejb-client/src/main/java/org/apache/openejb/client/ClientSecurity.java b/server/openejb-client/src/main/java/org/apache/openejb/client/ClientSecurity.java
index 1990958..99cacd1 100644
--- a/server/openejb-client/src/main/java/org/apache/openejb/client/ClientSecurity.java
+++ b/server/openejb-client/src/main/java/org/apache/openejb/client/ClientSecurity.java
@@ -1,204 +1,204 @@
-/**
- *
- * 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.openejb.client;
-
-import javax.security.auth.login.FailedLoginException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.rmi.RemoteException;
-
-public class ClientSecurity {
-
- public static final String IDENTITY_RESOLVER_STRATEGY = "openejb.client.identityResolver";
-
- private static ServerMetaData server;
- private static IdentityResolver identityResolver;
- private static Object staticClientIdentity;
- private static final InheritableThreadLocal<Object> threadClientIdentity = new InheritableThreadLocal<Object>();
-
- static {
- // determine the server uri
- final String serverUri = System.getProperty("openejb.server.uri");
-
- if (serverUri != null) {
- // determine the server location
- try {
- final URI location = new URI(serverUri);
- server = new ServerMetaData(location);
- } catch (final Exception e) {
- if (!serverUri.contains("://")) {
- try {
- final URI location = new URI("oejb://" + serverUri);
- server = new ServerMetaData(location);
- } catch (final URISyntaxException ignored) {
- }
- }
- }
- }
- }
-
- public static ServerMetaData getServer() {
- return server;
- }
-
- public static void setServer(final ServerMetaData server) {
- ClientSecurity.server = server;
- }
-
- /**
- * Login the spedified user using the specified password. This is a global login for the
- * entire Java Virtural Machine. If you would like to have a thread scoped login, use
- * ClientSecurity.login(username, password, true);
- * </p>
- * This is the equivalent of ClientSecurity.login(username, password, false);
- *
- * @param username the user to login
- * @param password the password for the user
- * @throws FailedLoginException if the username and password combination are not valid or
- * if there is a problem communiating with the server
- */
- public static void login(final String username, final String password) throws FailedLoginException {
- login(username, password, false);
- }
-
- /**
- * Login the spedified user using the specified password either globally for the
- * entire Java Virtural Machine or scoped to the thread.
- * </p>
- * When using thread scoped login, you should logout in a finally block. This particularly
- * when using thread pools. If a thread is returned to the pool with a login attached to the
- * thread the next user of that thread will inherit the thread scoped login.
- *
- * @param username the user to login
- * @param password the password for the user
- * @param threadScoped if true the login is scoped to the thread; otherwise the login is global
- * for the entire Java Virtural Machine
- * @throws FailedLoginException if the username and password combination are not valid or
- * if there is a problem communiating with the server
- */
- public static void login(final String username, final String password, final boolean threadScoped) throws FailedLoginException {
- final Object clientIdentity = directAuthentication(username, password, server);
- if (threadScoped) {
- threadClientIdentity.set(clientIdentity);
- } else {
- staticClientIdentity = clientIdentity;
- }
- identityResolver = new SimpleIdentityResolver();
- }
-
- /**
- * Clears the thread and global login data.
- */
- public static void logout() {
- threadClientIdentity.set(null);
- staticClientIdentity = null;
- }
-
- /**
- * This is a helper method for login modules. Directly authenticates with the server using the specified
- * username and password returning the identity token for the client. This methods does not store the
- * identity token and the caller must arrange for the to be available to the OpenEJB proxies via an
- * IdentityResolver.
- *
- * @param username the username for authentication
- * @param password the password for authentication
- * @param server ServerMetaData
- * @return the client identity token
- * @throws FailedLoginException if the username password combination is not valid
- */
- public static Object directAuthentication(final String username, final String password, final ServerMetaData server) throws FailedLoginException {
- return directAuthentication(null, username, password, server);
- }
-
- public static Object directAuthentication(final String securityRealm, final String username, final String password, final ServerMetaData server) throws FailedLoginException {
- // authenticate
- final AuthenticationRequest authReq = new AuthenticationRequest(securityRealm, username, password);
- final AuthenticationResponse authRes;
- try {
- authRes = (AuthenticationResponse) Client.request(authReq, new AuthenticationResponse(), server);
- } catch (final RemoteException e) {
- throw (FailedLoginException) new FailedLoginException("Unable to authenticate with server " + server).initCause(e);
- }
-
- // check the response
- if (authRes.getResponseCode() != ResponseCodes.AUTH_GRANTED) {
- throw (FailedLoginException) new FailedLoginException("This principal is not authenticated.").initCause(authRes.getDeniedCause());
- }
-
- // return the response object
- return authRes.getIdentity().getClientIdentity();
- }
-
- public static Object getIdentity() {
- return getIdentityResolver().getIdentity();
- }
-
- public static IdentityResolver getIdentityResolver() {
- if (identityResolver == null) {
- final String strategy = System.getProperty(IDENTITY_RESOLVER_STRATEGY);
- if (strategy == null) {
- identityResolver = new JaasIdentityResolver();
- } else {
- // find the strategy class
- final ResourceFinder finder = new ResourceFinder("META-INF/");
- final Class identityResolverClass;
- try {
- identityResolverClass = finder.findClass(IdentityResolver.class.getName() + "/" + strategy);
- } catch (final Exception e) {
- throw new IllegalArgumentException("Could not find client identity strategy '" + strategy + "'");
- }
-
- // verify the interface
- if (!IdentityResolver.class.isAssignableFrom(identityResolverClass)) {
- throw new IllegalArgumentException("Client identity strategy '" + strategy + "' " +
- "class '" + identityResolverClass.getName() + "' does not implement the " +
- "interface '" + IdentityResolver.class.getSimpleName() + "'");
- }
-
- // create the class
- try {
- identityResolver = (IdentityResolver) identityResolverClass.newInstance();
- } catch (final Exception e) {
- throw new IllegalArgumentException("Unable to create client identity strategy '" + strategy + "' " +
- "class '" + identityResolverClass.getName() + "'", e);
- }
- }
-
- }
- return identityResolver;
- }
-
- public static void setIdentityResolver(final IdentityResolver identityResolver) {
- ClientSecurity.identityResolver = identityResolver;
- }
-
- private ClientSecurity() {
- }
-
- public static class SimpleIdentityResolver implements IdentityResolver {
-
- @Override
- public Object getIdentity() {
- Object clientIdentity = threadClientIdentity.get();
- if (clientIdentity == null) {
- clientIdentity = staticClientIdentity;
- }
- return clientIdentity;
- }
- }
-}
+/**
+ *
+ * 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.openejb.client;
+
+import javax.security.auth.login.FailedLoginException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.rmi.RemoteException;
+
+public class ClientSecurity {
+
+ public static final String IDENTITY_RESOLVER_STRATEGY = "openejb.client.identityResolver";
+
+ private static ServerMetaData server;
+ private static IdentityResolver identityResolver;
+ private static Object staticClientIdentity;
+ private static final InheritableThreadLocal<Object> threadClientIdentity = new InheritableThreadLocal<Object>();
+
+ static {
+ // determine the server uri
+ final String serverUri = System.getProperty("openejb.server.uri");
+
+ if (serverUri != null) {
+ // determine the server location
+ try {
+ final URI location = new URI(serverUri);
+ server = new ServerMetaData(location);
+ } catch (final Exception e) {
+ if (!serverUri.contains("://")) {
+ try {
+ final URI location = new URI("oejb://" + serverUri);
+ server = new ServerMetaData(location);
+ } catch (final URISyntaxException ignored) {
+ }
+ }
+ }
+ }
+ }
+
+ public static ServerMetaData getServer() {
+ return server;
+ }
+
+ public static void setServer(final ServerMetaData server) {
+ ClientSecurity.server = server;
+ }
+
+ /**
+ * Login the spedified user using the specified password. This is a global login for the
+ * entire Java Virtural Machine. If you would like to have a thread scoped login, use
+ * ClientSecurity.login(username, password, true);
+ * </p>
+ * This is the equivalent of ClientSecurity.login(username, password, false);
+ *
+ * @param username the user to login
+ * @param password the password for the user
+ * @throws FailedLoginException if the username and password combination are not valid or
+ * if there is a problem communiating with the server
+ */
+ public static void login(final String username, final String password) throws FailedLoginException {
+ login(username, password, false);
+ }
+
+ /**
+ * Login the spedified user using the specified password either globally for the
+ * entire Java Virtural Machine or scoped to the thread.
+ * </p>
+ * When using thread scoped login, you should logout in a finally block. This particularly
+ * when using thread pools. If a thread is returned to the pool with a login attached to the
+ * thread the next user of that thread will inherit the thread scoped login.
+ *
+ * @param username the user to login
+ * @param password the password for the user
+ * @param threadScoped if true the login is scoped to the thread; otherwise the login is global
+ * for the entire Java Virtural Machine
+ * @throws FailedLoginException if the username and password combination are not valid or
+ * if there is a problem communiating with the server
+ */
+ public static void login(final String username, final String password, final boolean threadScoped) throws FailedLoginException {
+ final Object clientIdentity = directAuthentication(username, password, server);
+ if (threadScoped) {
+ threadClientIdentity.set(clientIdentity);
+ } else {
+ staticClientIdentity = clientIdentity;
+ }
+ identityResolver = new SimpleIdentityResolver();
+ }
+
+ /**
+ * Clears the thread and global login data.
+ */
+ public static void logout() {
+ threadClientIdentity.set(null);
+ staticClientIdentity = null;
+ }
+
+ /**
+ * This is a helper method for login modules. Directly authenticates with the server using the specified
+ * username and password returning the identity token for the client. This methods does not store the
+ * identity token and the caller must arrange for the to be available to the OpenEJB proxies via an
+ * IdentityResolver.
+ *
+ * @param username the username for authentication
+ * @param password the password for authentication
+ * @param server ServerMetaData
+ * @return the client identity token
+ * @throws FailedLoginException if the username password combination is not valid
+ */
+ public static Object directAuthentication(final String username, final String password, final ServerMetaData server) throws FailedLoginException {
+ return directAuthentication(null, username, password, server);
+ }
+
+ public static Object directAuthentication(final String securityRealm, final String username, final String password, final ServerMetaData server) throws FailedLoginException {
+ // authenticate
+ final AuthenticationRequest authReq = new AuthenticationRequest(securityRealm, username, password);
+ final AuthenticationResponse authRes;
+ try {
+ authRes = (AuthenticationResponse) Client.request(authReq, new AuthenticationResponse(), server);
+ } catch (final RemoteException e) {
+ throw (FailedLoginException) new FailedLoginException("Unable to authenticate with server " + server).initCause(e);
+ }
+
+ // check the response
+ if (authRes.getResponseCode() != ResponseCodes.AUTH_GRANTED) {
+ throw (FailedLoginException) new FailedLoginException("This principal is not authenticated.").initCause(authRes.getDeniedCause());
+ }
+
+ // return the response object
+ return authRes.getIdentity().getClientIdentity();
+ }
+
+ public static Object getIdentity() {
+ return getIdentityResolver().getIdentity();
+ }
+
+ public static IdentityResolver getIdentityResolver() {
+ if (identityResolver == null) {
+ final String strategy = System.getProperty(IDENTITY_RESOLVER_STRATEGY);
+ if (strategy == null) {
+ identityResolver = new JaasIdentityResolver();
+ } else {
+ // find the strategy class
+ final ResourceFinder finder = new ResourceFinder("META-INF/");
+ final Class identityResolverClass;
+ try {
+ identityResolverClass = finder.findClass(IdentityResolver.class.getName() + "/" + strategy);
+ } catch (final Exception e) {
+ throw new IllegalArgumentException("Could not find client identity strategy '" + strategy + "'");
+ }
+
+ // verify the interface
+ if (!IdentityResolver.class.isAssignableFrom(identityResolverClass)) {
+ throw new IllegalArgumentException("Client identity strategy '" + strategy + "' " +
+ "class '" + identityResolverClass.getName() + "' does not implement the " +
+ "interface '" + IdentityResolver.class.getSimpleName() + "'");
+ }
+
+ // create the class
+ try {
+ identityResolver = (IdentityResolver) identityResolverClass.newInstance();
+ } catch (final Exception e) {
+ throw new IllegalArgumentException("Unable to create client identity strategy '" + strategy + "' " +
+ "class '" + identityResolverClass.getName() + "'", e);
+ }
+ }
+
+ }
+ return identityResolver;
+ }
+
+ public static void setIdentityResolver(final IdentityResolver identityResolver) {
+ ClientSecurity.identityResolver = identityResolver;
+ }
+
+ private ClientSecurity() {
+ }
+
+ public static class SimpleIdentityResolver implements IdentityResolver {
+
+ @Override
+ public Object getIdentity() {
+ Object clientIdentity = threadClientIdentity.get();
+ if (clientIdentity == null) {
+ clientIdentity = staticClientIdentity;
+ }
+ return clientIdentity;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-client/src/main/java/org/apache/openejb/client/DirectConnectionStrategy.java
----------------------------------------------------------------------
diff --git a/server/openejb-client/src/main/java/org/apache/openejb/client/DirectConnectionStrategy.java b/server/openejb-client/src/main/java/org/apache/openejb/client/DirectConnectionStrategy.java
index 56d2623..c066c9f 100755
--- a/server/openejb-client/src/main/java/org/apache/openejb/client/DirectConnectionStrategy.java
+++ b/server/openejb-client/src/main/java/org/apache/openejb/client/DirectConnectionStrategy.java
@@ -1,33 +1,33 @@
-/*
- * 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.openejb.client;
-
-import java.io.IOException;
-
-public class DirectConnectionStrategy implements ConnectionStrategy {
-
- @Override
- public Connection connect(final ClusterMetaData cluster, final ServerMetaData server) throws IOException {
- final Connection connection = ConnectionManager.getConnection(server.getLocation());
-
- // Grabbing the URI from the associated connection allows the ConnectionFactory to
- // employ discovery to find and connect to a server. We then attempt to connect
- // to the discovered server rather than repeat the discovery process again.
- cluster.setLastLocation(connection.getURI());
- return connection;
- }
-}
+/*
+ * 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.openejb.client;
+
+import java.io.IOException;
+
+public class DirectConnectionStrategy implements ConnectionStrategy {
+
+ @Override
+ public Connection connect(final ClusterMetaData cluster, final ServerMetaData server) throws IOException {
+ final Connection connection = ConnectionManager.getConnection(server.getLocation());
+
+ // Grabbing the URI from the associated connection allows the ConnectionFactory to
+ // employ discovery to find and connect to a server. We then attempt to connect
+ // to the discovered server rather than repeat the discovery process again.
+ cluster.setLastLocation(connection.getURI());
+ return connection;
+ }
+}
[05/12] tomee git commit: EOL
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-daemon/src/main/java/org/apache/openejb/daemon/NTService.java
----------------------------------------------------------------------
diff --git a/server/openejb-daemon/src/main/java/org/apache/openejb/daemon/NTService.java b/server/openejb-daemon/src/main/java/org/apache/openejb/daemon/NTService.java
index 54749fe..aba70e1 100644
--- a/server/openejb-daemon/src/main/java/org/apache/openejb/daemon/NTService.java
+++ b/server/openejb-daemon/src/main/java/org/apache/openejb/daemon/NTService.java
@@ -1,114 +1,114 @@
-/*
- * 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.openejb.daemon;
-
-import org.apache.openejb.cli.Bootstrap;
-import org.apache.openejb.loader.SystemInstance;
-import org.apache.openejb.server.Server;
-import org.apache.openejb.server.ServerRuntimeException;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public class NTService {
-
- private static final NTService instance = new NTService();
- private final AtomicBoolean running = new AtomicBoolean(false);
-
- /**
- * Called by Apache Daemon
- *
- * @param args Start arguments
- */
- public static void start(final String[] args) {
- try {
- instance.startImpl(args);
- } catch (final Throwable e) {
- e.printStackTrace(System.err);
- }
- }
-
- /**
- * Called by Apache Daemon
- *
- * @param args Stop arguments - Not used
- */
- public static void stop(final String[] args) {
- try {
- instance.stopImpl();
- } catch (final Throwable e) {
- e.printStackTrace(System.err);
- }
- }
-
- private NTService() {
- }
-
- private void startImpl(String[] args) {
- if (!running.getAndSet(true)) {
-
- if (null == args) {
- args = new String[0];
- }
-
- if (null == System.getProperty("openejb.home")) {
- System.setProperty("openejb.home", System.getProperty("user.dir"));
- }
-
- final ArrayList<String> list = new ArrayList<String>();
- list.addAll(Arrays.asList(args));
-
- if (!list.contains("start")) {
- list.add("start");
- }
-
- try {
- System.out.println("Starting NTService: " + list);
- Bootstrap.main(list.toArray(new String[list.size()]));
-
- //The process has finished
- running.set(false);
-
- } catch (final Exception e) {
- running.set(false);
- throw new RuntimeException("Failed to Bootstrap OpenEJB", e);
- }
-
- }
- }
-
- private void stopImpl() {
- if (running.getAndSet(false)) {
-
- final Server server = SystemInstance.get().getComponent(Server.class);
-
- if (null != server) {
- try {
- System.out.println("Stopping NTService");
- server.stop();
- } catch (final Exception e) {
-
- //Failed to stop
- running.set(true);
- e.printStackTrace(System.err);
- }
- }
- }
- }
-
-}
+/*
+ * 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.openejb.daemon;
+
+import org.apache.openejb.cli.Bootstrap;
+import org.apache.openejb.loader.SystemInstance;
+import org.apache.openejb.server.Server;
+import org.apache.openejb.server.ServerRuntimeException;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+public class NTService {
+
+ private static final NTService instance = new NTService();
+ private final AtomicBoolean running = new AtomicBoolean(false);
+
+ /**
+ * Called by Apache Daemon
+ *
+ * @param args Start arguments
+ */
+ public static void start(final String[] args) {
+ try {
+ instance.startImpl(args);
+ } catch (final Throwable e) {
+ e.printStackTrace(System.err);
+ }
+ }
+
+ /**
+ * Called by Apache Daemon
+ *
+ * @param args Stop arguments - Not used
+ */
+ public static void stop(final String[] args) {
+ try {
+ instance.stopImpl();
+ } catch (final Throwable e) {
+ e.printStackTrace(System.err);
+ }
+ }
+
+ private NTService() {
+ }
+
+ private void startImpl(String[] args) {
+ if (!running.getAndSet(true)) {
+
+ if (null == args) {
+ args = new String[0];
+ }
+
+ if (null == System.getProperty("openejb.home")) {
+ System.setProperty("openejb.home", System.getProperty("user.dir"));
+ }
+
+ final ArrayList<String> list = new ArrayList<String>();
+ list.addAll(Arrays.asList(args));
+
+ if (!list.contains("start")) {
+ list.add("start");
+ }
+
+ try {
+ System.out.println("Starting NTService: " + list);
+ Bootstrap.main(list.toArray(new String[list.size()]));
+
+ //The process has finished
+ running.set(false);
+
+ } catch (final Exception e) {
+ running.set(false);
+ throw new RuntimeException("Failed to Bootstrap OpenEJB", e);
+ }
+
+ }
+ }
+
+ private void stopImpl() {
+ if (running.getAndSet(false)) {
+
+ final Server server = SystemInstance.get().getComponent(Server.class);
+
+ if (null != server) {
+ try {
+ System.out.println("Stopping NTService");
+ server.stop();
+ } catch (final Exception e) {
+
+ //Failed to stop
+ running.set(true);
+ e.printStackTrace(System.err);
+ }
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/EjbServer.java
----------------------------------------------------------------------
diff --git a/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/EjbServer.java b/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/EjbServer.java
index da49618..0af3626 100644
--- a/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/EjbServer.java
+++ b/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/EjbServer.java
@@ -1,144 +1,144 @@
-/**
- * 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.openejb.server.ejbd;
-
-import org.apache.openejb.ProxyInfo;
-import org.apache.openejb.core.ServerFederation;
-import org.apache.openejb.server.ServiceException;
-
-import javax.ejb.EJBHome;
-import javax.ejb.EJBMetaData;
-import javax.ejb.EJBObject;
-import javax.ejb.Handle;
-import javax.ejb.HomeHandle;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.Socket;
-import java.util.Properties;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class EjbServer implements org.apache.openejb.server.ServerService, org.apache.openejb.spi.ApplicationServer {
-
- protected KeepAliveServer keepAlive;
- protected EjbDaemon server;
-
- public EjbServer() {
-
- }
-
- @Override
- public void init(final Properties props) throws Exception {
- server = new EjbDaemon();
- if (props.getProperty("name") == null) { // to let server be component aware
- props.setProperty("name", getName());
- }
- server.init(props);
- keepAlive = new KeepAliveServer(this, server.isGzip());
- }
-
- @Override
- public void start() throws ServiceException {
- if (null != keepAlive) {
- keepAlive.start();
- } else {
- logNotInitialized();
- }
- }
-
- private void logNotInitialized() {
- Logger.getLogger(EjbServer.class.getName()).log(Level.WARNING, "EjbServer was not initialized");
- }
-
- @Override
- public void stop() throws ServiceException {
- if (null != keepAlive) {
- keepAlive.stop();
- } else {
- logNotInitialized();
- }
- }
-
- @Override
- public String getName() {
- return "ejbd";
- }
-
- @Override
- public int getPort() {
- return 0;
- }
-
- @Override
- public void service(final Socket socket) throws ServiceException, IOException {
- if (null != keepAlive) {
- keepAlive.service(socket);
- } else {
- logNotInitialized();
- }
- }
-
- @Override
- public void service(final InputStream inputStream, final OutputStream outputStream) throws ServiceException, IOException {
-
- ServerFederation.setApplicationServer(server);
- final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
-
- try {
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- server.service(inputStream, outputStream);
- } finally {
- Thread.currentThread().setContextClassLoader(oldCl);
- }
- }
-
- @Override
- public String getIP() {
- return "";
- }
-
- @Override
- public EJBMetaData getEJBMetaData(final ProxyInfo info) {
- return server.getEJBMetaData(info);
- }
-
- @Override
- public Handle getHandle(final ProxyInfo info) {
- return server.getHandle(info);
- }
-
- @Override
- public HomeHandle getHomeHandle(final ProxyInfo info) {
- return server.getHomeHandle(info);
- }
-
- @Override
- public EJBObject getEJBObject(final ProxyInfo info) {
- return server.getEJBObject(info);
- }
-
- @Override
- public Object getBusinessObject(final ProxyInfo info) {
- return server.getBusinessObject(info);
- }
-
- @Override
- public EJBHome getEJBHome(final ProxyInfo info) {
- return server.getEJBHome(info);
- }
-}
+/**
+ * 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.openejb.server.ejbd;
+
+import org.apache.openejb.ProxyInfo;
+import org.apache.openejb.core.ServerFederation;
+import org.apache.openejb.server.ServiceException;
+
+import javax.ejb.EJBHome;
+import javax.ejb.EJBMetaData;
+import javax.ejb.EJBObject;
+import javax.ejb.Handle;
+import javax.ejb.HomeHandle;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class EjbServer implements org.apache.openejb.server.ServerService, org.apache.openejb.spi.ApplicationServer {
+
+ protected KeepAliveServer keepAlive;
+ protected EjbDaemon server;
+
+ public EjbServer() {
+
+ }
+
+ @Override
+ public void init(final Properties props) throws Exception {
+ server = new EjbDaemon();
+ if (props.getProperty("name") == null) { // to let server be component aware
+ props.setProperty("name", getName());
+ }
+ server.init(props);
+ keepAlive = new KeepAliveServer(this, server.isGzip());
+ }
+
+ @Override
+ public void start() throws ServiceException {
+ if (null != keepAlive) {
+ keepAlive.start();
+ } else {
+ logNotInitialized();
+ }
+ }
+
+ private void logNotInitialized() {
+ Logger.getLogger(EjbServer.class.getName()).log(Level.WARNING, "EjbServer was not initialized");
+ }
+
+ @Override
+ public void stop() throws ServiceException {
+ if (null != keepAlive) {
+ keepAlive.stop();
+ } else {
+ logNotInitialized();
+ }
+ }
+
+ @Override
+ public String getName() {
+ return "ejbd";
+ }
+
+ @Override
+ public int getPort() {
+ return 0;
+ }
+
+ @Override
+ public void service(final Socket socket) throws ServiceException, IOException {
+ if (null != keepAlive) {
+ keepAlive.service(socket);
+ } else {
+ logNotInitialized();
+ }
+ }
+
+ @Override
+ public void service(final InputStream inputStream, final OutputStream outputStream) throws ServiceException, IOException {
+
+ ServerFederation.setApplicationServer(server);
+ final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
+
+ try {
+ Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+ server.service(inputStream, outputStream);
+ } finally {
+ Thread.currentThread().setContextClassLoader(oldCl);
+ }
+ }
+
+ @Override
+ public String getIP() {
+ return "";
+ }
+
+ @Override
+ public EJBMetaData getEJBMetaData(final ProxyInfo info) {
+ return server.getEJBMetaData(info);
+ }
+
+ @Override
+ public Handle getHandle(final ProxyInfo info) {
+ return server.getHandle(info);
+ }
+
+ @Override
+ public HomeHandle getHomeHandle(final ProxyInfo info) {
+ return server.getHomeHandle(info);
+ }
+
+ @Override
+ public EJBObject getEJBObject(final ProxyInfo info) {
+ return server.getEJBObject(info);
+ }
+
+ @Override
+ public Object getBusinessObject(final ProxyInfo info) {
+ return server.getBusinessObject(info);
+ }
+
+ @Override
+ public EJBHome getEJBHome(final ProxyInfo info) {
+ return server.getEJBHome(info);
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-multicast/src/main/java/org/apache/openejb/server/discovery/MulticastPulseAgent.java
----------------------------------------------------------------------
diff --git a/server/openejb-multicast/src/main/java/org/apache/openejb/server/discovery/MulticastPulseAgent.java b/server/openejb-multicast/src/main/java/org/apache/openejb/server/discovery/MulticastPulseAgent.java
index 7a18505..75a0886 100644
--- a/server/openejb-multicast/src/main/java/org/apache/openejb/server/discovery/MulticastPulseAgent.java
+++ b/server/openejb-multicast/src/main/java/org/apache/openejb/server/discovery/MulticastPulseAgent.java
@@ -1,760 +1,760 @@
-package org.apache.openejb.server.discovery;
-
-import org.apache.openejb.loader.Options;
-import org.apache.openejb.server.DiscoveryAgent;
-import org.apache.openejb.server.DiscoveryListener;
-import org.apache.openejb.server.SelfManaging;
-import org.apache.openejb.server.ServerService;
-import org.apache.openejb.server.ServiceException;
-import org.apache.openejb.util.DaemonThreadFactory;
-import org.apache.openejb.util.LogCategory;
-import org.apache.openejb.util.Logger;
-import org.apache.openejb.util.OptionsLog;
-import sun.net.util.IPAddressUtil;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.DatagramPacket;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.MulticastSocket;
-import java.net.NetworkInterface;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.URI;
-import java.net.UnknownHostException;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.ReentrantLock;
-
-/**
- * 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.
- */
-public class MulticastPulseAgent implements DiscoveryAgent, ServerService, SelfManaging {
-
- private static final Logger log = Logger.getInstance(LogCategory.OPENEJB_SERVER.createChild("discovery").createChild("multipulse"), MulticastPulseAgent.class);
- private static NetworkInterface[] interfaces = null;
- private static ExecutorService executor = null;
- private static final Charset UTF8 = Charset.forName("UTF-8");
- private static final int TTL = Integer.parseInt(System.getProperty("org.apache.openejb.multipulse.ttl", "32"));
-
- public static final String SERVER = "OpenEJB.MCP.Server:";
- public static final String CLIENT = "OpenEJB.MCP.Client:";
- public static final String BADURI = ":BadUri:";
- public static final String EMPTY = "NoService";
-
- private final ReentrantLock lock = new ReentrantLock();
- private final Set<String> ignore = Collections.synchronizedSet(new HashSet<String>());
- private final Set<URI> uriSet = new HashSet<URI>();
- private final AtomicBoolean running = new AtomicBoolean(false);
- final ArrayList<Future> futures = new ArrayList<Future>();
- private MulticastSocket[] sockets = null;
- private InetSocketAddress address = null;
-
- private String multicast = "239.255.3.2";
- private String group = "default";
- private int port = 6142;
- private DatagramPacket response = null;
- private DiscoveryListener listener = null;
- private boolean loopbackOnly = true;
-
- /**
- * This agent listens for client pulses on a defined multicast channel.
- * On receipt of a valid pulse the agent responds with its own pulse for
- * a defined amount of time and rate. A client can deliver a pulse as often as
- * required until it is happy of the server response.
- * <p/>
- * Both server and client deliver crafted information payloads.
- * <p/>
- * The client pulse contains OpenEJB.MCP.Client:(group or *)[:BadUri:URI]
- * The server will only respond to a request for it's own group or *
- * The optional :BadUri: is used by clients to notify a server that it is sending out unreachable URI's
- * <p/>
- * The server response pulse contains OpenEJB.MCP.Server:(Service|Service)|(Comma separated host list)
- */
- public MulticastPulseAgent() {
- }
-
- private static synchronized NetworkInterface[] getInterfaces() {
- if (null == interfaces) {
- interfaces = getNetworkInterfaces();
- }
-
- return interfaces;
- }
-
- private static synchronized ExecutorService getExecutorService() {
-
- if (null == executor) {
-
- int length = getInterfaces().length;
- if (length < 1) {
- length = 1;
- }
-
- executor = Executors.newFixedThreadPool(length * 3, new DaemonThreadFactory("multicast-pulse-agent-"));
- }
-
- return executor;
- }
-
- @Override
- public void init(final Properties p) throws Exception {
- final Options o = new Options(p);
- o.setLogger(new OptionsLog(log));
-
- this.ignore.add("localhost");
- this.ignore.add("::1");
- this.ignore.add("127.0.0.1");
-
- try {
- final String[] ignoreList = o.get("ignore", "").split(",");
- for (final String s : ignoreList) {
- if (null != s && s.trim().length() > 0) {
- this.ignore.add(s.trim().toLowerCase());
- }
- }
- } catch (final Exception e) {
- log.warning("Invalid ignore parameter. Should be a lowercase single host or comma seperated list of hosts to ignore like: ignore=host1,host2,ipv4,ipv6");
- }
-
- this.multicast = o.get("bind", this.multicast);
- this.port = o.get("port", this.port);
- this.group = o.get("group", this.group);
-
- final InetAddress ia = InetAddress.getByName(this.multicast);
- this.address = new InetSocketAddress(ia, this.port);
- this.buildPacket();
- }
-
- private void buildPacket() throws SocketException {
-
- final ReentrantLock l = this.lock;
- l.lock();
-
- try {
- this.loopbackOnly = true;
- for (final URI uri : this.uriSet) {
- if (!isLoopback(uri.getHost())) {
- this.loopbackOnly = false;
- break;
- }
- }
-
- final String hosts = getHosts(this.ignore);
- final StringBuilder sb = new StringBuilder(SERVER);
- sb.append(this.group);
- sb.append(':');
-
- if (this.uriSet.size() > 0) {
- for (final URI uri : this.uriSet) {
- sb.append(uri.toASCIIString());
- sb.append('|');
- }
- } else {
- sb.append(EMPTY);
- sb.append('|');
- }
-
- sb.append(hosts);
-
- final byte[] bytes = (sb.toString()).getBytes(UTF8);
- this.response = new DatagramPacket(bytes, bytes.length, this.address);
-
- if (log.isDebugEnabled()) {
- log.debug("MultiPulse packet is: " + sb);
- }
-
- if (bytes.length > 2048) {
- log.warning("MultiPulse packet is larger than 2048 bytes, clients will not be able to read the packet" +
- "\n - You should define the 'ignore' property to filter out unreachable addresses: " + sb);
- }
- } finally {
- l.unlock();
- }
- }
-
- public DatagramPacket getResponsePacket() {
- final ReentrantLock l = this.lock;
- l.lock();
-
- try {
- return this.response;
- } finally {
- l.unlock();
- }
- }
-
- @Override
- public void setDiscoveryListener(final DiscoveryListener listener) {
- this.listener = listener;
- }
-
- public DiscoveryListener getDiscoveryListener() {
- return listener;
- }
-
- @Override
- public void registerService(URI uri) throws IOException {
-
- uri = parseUri(uri);
-
- if (this.uriSet.add(uri)) {
- this.buildPacket();
- this.fireEvent(uri, true);
- }
- }
-
- @Override
- public void unregisterService(final URI uri) throws IOException {
-
- final URI tmp = parseUri(uri);
-
- if (this.uriSet.remove(tmp)) {
- this.fireEvent(uri, false);
- }
- }
-
- @Override
- public void reportFailed(final URI serviceUri) throws IOException {
- this.unregisterService(serviceUri);
- }
-
- /**
- * Strip the scheme
- *
- * @param uri URI to strip the scheme
- * @return Stripped URI
- */
- private URI parseUri(final URI uri) {
- return URI.create(uri.getSchemeSpecificPart());
- }
-
- private void fireEvent(final URI uri, final boolean add) {
- if (null != this.listener) {
- final DiscoveryListener dl = this.listener;
- getExecutorService().execute(new Runnable() {
- @Override
- public void run() {
- if (add) {
- dl.serviceAdded(uri);
- } else {
- dl.serviceRemoved(uri);
- }
- }
- });
- }
- }
-
- @Override
- public void start() throws ServiceException {
- if (!this.running.getAndSet(true)) {
-
- try {
- this.sockets = getSockets(this.multicast, this.port);
- } catch (final Exception e) {
- throw new ServiceException("Failed to get Multicast sockets", e);
- }
-
- final CountDownLatch latch = new CountDownLatch(this.sockets.length);
- final String mpg = this.group;
- final boolean isLoopBackOnly = this.loopbackOnly;
- final ExecutorService executorService = getExecutorService();
- final MulticastPulseAgent agent = MulticastPulseAgent.this;
-
- for (final MulticastSocket socket : this.sockets) {
-
- final String socketKey;
- try {
- socketKey = socket.getNetworkInterface().toString();
- } catch (final SocketException e) {
- log.error("Failed to get network interface name on: " + socket, e);
- continue;
- }
-
- final Sender sender = new Sender(this, socketKey, socket);
- this.futures.add(executorService.submit(sender));
-
- this.futures.add(executorService.submit(new Runnable() {
- @Override
- public void run() {
-
- final DatagramPacket request = new DatagramPacket(new byte[2048], 2048);
- latch.countDown();
-
- while (agent.running.get()) {
-
- try {
- socket.receive(request);
- final SocketAddress sa = request.getSocketAddress();
-
- if (null != sa) {
-
- String req = new String(request.getData(), 0, request.getLength());
-
- if (req.startsWith(CLIENT)) {
-
- final int ix = req.indexOf(BADURI);
- String badUri = null;
-
- if (ix > 0) {
- //The client is notifying of a bad uri
- badUri = req.substring(ix).replace(BADURI, "");
- req = req.substring(0, ix).replace(CLIENT, "");
- } else {
- req = (req.replace(CLIENT, ""));
- }
-
- //Is this a group or global pulse request
- if (mpg.equals(req) || "*".equals(req)) {
-
- //Is there a bad url and is it this agent broadcasting the bad URI?
- if (null != badUri) {
- if (getHosts(agent.ignore).contains(badUri)) {
- final ReentrantLock l = agent.lock;
- l.lock();
-
- try {
- //Remove it and rebuild our broadcast packet
- if (agent.ignore.add(badUri)) {
- agent.buildPacket();
- log.warning("This server has removed the unreachable host '" + badUri + "' from discovery, you should consider adding" +
- " this to the 'ignore' property in the multipulse.properties file");
- }
- } finally {
- l.unlock();
- }
- }
-
- agent.fireEvent(URI.create("OpenEJB" + BADURI + badUri), false);
-
- } else {
-
- //Normal client multicast pulse request
- final String client = ((InetSocketAddress) sa).getAddress().getHostAddress();
-
- if (isLoopBackOnly && !MulticastPulseAgent.isLocalAddress(client, false)) {
- //We only have local services, so make sure the request is from a local source else ignore it
- if (log.isDebugEnabled()) {
- log.debug(String.format("Ignoring remote client %1$s pulse request for group: %2$s - No remote services available",
- client,
- req));
- }
- } else {
-
- //We have received a valid pulse request
- if (log.isDebugEnabled()) {
- log.debug(String.format("Answering client '%1$s' pulse request for group: '%2$s' on '%3$s'", client, req, socketKey));
- }
-
- //Renew response pulse
- sender.pulseResponse();
- }
- }
- }
- }
- }
-
- } catch (final Exception e) {
- if (log.isDebugEnabled()) {
- log.debug("MulticastPulseAgent request error: " + e.getMessage(), e);
- }
- }
- }
-
- try {
- socket.close();
- } catch (final Throwable e) {
- //Ignore
- }
- }
- }));
- }
-
- try {
- //Give threads a reasonable amount of time to start
- latch.await(5, TimeUnit.SECONDS);
- } catch (final InterruptedException e) {
- this.stop();
- }
- }
- }
-
- @Override
- public void stop() throws ServiceException {
- if (this.running.getAndSet(false)) {
-
- try {
- //Iterrupt threads
- for (final Future future : this.futures) {
- try {
- future.cancel(true);
- } catch (final Throwable e) {
- //Ignore
- }
- }
-
- //Wait for threads to complete
- for (final Future future : this.futures) {
- try {
- future.get();
- } catch (final Throwable e) {
- //Ignore
- }
- }
- } finally {
- this.futures.clear();
- }
-
- if (null != this.sockets) {
- try {
- for (final MulticastSocket s : this.sockets) {
- try {
- s.close();
- } catch (final Throwable e) {
- //Ignore
- }
- }
- } finally {
- this.sockets = null;
- }
- }
- }
- }
-
- @Override
- public void service(final InputStream in, final OutputStream out) throws ServiceException, IOException {
- //Ignore
- }
-
- @Override
- public void service(final Socket socket) throws ServiceException, IOException {
- //Ignore
- }
-
- @Override
- public String getName() {
- return "multipulse";
- }
-
- @Override
- public String getIP() {
- return this.multicast;
- }
-
- @Override
- public int getPort() {
- return this.port;
- }
-
- /**
- * Lists current broadcast hosts as a comma separated list.
- * Used principally for testing.
- *
- * @return String
- */
- public String getHosts() {
- return getHosts(this.ignore);
- }
-
- /**
- * Remove a host from the ignore list.
- * Used principally for testing.
- *
- * @param host String
- * @return True if removed, else false
- */
- public boolean removeFromIgnore(final String host) {
- return this.ignore.remove(host);
- }
-
- /**
- * Attempts to return at least one socket per valid network interface.
- * If no valid interface is found then the array will be empty.
- *
- * @param multicastAddress A valid multicast address
- * @param port A valid multicast port
- * @return MulticastSocket[], may be empty if no valid interfaces exist
- * @throws Exception On invalid parameters
- */
- public static MulticastSocket[] getSockets(final String multicastAddress, final int port) throws Exception {
-
- final InetAddress ia;
-
- try {
- ia = InetAddress.getByName(multicastAddress);
- } catch (final UnknownHostException e) {
- throw new ServiceException(multicastAddress + " is not a valid address", e);
- }
-
- if (null == ia || !ia.isMulticastAddress()) {
- throw new ServiceException(multicastAddress + " is not a valid multicast address");
- }
-
- return getSockets(ia, port);
- }
-
- private static MulticastSocket[] getSockets(final InetAddress ia, final int port) throws Exception {
-
- final ArrayList<MulticastSocket> list = new ArrayList<MulticastSocket>();
-
- for (final NetworkInterface ni : getInterfaces()) {
-
- MulticastSocket ms = null;
-
- try {
-
- ms = new MulticastSocket(port);
- ms.setNetworkInterface(ni);
- ms.setSoTimeout(0);
- ms.setTimeToLive(TTL);
- if (!ms.getBroadcast()) {
- ms.setBroadcast(true);
- }
- ms.joinGroup(ia);
-
- list.add(ms);
-
- log.debug(String.format("Created MulticastSocket for '%1$s:%2$s' on network adapter: %3$s", ia.getHostName(), port, ni));
-
- } catch (final Throwable e) {
-
- if (null != ms) {
- try {
- ms.close();
- } catch (final Throwable t) {
- //Ignore
- }
- }
- }
- }
-
- return list.toArray(new MulticastSocket[list.size()]);
- }
-
- private static NetworkInterface[] getNetworkInterfaces() {
-
- final HashSet<NetworkInterface> list = new HashSet<NetworkInterface>();
-
- try {
- final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
- while (interfaces.hasMoreElements()) {
- final NetworkInterface next = interfaces.nextElement();
-
- if (next.supportsMulticast() && next.isUp()) {
- list.add(next);
- }
- }
- } catch (final SocketException e) {
- //Ignore
- }
-
- return list.toArray(new NetworkInterface[list.size()]);
- }
-
- /**
- * Is the provided host a valid loopback address
- *
- * @param host Host to test
- * @return True or false
- */
- public static boolean isLoopback(final String host) {
-
- final InetAddress addr;
- try {
- addr = InetAddress.getByName(host);
- } catch (final UnknownHostException e) {
- return false;
- }
-
- return addr.isLoopbackAddress();
- }
-
- /**
- * Is the provided host a local host
- *
- * @param host The host to test
- * @param wildcardIsLocal Should 0.0.0.0 or [::] be deemed as local
- * @return True is the host is a local host else false
- */
- public static boolean isLocalAddress(final String host, final boolean wildcardIsLocal) {
-
- final InetAddress addr;
- try {
- addr = InetAddress.getByName(host);
- } catch (final UnknownHostException e) {
- return false;
- }
-
- // Check if the address is a valid special local or loop back
- if ((wildcardIsLocal && addr.isAnyLocalAddress()) || addr.isLoopbackAddress()) {
- return true;
- }
-
- // Check if the address is defined on any interface
- try {
- return NetworkInterface.getByInetAddress(addr) != null;
- } catch (final SocketException e) {
- return false;
- }
- }
-
- private static String getHosts(final Set<String> ignore) {
-
- final Set<String> hosts = new TreeSet<String>(new Comparator<String>() {
-
- @Override
- public int compare(final String h1, final String h2) {
-
- //Sort by hostname, IPv4, IPv6
-
- try {
- if (IPAddressUtil.isIPv4LiteralAddress(h1)) {
- if (IPAddressUtil.isIPv6LiteralAddress(h2.replace("[", "").replace("]", ""))) {
- return -1;
- }
- } else if (IPAddressUtil.isIPv6LiteralAddress(h1.replace("[", "").replace("]", ""))) {
- if (IPAddressUtil.isIPv4LiteralAddress(h2)) {
- return 1;
- }
- } else if (0 != h1.compareTo(h2)) {
- return -1;
- }
- } catch (final Throwable e) {
- //Ignore
- }
-
- return h1.compareTo(h2);
- }
- });
-
- try {
- final InetAddress localhost = InetAddress.getLocalHost();
- hosts.add(localhost.getHostAddress());
- //Multi-homed
- final InetAddress[] all = InetAddress.getAllByName(localhost.getHostName());
- for (final InetAddress ip : all) {
-
- if (ip.isLinkLocalAddress() || ip.isMulticastAddress()) {
- continue;
- }
-
- final String ha = ip.getHostAddress();
- if (!ha.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
- hosts.add(ha);
- hosts.add(ip.getHostName());
- }
- }
- } catch (final UnknownHostException e) {
- log.warning("Failed to list machine hosts", e);
- }
-
- final StringBuilder sb = new StringBuilder();
- for (final String host : hosts) {
- final String lc = host.toLowerCase();
- if (!ignore.contains(lc)) {
- if (sb.length() > 0) {
- sb.append(',');
- }
- sb.append(host);
- }
- }
-
- return sb.toString();
- }
-
- private static class Sender implements Runnable {
-
- private final AtomicInteger counter = new AtomicInteger(0);
- private final MulticastPulseAgent agent;
- private final String socketKey;
- private final MulticastSocket socket;
-
- private Sender(final MulticastPulseAgent agent, final String socketKey, final MulticastSocket socket) {
- this.agent = agent;
- this.socketKey = socketKey;
- this.socket = socket;
- }
-
- @Override
- public void run() {
- while (this.agent.running.get()) {
-
- synchronized (this.counter) {
- try {
- //Wait indefinitely until we are interrupted or notified
- this.counter.wait();
- } catch (final InterruptedException e) {
- if (!this.agent.running.get()) {
- break;
- }
- }
- }
-
- //Pulse a response every 10ms until our counter is 0 (at least 1 second)
- while (this.counter.decrementAndGet() > 0) {
-
- try {
- this.socket.send(this.agent.getResponsePacket());
- } catch (final Exception e) {
- if (log.isDebugEnabled()) {
- log.debug("MulticastPulseAgent client error: " + e.getMessage(), e);
- }
- }
-
- try {
- Thread.sleep(10);
- } catch (final InterruptedException e) {
- break;
- }
- }
- }
- }
-
- /**
- * Renew the counter and notify to pulse response
- */
- private void pulseResponse() {
-
- synchronized (this.counter) {
-
- this.counter.set(100);
- this.counter.notifyAll();
- }
- }
-
- @Override
- public String toString() {
- return this.socketKey;
- }
- }
-}
+package org.apache.openejb.server.discovery;
+
+import org.apache.openejb.loader.Options;
+import org.apache.openejb.server.DiscoveryAgent;
+import org.apache.openejb.server.DiscoveryListener;
+import org.apache.openejb.server.SelfManaging;
+import org.apache.openejb.server.ServerService;
+import org.apache.openejb.server.ServiceException;
+import org.apache.openejb.util.DaemonThreadFactory;
+import org.apache.openejb.util.LogCategory;
+import org.apache.openejb.util.Logger;
+import org.apache.openejb.util.OptionsLog;
+import sun.net.util.IPAddressUtil;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.DatagramPacket;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MulticastSocket;
+import java.net.NetworkInterface;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * 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.
+ */
+public class MulticastPulseAgent implements DiscoveryAgent, ServerService, SelfManaging {
+
+ private static final Logger log = Logger.getInstance(LogCategory.OPENEJB_SERVER.createChild("discovery").createChild("multipulse"), MulticastPulseAgent.class);
+ private static NetworkInterface[] interfaces = null;
+ private static ExecutorService executor = null;
+ private static final Charset UTF8 = Charset.forName("UTF-8");
+ private static final int TTL = Integer.parseInt(System.getProperty("org.apache.openejb.multipulse.ttl", "32"));
+
+ public static final String SERVER = "OpenEJB.MCP.Server:";
+ public static final String CLIENT = "OpenEJB.MCP.Client:";
+ public static final String BADURI = ":BadUri:";
+ public static final String EMPTY = "NoService";
+
+ private final ReentrantLock lock = new ReentrantLock();
+ private final Set<String> ignore = Collections.synchronizedSet(new HashSet<String>());
+ private final Set<URI> uriSet = new HashSet<URI>();
+ private final AtomicBoolean running = new AtomicBoolean(false);
+ final ArrayList<Future> futures = new ArrayList<Future>();
+ private MulticastSocket[] sockets = null;
+ private InetSocketAddress address = null;
+
+ private String multicast = "239.255.3.2";
+ private String group = "default";
+ private int port = 6142;
+ private DatagramPacket response = null;
+ private DiscoveryListener listener = null;
+ private boolean loopbackOnly = true;
+
+ /**
+ * This agent listens for client pulses on a defined multicast channel.
+ * On receipt of a valid pulse the agent responds with its own pulse for
+ * a defined amount of time and rate. A client can deliver a pulse as often as
+ * required until it is happy of the server response.
+ * <p/>
+ * Both server and client deliver crafted information payloads.
+ * <p/>
+ * The client pulse contains OpenEJB.MCP.Client:(group or *)[:BadUri:URI]
+ * The server will only respond to a request for it's own group or *
+ * The optional :BadUri: is used by clients to notify a server that it is sending out unreachable URI's
+ * <p/>
+ * The server response pulse contains OpenEJB.MCP.Server:(Service|Service)|(Comma separated host list)
+ */
+ public MulticastPulseAgent() {
+ }
+
+ private static synchronized NetworkInterface[] getInterfaces() {
+ if (null == interfaces) {
+ interfaces = getNetworkInterfaces();
+ }
+
+ return interfaces;
+ }
+
+ private static synchronized ExecutorService getExecutorService() {
+
+ if (null == executor) {
+
+ int length = getInterfaces().length;
+ if (length < 1) {
+ length = 1;
+ }
+
+ executor = Executors.newFixedThreadPool(length * 3, new DaemonThreadFactory("multicast-pulse-agent-"));
+ }
+
+ return executor;
+ }
+
+ @Override
+ public void init(final Properties p) throws Exception {
+ final Options o = new Options(p);
+ o.setLogger(new OptionsLog(log));
+
+ this.ignore.add("localhost");
+ this.ignore.add("::1");
+ this.ignore.add("127.0.0.1");
+
+ try {
+ final String[] ignoreList = o.get("ignore", "").split(",");
+ for (final String s : ignoreList) {
+ if (null != s && s.trim().length() > 0) {
+ this.ignore.add(s.trim().toLowerCase());
+ }
+ }
+ } catch (final Exception e) {
+ log.warning("Invalid ignore parameter. Should be a lowercase single host or comma seperated list of hosts to ignore like: ignore=host1,host2,ipv4,ipv6");
+ }
+
+ this.multicast = o.get("bind", this.multicast);
+ this.port = o.get("port", this.port);
+ this.group = o.get("group", this.group);
+
+ final InetAddress ia = InetAddress.getByName(this.multicast);
+ this.address = new InetSocketAddress(ia, this.port);
+ this.buildPacket();
+ }
+
+ private void buildPacket() throws SocketException {
+
+ final ReentrantLock l = this.lock;
+ l.lock();
+
+ try {
+ this.loopbackOnly = true;
+ for (final URI uri : this.uriSet) {
+ if (!isLoopback(uri.getHost())) {
+ this.loopbackOnly = false;
+ break;
+ }
+ }
+
+ final String hosts = getHosts(this.ignore);
+ final StringBuilder sb = new StringBuilder(SERVER);
+ sb.append(this.group);
+ sb.append(':');
+
+ if (this.uriSet.size() > 0) {
+ for (final URI uri : this.uriSet) {
+ sb.append(uri.toASCIIString());
+ sb.append('|');
+ }
+ } else {
+ sb.append(EMPTY);
+ sb.append('|');
+ }
+
+ sb.append(hosts);
+
+ final byte[] bytes = (sb.toString()).getBytes(UTF8);
+ this.response = new DatagramPacket(bytes, bytes.length, this.address);
+
+ if (log.isDebugEnabled()) {
+ log.debug("MultiPulse packet is: " + sb);
+ }
+
+ if (bytes.length > 2048) {
+ log.warning("MultiPulse packet is larger than 2048 bytes, clients will not be able to read the packet" +
+ "\n - You should define the 'ignore' property to filter out unreachable addresses: " + sb);
+ }
+ } finally {
+ l.unlock();
+ }
+ }
+
+ public DatagramPacket getResponsePacket() {
+ final ReentrantLock l = this.lock;
+ l.lock();
+
+ try {
+ return this.response;
+ } finally {
+ l.unlock();
+ }
+ }
+
+ @Override
+ public void setDiscoveryListener(final DiscoveryListener listener) {
+ this.listener = listener;
+ }
+
+ public DiscoveryListener getDiscoveryListener() {
+ return listener;
+ }
+
+ @Override
+ public void registerService(URI uri) throws IOException {
+
+ uri = parseUri(uri);
+
+ if (this.uriSet.add(uri)) {
+ this.buildPacket();
+ this.fireEvent(uri, true);
+ }
+ }
+
+ @Override
+ public void unregisterService(final URI uri) throws IOException {
+
+ final URI tmp = parseUri(uri);
+
+ if (this.uriSet.remove(tmp)) {
+ this.fireEvent(uri, false);
+ }
+ }
+
+ @Override
+ public void reportFailed(final URI serviceUri) throws IOException {
+ this.unregisterService(serviceUri);
+ }
+
+ /**
+ * Strip the scheme
+ *
+ * @param uri URI to strip the scheme
+ * @return Stripped URI
+ */
+ private URI parseUri(final URI uri) {
+ return URI.create(uri.getSchemeSpecificPart());
+ }
+
+ private void fireEvent(final URI uri, final boolean add) {
+ if (null != this.listener) {
+ final DiscoveryListener dl = this.listener;
+ getExecutorService().execute(new Runnable() {
+ @Override
+ public void run() {
+ if (add) {
+ dl.serviceAdded(uri);
+ } else {
+ dl.serviceRemoved(uri);
+ }
+ }
+ });
+ }
+ }
+
+ @Override
+ public void start() throws ServiceException {
+ if (!this.running.getAndSet(true)) {
+
+ try {
+ this.sockets = getSockets(this.multicast, this.port);
+ } catch (final Exception e) {
+ throw new ServiceException("Failed to get Multicast sockets", e);
+ }
+
+ final CountDownLatch latch = new CountDownLatch(this.sockets.length);
+ final String mpg = this.group;
+ final boolean isLoopBackOnly = this.loopbackOnly;
+ final ExecutorService executorService = getExecutorService();
+ final MulticastPulseAgent agent = MulticastPulseAgent.this;
+
+ for (final MulticastSocket socket : this.sockets) {
+
+ final String socketKey;
+ try {
+ socketKey = socket.getNetworkInterface().toString();
+ } catch (final SocketException e) {
+ log.error("Failed to get network interface name on: " + socket, e);
+ continue;
+ }
+
+ final Sender sender = new Sender(this, socketKey, socket);
+ this.futures.add(executorService.submit(sender));
+
+ this.futures.add(executorService.submit(new Runnable() {
+ @Override
+ public void run() {
+
+ final DatagramPacket request = new DatagramPacket(new byte[2048], 2048);
+ latch.countDown();
+
+ while (agent.running.get()) {
+
+ try {
+ socket.receive(request);
+ final SocketAddress sa = request.getSocketAddress();
+
+ if (null != sa) {
+
+ String req = new String(request.getData(), 0, request.getLength());
+
+ if (req.startsWith(CLIENT)) {
+
+ final int ix = req.indexOf(BADURI);
+ String badUri = null;
+
+ if (ix > 0) {
+ //The client is notifying of a bad uri
+ badUri = req.substring(ix).replace(BADURI, "");
+ req = req.substring(0, ix).replace(CLIENT, "");
+ } else {
+ req = (req.replace(CLIENT, ""));
+ }
+
+ //Is this a group or global pulse request
+ if (mpg.equals(req) || "*".equals(req)) {
+
+ //Is there a bad url and is it this agent broadcasting the bad URI?
+ if (null != badUri) {
+ if (getHosts(agent.ignore).contains(badUri)) {
+ final ReentrantLock l = agent.lock;
+ l.lock();
+
+ try {
+ //Remove it and rebuild our broadcast packet
+ if (agent.ignore.add(badUri)) {
+ agent.buildPacket();
+ log.warning("This server has removed the unreachable host '" + badUri + "' from discovery, you should consider adding" +
+ " this to the 'ignore' property in the multipulse.properties file");
+ }
+ } finally {
+ l.unlock();
+ }
+ }
+
+ agent.fireEvent(URI.create("OpenEJB" + BADURI + badUri), false);
+
+ } else {
+
+ //Normal client multicast pulse request
+ final String client = ((InetSocketAddress) sa).getAddress().getHostAddress();
+
+ if (isLoopBackOnly && !MulticastPulseAgent.isLocalAddress(client, false)) {
+ //We only have local services, so make sure the request is from a local source else ignore it
+ if (log.isDebugEnabled()) {
+ log.debug(String.format("Ignoring remote client %1$s pulse request for group: %2$s - No remote services available",
+ client,
+ req));
+ }
+ } else {
+
+ //We have received a valid pulse request
+ if (log.isDebugEnabled()) {
+ log.debug(String.format("Answering client '%1$s' pulse request for group: '%2$s' on '%3$s'", client, req, socketKey));
+ }
+
+ //Renew response pulse
+ sender.pulseResponse();
+ }
+ }
+ }
+ }
+ }
+
+ } catch (final Exception e) {
+ if (log.isDebugEnabled()) {
+ log.debug("MulticastPulseAgent request error: " + e.getMessage(), e);
+ }
+ }
+ }
+
+ try {
+ socket.close();
+ } catch (final Throwable e) {
+ //Ignore
+ }
+ }
+ }));
+ }
+
+ try {
+ //Give threads a reasonable amount of time to start
+ latch.await(5, TimeUnit.SECONDS);
+ } catch (final InterruptedException e) {
+ this.stop();
+ }
+ }
+ }
+
+ @Override
+ public void stop() throws ServiceException {
+ if (this.running.getAndSet(false)) {
+
+ try {
+ //Iterrupt threads
+ for (final Future future : this.futures) {
+ try {
+ future.cancel(true);
+ } catch (final Throwable e) {
+ //Ignore
+ }
+ }
+
+ //Wait for threads to complete
+ for (final Future future : this.futures) {
+ try {
+ future.get();
+ } catch (final Throwable e) {
+ //Ignore
+ }
+ }
+ } finally {
+ this.futures.clear();
+ }
+
+ if (null != this.sockets) {
+ try {
+ for (final MulticastSocket s : this.sockets) {
+ try {
+ s.close();
+ } catch (final Throwable e) {
+ //Ignore
+ }
+ }
+ } finally {
+ this.sockets = null;
+ }
+ }
+ }
+ }
+
+ @Override
+ public void service(final InputStream in, final OutputStream out) throws ServiceException, IOException {
+ //Ignore
+ }
+
+ @Override
+ public void service(final Socket socket) throws ServiceException, IOException {
+ //Ignore
+ }
+
+ @Override
+ public String getName() {
+ return "multipulse";
+ }
+
+ @Override
+ public String getIP() {
+ return this.multicast;
+ }
+
+ @Override
+ public int getPort() {
+ return this.port;
+ }
+
+ /**
+ * Lists current broadcast hosts as a comma separated list.
+ * Used principally for testing.
+ *
+ * @return String
+ */
+ public String getHosts() {
+ return getHosts(this.ignore);
+ }
+
+ /**
+ * Remove a host from the ignore list.
+ * Used principally for testing.
+ *
+ * @param host String
+ * @return True if removed, else false
+ */
+ public boolean removeFromIgnore(final String host) {
+ return this.ignore.remove(host);
+ }
+
+ /**
+ * Attempts to return at least one socket per valid network interface.
+ * If no valid interface is found then the array will be empty.
+ *
+ * @param multicastAddress A valid multicast address
+ * @param port A valid multicast port
+ * @return MulticastSocket[], may be empty if no valid interfaces exist
+ * @throws Exception On invalid parameters
+ */
+ public static MulticastSocket[] getSockets(final String multicastAddress, final int port) throws Exception {
+
+ final InetAddress ia;
+
+ try {
+ ia = InetAddress.getByName(multicastAddress);
+ } catch (final UnknownHostException e) {
+ throw new ServiceException(multicastAddress + " is not a valid address", e);
+ }
+
+ if (null == ia || !ia.isMulticastAddress()) {
+ throw new ServiceException(multicastAddress + " is not a valid multicast address");
+ }
+
+ return getSockets(ia, port);
+ }
+
+ private static MulticastSocket[] getSockets(final InetAddress ia, final int port) throws Exception {
+
+ final ArrayList<MulticastSocket> list = new ArrayList<MulticastSocket>();
+
+ for (final NetworkInterface ni : getInterfaces()) {
+
+ MulticastSocket ms = null;
+
+ try {
+
+ ms = new MulticastSocket(port);
+ ms.setNetworkInterface(ni);
+ ms.setSoTimeout(0);
+ ms.setTimeToLive(TTL);
+ if (!ms.getBroadcast()) {
+ ms.setBroadcast(true);
+ }
+ ms.joinGroup(ia);
+
+ list.add(ms);
+
+ log.debug(String.format("Created MulticastSocket for '%1$s:%2$s' on network adapter: %3$s", ia.getHostName(), port, ni));
+
+ } catch (final Throwable e) {
+
+ if (null != ms) {
+ try {
+ ms.close();
+ } catch (final Throwable t) {
+ //Ignore
+ }
+ }
+ }
+ }
+
+ return list.toArray(new MulticastSocket[list.size()]);
+ }
+
+ private static NetworkInterface[] getNetworkInterfaces() {
+
+ final HashSet<NetworkInterface> list = new HashSet<NetworkInterface>();
+
+ try {
+ final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
+ while (interfaces.hasMoreElements()) {
+ final NetworkInterface next = interfaces.nextElement();
+
+ if (next.supportsMulticast() && next.isUp()) {
+ list.add(next);
+ }
+ }
+ } catch (final SocketException e) {
+ //Ignore
+ }
+
+ return list.toArray(new NetworkInterface[list.size()]);
+ }
+
+ /**
+ * Is the provided host a valid loopback address
+ *
+ * @param host Host to test
+ * @return True or false
+ */
+ public static boolean isLoopback(final String host) {
+
+ final InetAddress addr;
+ try {
+ addr = InetAddress.getByName(host);
+ } catch (final UnknownHostException e) {
+ return false;
+ }
+
+ return addr.isLoopbackAddress();
+ }
+
+ /**
+ * Is the provided host a local host
+ *
+ * @param host The host to test
+ * @param wildcardIsLocal Should 0.0.0.0 or [::] be deemed as local
+ * @return True is the host is a local host else false
+ */
+ public static boolean isLocalAddress(final String host, final boolean wildcardIsLocal) {
+
+ final InetAddress addr;
+ try {
+ addr = InetAddress.getByName(host);
+ } catch (final UnknownHostException e) {
+ return false;
+ }
+
+ // Check if the address is a valid special local or loop back
+ if ((wildcardIsLocal && addr.isAnyLocalAddress()) || addr.isLoopbackAddress()) {
+ return true;
+ }
+
+ // Check if the address is defined on any interface
+ try {
+ return NetworkInterface.getByInetAddress(addr) != null;
+ } catch (final SocketException e) {
+ return false;
+ }
+ }
+
+ private static String getHosts(final Set<String> ignore) {
+
+ final Set<String> hosts = new TreeSet<String>(new Comparator<String>() {
+
+ @Override
+ public int compare(final String h1, final String h2) {
+
+ //Sort by hostname, IPv4, IPv6
+
+ try {
+ if (IPAddressUtil.isIPv4LiteralAddress(h1)) {
+ if (IPAddressUtil.isIPv6LiteralAddress(h2.replace("[", "").replace("]", ""))) {
+ return -1;
+ }
+ } else if (IPAddressUtil.isIPv6LiteralAddress(h1.replace("[", "").replace("]", ""))) {
+ if (IPAddressUtil.isIPv4LiteralAddress(h2)) {
+ return 1;
+ }
+ } else if (0 != h1.compareTo(h2)) {
+ return -1;
+ }
+ } catch (final Throwable e) {
+ //Ignore
+ }
+
+ return h1.compareTo(h2);
+ }
+ });
+
+ try {
+ final InetAddress localhost = InetAddress.getLocalHost();
+ hosts.add(localhost.getHostAddress());
+ //Multi-homed
+ final InetAddress[] all = InetAddress.getAllByName(localhost.getHostName());
+ for (final InetAddress ip : all) {
+
+ if (ip.isLinkLocalAddress() || ip.isMulticastAddress()) {
+ continue;
+ }
+
+ final String ha = ip.getHostAddress();
+ if (!ha.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
+ hosts.add(ha);
+ hosts.add(ip.getHostName());
+ }
+ }
+ } catch (final UnknownHostException e) {
+ log.warning("Failed to list machine hosts", e);
+ }
+
+ final StringBuilder sb = new StringBuilder();
+ for (final String host : hosts) {
+ final String lc = host.toLowerCase();
+ if (!ignore.contains(lc)) {
+ if (sb.length() > 0) {
+ sb.append(',');
+ }
+ sb.append(host);
+ }
+ }
+
+ return sb.toString();
+ }
+
+ private static class Sender implements Runnable {
+
+ private final AtomicInteger counter = new AtomicInteger(0);
+ private final MulticastPulseAgent agent;
+ private final String socketKey;
+ private final MulticastSocket socket;
+
+ private Sender(final MulticastPulseAgent agent, final String socketKey, final MulticastSocket socket) {
+ this.agent = agent;
+ this.socketKey = socketKey;
+ this.socket = socket;
+ }
+
+ @Override
+ public void run() {
+ while (this.agent.running.get()) {
+
+ synchronized (this.counter) {
+ try {
+ //Wait indefinitely until we are interrupted or notified
+ this.counter.wait();
+ } catch (final InterruptedException e) {
+ if (!this.agent.running.get()) {
+ break;
+ }
+ }
+ }
+
+ //Pulse a response every 10ms until our counter is 0 (at least 1 second)
+ while (this.counter.decrementAndGet() > 0) {
+
+ try {
+ this.socket.send(this.agent.getResponsePacket());
+ } catch (final Exception e) {
+ if (log.isDebugEnabled()) {
+ log.debug("MulticastPulseAgent client error: " + e.getMessage(), e);
+ }
+ }
+
+ try {
+ Thread.sleep(10);
+ } catch (final InterruptedException e) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Renew the counter and notify to pulse response
+ */
+ private void pulseResponse() {
+
+ synchronized (this.counter) {
+
+ this.counter.set(100);
+ this.counter.notifyAll();
+ }
+ }
+
+ @Override
+ public String toString() {
+ return this.socketKey;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/EJBRestServiceInfo.java
----------------------------------------------------------------------
diff --git a/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/EJBRestServiceInfo.java b/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/EJBRestServiceInfo.java
index b8cc1d3..1d68961 100644
--- a/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/EJBRestServiceInfo.java
+++ b/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/EJBRestServiceInfo.java
@@ -1,33 +1,33 @@
-/*
- * 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.openejb.server.rest;
-
-import org.apache.openejb.BeanContext;
-
-public class EJBRestServiceInfo {
- public String path;
- public BeanContext context;
-
- public EJBRestServiceInfo(final String path, final BeanContext context) {
- if (context == null) {
- throw new OpenEJBRestRuntimeException("can't find context");
- }
-
- this.path = path;
- this.context = context;
- }
-}
+/*
+ * 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.openejb.server.rest;
+
+import org.apache.openejb.BeanContext;
+
+public class EJBRestServiceInfo {
+ public String path;
+ public BeanContext context;
+
+ public EJBRestServiceInfo(final String path, final BeanContext context) {
+ if (context == null) {
+ throw new OpenEJBRestRuntimeException("can't find context");
+ }
+
+ this.path = path;
+ this.context = context;
+ }
+}
[11/12] tomee git commit: EOL
Posted by an...@apache.org.
EOL
Project: http://git-wip-us.apache.org/repos/asf/tomee/repo
Commit: http://git-wip-us.apache.org/repos/asf/tomee/commit/352bade2
Tree: http://git-wip-us.apache.org/repos/asf/tomee/tree/352bade2
Diff: http://git-wip-us.apache.org/repos/asf/tomee/diff/352bade2
Branch: refs/heads/tomee-1.7.3-prepare
Commit: 352bade204598819709f0d336d46a02b6f4e29c1
Parents: 267945e
Author: AndyGee <an...@gmx.de>
Authored: Tue Nov 24 18:15:41 2015 +0100
Committer: AndyGee <an...@gmx.de>
Committed: Tue Nov 24 18:15:41 2015 +0100
----------------------------------------------------------------------
.../openejb/maven/plugin/AbstractTomEEMojo.java | 2726 +++++++++---------
.../maven/plugin/test/TomEEMavenPluginTest.java | 138 +-
.../apache/openejb/client/ClientSecurity.java | 408 +--
.../client/DirectConnectionStrategy.java | 66 +-
.../openejb/client/MulticastPulseClient.java | 1556 +++++-----
.../apache/openejb/client/ProtocolMetaData.java | 224 +-
.../openejb/server/cxf/rs/AutoJAXRSInvoker.java | 140 +-
.../server/cxf/rs/CxfRsHttpListener.java | 2194 +++++++-------
.../server/cxf/rs/OpenEJBEJBInvoker.java | 230 +-
.../rs/DynamicSubclassEjbDeploymentTest.java | 260 +-
.../cxf/rs/EJBAccessExceptionMapperTest.java | 220 +-
.../server/cxf/rs/EjbDeploymentTest.java | 246 +-
.../cxf/rs/PathParamAtClassLevelTest.java | 148 +-
.../server/cxf/WSSPassThroughInterceptor.java | 132 +-
.../server/cxf/ejb/EjbMessageContext.java | 124 +-
.../server/cxf/CxfJaxWsProviderTest.java | 274 +-
.../cxf/fault/AuthenticatorServiceBean.java | 84 +-
.../AuthenticatorServiceBeanNoHandler.java | 82 +-
.../server/cxf/fault/DummyInterceptor.java | 96 +-
.../cxf/fault/WrongPasswordException.java | 82 +-
.../fault/WrongPasswordRuntimeException.java | 84 +-
.../org/apache/openejb/daemon/NTService.java | 228 +-
.../apache/openejb/server/ejbd/EjbServer.java | 288 +-
.../server/discovery/MulticastPulseAgent.java | 1520 +++++-----
.../openejb/server/rest/EJBRestServiceInfo.java | 66 +-
.../openejb/tck/impl/ContainersImplTomEE.java | 338 +--
.../openejb/tck/impl/FullRestartContainer.java | 274 +-
.../apache-tomee/src/main/resources/service.bat | 452 +--
tomee/apache-tomee/src/main/resources/tomee.bat | 170 +-
.../org/apache/tomee/catalina/Contexts.java | 296 +-
.../catalina/ProvisioningWebappLoader.java | 238 +-
.../org/apache/tomee/common/NamingUtil.java | 298 +-
.../java/org/apache/tomee/common/WsFactory.java | 268 +-
33 files changed, 6975 insertions(+), 6975 deletions(-)
----------------------------------------------------------------------
[03/12] tomee git commit: EOL
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/352bade2/tomee/tomee-common/src/main/java/org/apache/tomee/common/WsFactory.java
----------------------------------------------------------------------
diff --git a/tomee/tomee-common/src/main/java/org/apache/tomee/common/WsFactory.java b/tomee/tomee-common/src/main/java/org/apache/tomee/common/WsFactory.java
index 1de7a83..8546deb 100644
--- a/tomee/tomee-common/src/main/java/org/apache/tomee/common/WsFactory.java
+++ b/tomee/tomee-common/src/main/java/org/apache/tomee/common/WsFactory.java
@@ -1,134 +1,134 @@
-/**
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.tomee.common;
-
-import org.apache.naming.ResourceRef;
-import org.apache.openejb.Injection;
-import org.apache.openejb.core.ivm.naming.JaxWsServiceReference;
-import org.apache.openejb.core.webservices.HandlerChainData;
-import org.apache.openejb.core.webservices.PortRefData;
-
-import javax.naming.Context;
-import javax.naming.Name;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.xml.namespace.QName;
-import javax.xml.ws.Service;
-import java.net.URL;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Properties;
-
-public class WsFactory extends AbstractObjectFactory {
- public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
- // ignore non resource-refs
- if (!(object instanceof ResourceRef)) {
- return null;
- }
-
- final Reference ref = (Reference) object;
-
- final Object value;
- if (NamingUtil.getProperty(ref, NamingUtil.JNDI_NAME) != null) {
- // lookup the value in JNDI
- value = super.getObjectInstance(object, name, context, environment);
- } else {
- // load service class which is used to construct the port
- final String serviceClassName = NamingUtil.getProperty(ref, NamingUtil.WS_CLASS);
- Class<? extends Service> serviceClass = Service.class;
- if (serviceClassName != null) {
- final Class<?> loadClass = NamingUtil.loadClass(serviceClassName);
-
- if (loadClass == null) {
- throw new NamingException("Could not load service type class "+ serviceClassName);
- }
-
- serviceClass = loadClass.asSubclass(Service.class);
- }
-
- // load the reference class which is the ultimate type of the port
- final Class<?> referenceClass = NamingUtil.loadClass(ref.getClassName());
-
- // if ref class is a subclass of Service, use it for the service class
- if (referenceClass != null && Service.class.isAssignableFrom(referenceClass)) {
- serviceClass = referenceClass.asSubclass(Service.class);
- }
-
- // PORT ID
- final String serviceId = NamingUtil.getProperty(ref, NamingUtil.WS_ID);
-
- // Service QName
- QName serviceQName = null;
- String property = NamingUtil.getProperty(ref, NamingUtil.WS_QNAME);
- if (property != null) {
- serviceQName = QName.valueOf(property);
- }
-
- // WSDL URL
- URL wsdlUrl = null;
- property = NamingUtil.getProperty(ref, NamingUtil.WSDL_URL);
- if (property != null) {
- wsdlUrl = new URL(property);
- }
-
- // Port QName
- QName portQName = null;
- property = NamingUtil.getProperty(ref, NamingUtil.WS_PORT_QNAME);
- if (property != null) {
- portQName = QName.valueOf(property);
- }
-
- // port refs
- List<PortRefData> portRefs = NamingUtil.getStaticValue(ref, "port-refs");
- if (portRefs == null) {
- portRefs = Collections.emptyList();
- }
-
- // HandlerChain
- List<HandlerChainData> handlerChains = NamingUtil.getStaticValue(ref, "handler-chains");
- if (handlerChains == null) {
- handlerChains = Collections.emptyList();
- }
- Collection<Injection> injections = NamingUtil.getStaticValue(ref, "injections");
- if (injections == null) {
- injections = Collections.emptyList();
- }
-
- final Properties properties = new Properties();
- properties.putAll(environment);
- final JaxWsServiceReference serviceReference = new JaxWsServiceReference(serviceId,
- serviceQName,
- serviceClass, portQName,
- referenceClass,
- wsdlUrl,
- portRefs,
- handlerChains,
- injections,
- properties);
- value = serviceReference.getObject();
- }
-
- return value;
- }
-
- protected String buildJndiName(final Reference reference) throws NamingException {
- throw new UnsupportedOperationException();
- }
-}
+/**
+ *
+ * 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.tomee.common;
+
+import org.apache.naming.ResourceRef;
+import org.apache.openejb.Injection;
+import org.apache.openejb.core.ivm.naming.JaxWsServiceReference;
+import org.apache.openejb.core.webservices.HandlerChainData;
+import org.apache.openejb.core.webservices.PortRefData;
+
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.NamingException;
+import javax.naming.Reference;
+import javax.xml.namespace.QName;
+import javax.xml.ws.Service;
+import java.net.URL;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Properties;
+
+public class WsFactory extends AbstractObjectFactory {
+ public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
+ // ignore non resource-refs
+ if (!(object instanceof ResourceRef)) {
+ return null;
+ }
+
+ final Reference ref = (Reference) object;
+
+ final Object value;
+ if (NamingUtil.getProperty(ref, NamingUtil.JNDI_NAME) != null) {
+ // lookup the value in JNDI
+ value = super.getObjectInstance(object, name, context, environment);
+ } else {
+ // load service class which is used to construct the port
+ final String serviceClassName = NamingUtil.getProperty(ref, NamingUtil.WS_CLASS);
+ Class<? extends Service> serviceClass = Service.class;
+ if (serviceClassName != null) {
+ final Class<?> loadClass = NamingUtil.loadClass(serviceClassName);
+
+ if (loadClass == null) {
+ throw new NamingException("Could not load service type class "+ serviceClassName);
+ }
+
+ serviceClass = loadClass.asSubclass(Service.class);
+ }
+
+ // load the reference class which is the ultimate type of the port
+ final Class<?> referenceClass = NamingUtil.loadClass(ref.getClassName());
+
+ // if ref class is a subclass of Service, use it for the service class
+ if (referenceClass != null && Service.class.isAssignableFrom(referenceClass)) {
+ serviceClass = referenceClass.asSubclass(Service.class);
+ }
+
+ // PORT ID
+ final String serviceId = NamingUtil.getProperty(ref, NamingUtil.WS_ID);
+
+ // Service QName
+ QName serviceQName = null;
+ String property = NamingUtil.getProperty(ref, NamingUtil.WS_QNAME);
+ if (property != null) {
+ serviceQName = QName.valueOf(property);
+ }
+
+ // WSDL URL
+ URL wsdlUrl = null;
+ property = NamingUtil.getProperty(ref, NamingUtil.WSDL_URL);
+ if (property != null) {
+ wsdlUrl = new URL(property);
+ }
+
+ // Port QName
+ QName portQName = null;
+ property = NamingUtil.getProperty(ref, NamingUtil.WS_PORT_QNAME);
+ if (property != null) {
+ portQName = QName.valueOf(property);
+ }
+
+ // port refs
+ List<PortRefData> portRefs = NamingUtil.getStaticValue(ref, "port-refs");
+ if (portRefs == null) {
+ portRefs = Collections.emptyList();
+ }
+
+ // HandlerChain
+ List<HandlerChainData> handlerChains = NamingUtil.getStaticValue(ref, "handler-chains");
+ if (handlerChains == null) {
+ handlerChains = Collections.emptyList();
+ }
+ Collection<Injection> injections = NamingUtil.getStaticValue(ref, "injections");
+ if (injections == null) {
+ injections = Collections.emptyList();
+ }
+
+ final Properties properties = new Properties();
+ properties.putAll(environment);
+ final JaxWsServiceReference serviceReference = new JaxWsServiceReference(serviceId,
+ serviceQName,
+ serviceClass, portQName,
+ referenceClass,
+ wsdlUrl,
+ portRefs,
+ handlerChains,
+ injections,
+ properties);
+ value = serviceReference.getObject();
+ }
+
+ return value;
+ }
+
+ protected String buildJndiName(final Reference reference) throws NamingException {
+ throw new UnsupportedOperationException();
+ }
+}