You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by jg...@apache.org on 2015/07/14 02:25:28 UTC

[1/6] tomee git commit: Re-use the connection for the datasource and transaction rather than fetch another one only to throw it away later. Slightly experimental change to prevent the db pool locking up.

Repository: tomee
Updated Branches:
  refs/heads/tomee-1.7.x fbb34e385 -> bd7dbd0f3


http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/tomee/apache-tomee/src/main/resources/service.install.as.admin.bat
----------------------------------------------------------------------
diff --git a/tomee/apache-tomee/src/main/resources/service.install.as.admin.bat b/tomee/apache-tomee/src/main/resources/service.install.as.admin.bat
index 8569a4d..dcfbe6b 100644
--- a/tomee/apache-tomee/src/main/resources/service.install.as.admin.bat
+++ b/tomee/apache-tomee/src/main/resources/service.install.as.admin.bat
@@ -1,33 +1,33 @@
-@echo off
-cls
-REM================================================
-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 _______________________________________________
-REM $Rev$
-REM================================================
-
-@if not "%ECHO%" == ""  echo %ECHO%
-@if "%OS%" == "Windows_NT" setlocal
-
-if "%OS%" == "Windows_NT" (
-  set "DIRNAME=%~dp0%"
-) else (
-  set DIRNAME=.\
-)
-
-pushd %DIRNAME%
-
+@echo off
+cls
+REM================================================
+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 _______________________________________________
+REM $Rev$
+REM================================================
+
+@if not "%ECHO%" == ""  echo %ECHO%
+@if "%OS%" == "Windows_NT" setlocal
+
+if "%OS%" == "Windows_NT" (
+  set "DIRNAME=%~dp0%"
+) else (
+  set DIRNAME=.\
+)
+
+pushd %DIRNAME%
+
 service install
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/tomee/apache-tomee/src/main/resources/service.remove.as.admin.bat
----------------------------------------------------------------------
diff --git a/tomee/apache-tomee/src/main/resources/service.remove.as.admin.bat b/tomee/apache-tomee/src/main/resources/service.remove.as.admin.bat
index 3b5d4ac..bc5fe0a 100644
--- a/tomee/apache-tomee/src/main/resources/service.remove.as.admin.bat
+++ b/tomee/apache-tomee/src/main/resources/service.remove.as.admin.bat
@@ -1,33 +1,33 @@
-@echo off
-cls
-REM================================================
-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 _______________________________________________
-REM $Rev$
-REM================================================
-
-@if not "%ECHO%" == ""  echo %ECHO%
-@if "%OS%" == "Windows_NT" setlocal
-
-if "%OS%" == "Windows_NT" (
-  set "DIRNAME=%~dp0%"
-) else (
-  set DIRNAME=.\
-)
-
-pushd %DIRNAME%
-
+@echo off
+cls
+REM================================================
+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 _______________________________________________
+REM $Rev$
+REM================================================
+
+@if not "%ECHO%" == ""  echo %ECHO%
+@if "%OS%" == "Windows_NT" setlocal
+
+if "%OS%" == "Windows_NT" (
+  set "DIRNAME=%~dp0%"
+) else (
+  set DIRNAME=.\
+)
+
+pushd %DIRNAME%
+
 service remove
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/TomcatDeploymentLoader.java
----------------------------------------------------------------------
diff --git a/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/TomcatDeploymentLoader.java b/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/TomcatDeploymentLoader.java
index 03fea68..4496e54 100644
--- a/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/TomcatDeploymentLoader.java
+++ b/tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/TomcatDeploymentLoader.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.tomee.catalina;
-
-import org.apache.catalina.core.StandardContext;
-import org.apache.openejb.config.DeploymentLoader;
-
-/**
- * @version $Id$
- */
-public class TomcatDeploymentLoader extends DeploymentLoader {
-    private StandardContext standardContext;
-    private String moduleId;
-
-    public TomcatDeploymentLoader(final StandardContext standardContext, final String moduleId) {
-        this.standardContext = standardContext;
-        this.moduleId = moduleId;
-    }
-
-    @Override
-    protected String getContextRoot() {
-        return standardContext.getPath();
-    }
-
-    @Override
-    protected String getModuleName() {
-        return moduleId;
-    }
-}
+/*
+ * 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.core.StandardContext;
+import org.apache.openejb.config.DeploymentLoader;
+
+/**
+ * @version $Id$
+ */
+public class TomcatDeploymentLoader extends DeploymentLoader {
+    private StandardContext standardContext;
+    private String moduleId;
+
+    public TomcatDeploymentLoader(final StandardContext standardContext, final String moduleId) {
+        this.standardContext = standardContext;
+        this.moduleId = moduleId;
+    }
+
+    @Override
+    protected String getContextRoot() {
+        return standardContext.getPath();
+    }
+
+    @Override
+    protected String getModuleName() {
+        return moduleId;
+    }
+}


[6/6] tomee git commit: Re-use the connection for the datasource and transaction rather than fetch another one only to throw it away later. Slightly experimental change to prevent the db pool locking up.

Posted by jg...@apache.org.
Re-use the connection for the datasource and transaction rather than fetch another one only to throw it away later. Slightly experimental change to prevent the db pool locking up.


Project: http://git-wip-us.apache.org/repos/asf/tomee/repo
Commit: http://git-wip-us.apache.org/repos/asf/tomee/commit/bd7dbd0f
Tree: http://git-wip-us.apache.org/repos/asf/tomee/tree/bd7dbd0f
Diff: http://git-wip-us.apache.org/repos/asf/tomee/diff/bd7dbd0f

Branch: refs/heads/tomee-1.7.x
Commit: bd7dbd0f31964df0c3ea421bc2f4aba2f51f8a2e
Parents: fbb34e3
Author: Jonathan Gallimore <jo...@jrg.me.uk>
Authored: Tue Jul 14 01:24:18 2015 +0100
Committer: Jonathan Gallimore <jo...@jrg.me.uk>
Committed: Tue Jul 14 01:24:18 2015 +0100

----------------------------------------------------------------------
 .../jdbc/managed/local/ManagedConnection.java   |   16 +-
 .../jdbc/managed/local/ManagedDataSource.java   |   28 +-
 .../resource/jdbc/ManagedDataSourceTest.java    |    4 +-
 .../MultiThreadedManagedDataSourceTest.java     |    4 +-
 .../resource/jdbc/UTManagedDataSourceTest.java  |    4 +-
 .../maven/plugin/AbstractSynchronizable.java    |  142 +-
 .../test/resources/schema/ComplexAllElement.xsd |   42 +-
 .../test/resources/schema/ComplexAllType.xsd    |   42 +-
 .../resources/schema/ComplexSequenceElement.xsd |   42 +-
 .../resources/schema/ComplexSequenceType.xsd    |   42 +-
 .../test/resources/schema/JaxRpcSpecExample.xsd |   42 +-
 .../src/test/resources/schema/SimpleElement.xsd |   42 +-
 .../src/test/resources/schema/SimpleType.xsd    |   42 +-
 .../resources/schema/SoapArrayByAttribute.xsd   |   42 +-
 .../resources/schema/SoapArrayByRestriction.xsd |   42 +-
 .../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/OpenEJBEJBInvoker.java        |  230 +--
 .../openejb/server/cxf/rs/PojoInvoker.java      |  124 +-
 .../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 +--
 .../server/cxf/fault/AuthenticatorService.java  |   60 +-
 .../cxf/fault/AuthenticatorServiceBean.java     |   84 +-
 .../AuthenticatorServiceBeanNoHandler.java      |   82 +-
 .../server/cxf/fault/DummyInterceptor.java      |   96 +-
 .../cxf/fault/WrongPasswordException.java       |   82 +-
 .../fault/WrongPasswordRuntimeException.java    |   84 +-
 .../src/test/resources/META-INF/ejb-jar.xml     |   36 +-
 .../apache/openejb/server/cxf/fault/handler.xml |   52 +-
 .../org/apache/openejb/daemon/NTService.java    |  228 +--
 .../openejb/server/ejbd/RequestHandler.java     |   90 +-
 .../server/discovery/MulticastPulseAgent.java   | 1520 ++++++++---------
 .../multipulse                                  |    6 +-
 .../discovery/MulticastPulseAgentTest.java      | 1026 ++++++------
 .../openejb/server/rest/EJBRestServiceInfo.java |   66 +-
 .../server/rest/InternalApplication.java        |   90 +-
 .../main/resources/META-INF/openejb-server.xml  |   72 +-
 .../META-INF/org.apache.openejb.cli/stop.help   |   28 +-
 src/main/style/checkstyle.xml                   |  330 ++--
 .../apache/openejb/tck/util/ServerLocal.java    |  100 +-
 .../apache-tomee/src/main/resources/service.bat |  452 ++---
 .../main/resources/service.install.as.admin.bat |   64 +-
 .../main/resources/service.remove.as.admin.bat  |   64 +-
 tomee/apache-tomee/src/main/resources/tomee.bat |  170 +-
 .../org/apache/tomee/catalina/Contexts.java     |  296 ++--
 .../catalina/ProvisioningWebappLoader.java      |  238 +--
 .../tomee/catalina/TomcatDeploymentLoader.java  |   86 +-
 55 files changed, 5122 insertions(+), 5108 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedConnection.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedConnection.java b/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedConnection.java
index 25e1727..5a8c4c7 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedConnection.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedConnection.java
@@ -35,13 +35,10 @@ import java.lang.reflect.Method;
 import java.sql.Connection;
 import java.sql.SQLException;
 import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
 
 public class ManagedConnection implements InvocationHandler {
     private static final Logger LOGGER = Logger.getInstance(LogCategory.OPENEJB_RESOURCE_JDBC, ManagedConnection.class);
 
-    private static final Map<Integer, Map<Transaction, Connection>> CONNECTION_BY_TX_BY_DS = new ConcurrentHashMap<Integer, Map<Transaction, Connection>>();
-
     private final TransactionManager transactionManager;
     private final LocalXAResource xaResource;
     protected Connection delegate;
@@ -55,7 +52,7 @@ public class ManagedConnection implements InvocationHandler {
         transactionManager = txMgr;
         closed = false;
         xaResource = new LocalXAResource(delegate);
-        connectionByTx = CONNECTION_BY_TX_BY_DS.get(ds.hashCode());
+        connectionByTx = ManagedConnectionsByTransactionByDatasource.get(ds);
     }
 
     public XAResource getXAResource() throws SQLException {
@@ -195,17 +192,6 @@ public class ManagedConnection implements InvocationHandler {
         }
     }
 
-    public static void pushDataSource(final CommonDataSource ds) {
-        CONNECTION_BY_TX_BY_DS.put(ds.hashCode(), new ConcurrentHashMap<Transaction, Connection>());
-    }
-
-    public static void cleanDataSource(final CommonDataSource ds) {
-        final Map<Transaction, Connection> map = CONNECTION_BY_TX_BY_DS.remove(ds.hashCode());
-        if (map != null) {
-            map.clear();
-        }
-    }
-
     private static class ClosingSynchronization implements Synchronization {
         private final Connection connection;
         private final Map<Transaction, Connection> mapToCleanup;

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedDataSource.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedDataSource.java b/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedDataSource.java
index 0c074f9..f57b9d8 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedDataSource.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/managed/local/ManagedDataSource.java
@@ -21,7 +21,10 @@ import org.apache.openejb.util.reflection.Reflections;
 
 import javax.sql.CommonDataSource;
 import javax.sql.DataSource;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
 import javax.transaction.TransactionManager;
+
 import java.io.PrintWriter;
 import java.lang.reflect.Proxy;
 import java.sql.Connection;
@@ -40,7 +43,7 @@ public class ManagedDataSource implements DataSource {
         delegate = ds;
         hashCode = hc;
         transactionManager = txMgr;
-        ManagedConnection.pushDataSource(this);
+        ManagedConnectionsByTransactionByDatasource.pushDataSource(this);
     }
 
     public ManagedDataSource(final DataSource ds, final TransactionManager txMgr) {
@@ -49,7 +52,26 @@ public class ManagedDataSource implements DataSource {
 
     @Override
     public Connection getConnection() throws SQLException {
-        return managed(delegate.getConnection());
+        
+        Transaction transaction = null;
+        
+        try {
+            transaction = transactionManager.getTransaction();
+        } catch (final SystemException e) {
+            // ignore
+        }
+        
+        Connection connection = null;
+        
+        if (transaction != null) {
+            connection = ManagedConnectionsByTransactionByDatasource.get(this, transaction);
+        }
+        
+        if (connection == null) {
+            connection = delegate.getConnection();
+        }
+        
+        return managed(connection);
     }
 
     @Override
@@ -101,7 +123,7 @@ public class ManagedDataSource implements DataSource {
     }
 
     public void clean() {
-        ManagedConnection.cleanDataSource(this);
+        ManagedConnectionsByTransactionByDatasource.cleanDataSource(this);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/ManagedDataSourceTest.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/ManagedDataSourceTest.java b/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/ManagedDataSourceTest.java
index e959693..6279f6c 100644
--- a/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/ManagedDataSourceTest.java
+++ b/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/ManagedDataSourceTest.java
@@ -20,6 +20,7 @@ import org.apache.openejb.jee.EjbJar;
 import org.apache.openejb.jee.SingletonBean;
 import org.apache.openejb.junit.ApplicationComposer;
 import org.apache.openejb.resource.jdbc.managed.local.ManagedConnection;
+import org.apache.openejb.resource.jdbc.managed.local.ManagedConnectionsByTransactionByDatasource;
 import org.apache.openejb.testing.Configuration;
 import org.apache.openejb.testing.Module;
 import org.junit.After;
@@ -36,6 +37,7 @@ import javax.ejb.TransactionAttribute;
 import javax.ejb.TransactionAttributeType;
 import javax.sql.DataSource;
 import javax.transaction.Transaction;
+
 import java.lang.reflect.Field;
 import java.sql.Connection;
 import java.sql.DriverManager;
@@ -200,7 +202,7 @@ public class ManagedDataSourceTest {
 
     @After
     public void checkTxMapIsEmpty() throws Exception { // avoid memory leak
-        final Field map = ManagedConnection.class.getDeclaredField("CONNECTION_BY_TX_BY_DS");
+        final Field map = ManagedConnectionsByTransactionByDatasource.class.getDeclaredField("CONNECTION_BY_TX_BY_DS");
         map.setAccessible(true);
         final Map<DataSource, Map<Transaction, Connection>> instance = (Map<DataSource, Map<Transaction, Connection>>) map.get(null);
         assertEquals(1, instance.size());

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/MultiThreadedManagedDataSourceTest.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/MultiThreadedManagedDataSourceTest.java b/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/MultiThreadedManagedDataSourceTest.java
index 15288fe..f538783 100644
--- a/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/MultiThreadedManagedDataSourceTest.java
+++ b/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/MultiThreadedManagedDataSourceTest.java
@@ -20,6 +20,7 @@ import org.apache.openejb.jee.EjbJar;
 import org.apache.openejb.jee.SingletonBean;
 import org.apache.openejb.junit.ApplicationComposer;
 import org.apache.openejb.resource.jdbc.managed.local.ManagedConnection;
+import org.apache.openejb.resource.jdbc.managed.local.ManagedConnectionsByTransactionByDatasource;
 import org.apache.openejb.testing.Configuration;
 import org.apache.openejb.testing.Module;
 import org.junit.After;
@@ -34,6 +35,7 @@ import javax.ejb.LocalBean;
 import javax.ejb.Singleton;
 import javax.sql.DataSource;
 import javax.transaction.Transaction;
+
 import java.lang.reflect.Field;
 import java.sql.Connection;
 import java.sql.DriverManager;
@@ -194,7 +196,7 @@ public class MultiThreadedManagedDataSourceTest {
 
     @After
     public void checkTxMapIsEmpty() throws Exception { // avoid memory leak
-        final Field map = ManagedConnection.class.getDeclaredField("CONNECTION_BY_TX_BY_DS");
+        final Field map = ManagedConnectionsByTransactionByDatasource.class.getDeclaredField("CONNECTION_BY_TX_BY_DS");
         map.setAccessible(true);
         final Map<DataSource, Map<Transaction, Connection>> instance = (Map<DataSource, Map<Transaction, Connection>>) map.get(null);
         assertEquals(1, instance.size());

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/UTManagedDataSourceTest.java
----------------------------------------------------------------------
diff --git a/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/UTManagedDataSourceTest.java b/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/UTManagedDataSourceTest.java
index 146a5b3..821a761 100644
--- a/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/UTManagedDataSourceTest.java
+++ b/container/openejb-core/src/test/java/org/apache/openejb/resource/jdbc/UTManagedDataSourceTest.java
@@ -20,6 +20,7 @@ import org.apache.openejb.jee.EjbJar;
 import org.apache.openejb.jee.SingletonBean;
 import org.apache.openejb.junit.ApplicationComposer;
 import org.apache.openejb.resource.jdbc.managed.local.ManagedConnection;
+import org.apache.openejb.resource.jdbc.managed.local.ManagedConnectionsByTransactionByDatasource;
 import org.apache.openejb.testing.Configuration;
 import org.apache.openejb.testing.Module;
 import org.junit.After;
@@ -36,6 +37,7 @@ import javax.ejb.TransactionManagementType;
 import javax.sql.DataSource;
 import javax.transaction.Transaction;
 import javax.transaction.UserTransaction;
+
 import java.lang.reflect.Field;
 import java.sql.Connection;
 import java.sql.DriverManager;
@@ -211,7 +213,7 @@ public class UTManagedDataSourceTest {
 
     @After
     public void checkTxMapIsEmpty() throws Exception { // avoid memory leak
-        final Field map = ManagedConnection.class.getDeclaredField("CONNECTION_BY_TX_BY_DS");
+        final Field map = ManagedConnectionsByTransactionByDatasource.class.getDeclaredField("CONNECTION_BY_TX_BY_DS");
         map.setAccessible(true);
         final Map<DataSource, Map<Transaction, Connection>> instance = (Map<DataSource, Map<Transaction, Connection>>) map.get(null);
         assertEquals(1, instance.size());

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractSynchronizable.java
----------------------------------------------------------------------
diff --git a/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractSynchronizable.java b/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractSynchronizable.java
index 488e372..1244882 100644
--- a/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractSynchronizable.java
+++ b/maven/tomee-maven-plugin/src/main/java/org/apache/openejb/maven/plugin/AbstractSynchronizable.java
@@ -1,71 +1,71 @@
-/**
- *
- * 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 java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-public abstract class AbstractSynchronizable {
-    protected int updateInterval;
-    protected List<String> extensions;
-    protected List<String> updateOnlyExtensions;
-    protected String regex;
-    protected Map<File, File> updates;
-
-    public abstract Map<File, File> updates();
-
-    public int getUpdateInterval() {
-        return updateInterval;
-    }
-
-    public void setUpdateInterval(final int updateInterval) {
-        this.updateInterval = updateInterval;
-    }
-
-    public List<String> getExtensions() {
-        if (extensions == null) {
-            extensions = new ArrayList<String>();
-        }
-        return extensions;
-    }
-
-    public void setExtensions(final List<String> extensions) {
-        this.extensions = extensions;
-    }
-
-    public String getRegex() {
-        return regex;
-    }
-
-    public void setRegex(final String regex) {
-        this.regex = regex;
-    }
-
-    public List<String> getUpdateOnlyExtenions() {
-        if (updateOnlyExtensions == null) {
-            updateOnlyExtensions = new ArrayList<String>();
-        }
-        return updateOnlyExtensions;
-    }
-
-    public void setUpdateOnlyExtensions(final List<String> updateOnlyExtensions) {
-        this.updateOnlyExtensions = updateOnlyExtensions;
-    }
-}
+/**
+ *
+ * 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 java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public abstract class AbstractSynchronizable {
+    protected int updateInterval;
+    protected List<String> extensions;
+    protected List<String> updateOnlyExtensions;
+    protected String regex;
+    protected Map<File, File> updates;
+
+    public abstract Map<File, File> updates();
+
+    public int getUpdateInterval() {
+        return updateInterval;
+    }
+
+    public void setUpdateInterval(final int updateInterval) {
+        this.updateInterval = updateInterval;
+    }
+
+    public List<String> getExtensions() {
+        if (extensions == null) {
+            extensions = new ArrayList<String>();
+        }
+        return extensions;
+    }
+
+    public void setExtensions(final List<String> extensions) {
+        this.extensions = extensions;
+    }
+
+    public String getRegex() {
+        return regex;
+    }
+
+    public void setRegex(final String regex) {
+        this.regex = regex;
+    }
+
+    public List<String> getUpdateOnlyExtenions() {
+        if (updateOnlyExtensions == null) {
+            updateOnlyExtensions = new ArrayList<String>();
+        }
+        return updateOnlyExtensions;
+    }
+
+    public void setUpdateOnlyExtensions(final List<String> updateOnlyExtensions) {
+        this.updateOnlyExtensions = updateOnlyExtensions;
+    }
+}

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/ComplexAllElement.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/ComplexAllElement.xsd b/server/openejb-axis/src/test/resources/schema/ComplexAllElement.xsd
index df9ef21..4821609 100644
--- a/server/openejb-axis/src/test/resources/schema/ComplexAllElement.xsd
+++ b/server/openejb-axis/src/test/resources/schema/ComplexAllElement.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="X"
         xmlns:tns="X"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/ComplexAllType.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/ComplexAllType.xsd b/server/openejb-axis/src/test/resources/schema/ComplexAllType.xsd
index f9dd8b4..9409581 100644
--- a/server/openejb-axis/src/test/resources/schema/ComplexAllType.xsd
+++ b/server/openejb-axis/src/test/resources/schema/ComplexAllType.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="X"
         xmlns:tns="X"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/ComplexSequenceElement.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/ComplexSequenceElement.xsd b/server/openejb-axis/src/test/resources/schema/ComplexSequenceElement.xsd
index 36299e3..f59ab72 100644
--- a/server/openejb-axis/src/test/resources/schema/ComplexSequenceElement.xsd
+++ b/server/openejb-axis/src/test/resources/schema/ComplexSequenceElement.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="X"
         xmlns:tns="X"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/ComplexSequenceType.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/ComplexSequenceType.xsd b/server/openejb-axis/src/test/resources/schema/ComplexSequenceType.xsd
index 34dbf99..0484e30 100644
--- a/server/openejb-axis/src/test/resources/schema/ComplexSequenceType.xsd
+++ b/server/openejb-axis/src/test/resources/schema/ComplexSequenceType.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="X"
         xmlns:tns="X"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/JaxRpcSpecExample.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/JaxRpcSpecExample.xsd b/server/openejb-axis/src/test/resources/schema/JaxRpcSpecExample.xsd
index a1bba13..65eb581 100644
--- a/server/openejb-axis/src/test/resources/schema/JaxRpcSpecExample.xsd
+++ b/server/openejb-axis/src/test/resources/schema/JaxRpcSpecExample.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="X"
         xmlns:tns="X"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/SimpleElement.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/SimpleElement.xsd b/server/openejb-axis/src/test/resources/schema/SimpleElement.xsd
index 9d4bd82..3f483e3 100644
--- a/server/openejb-axis/src/test/resources/schema/SimpleElement.xsd
+++ b/server/openejb-axis/src/test/resources/schema/SimpleElement.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="X"
         xmlns:tns="X"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/SimpleType.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/SimpleType.xsd b/server/openejb-axis/src/test/resources/schema/SimpleType.xsd
index 83339ae..894c3b4 100644
--- a/server/openejb-axis/src/test/resources/schema/SimpleType.xsd
+++ b/server/openejb-axis/src/test/resources/schema/SimpleType.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="X"
         xmlns:tns="X"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/SoapArrayByAttribute.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/SoapArrayByAttribute.xsd b/server/openejb-axis/src/test/resources/schema/SoapArrayByAttribute.xsd
index 5696c61..1f63eed 100644
--- a/server/openejb-axis/src/test/resources/schema/SoapArrayByAttribute.xsd
+++ b/server/openejb-axis/src/test/resources/schema/SoapArrayByAttribute.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <xsd:schema
         targetNamespace="X"
         xmlns:tns="X"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-axis/src/test/resources/schema/SoapArrayByRestriction.xsd
----------------------------------------------------------------------
diff --git a/server/openejb-axis/src/test/resources/schema/SoapArrayByRestriction.xsd b/server/openejb-axis/src/test/resources/schema/SoapArrayByRestriction.xsd
index 9b61fcc..ab4c67b 100644
--- a/server/openejb-axis/src/test/resources/schema/SoapArrayByRestriction.xsd
+++ b/server/openejb-axis/src/test/resources/schema/SoapArrayByRestriction.xsd
@@ -1,24 +1,24 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
-    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.
--->
-
-<!-- $Rev$ $Date$ -->
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+-->
+
+<!-- $Rev$ $Date$ -->
+
 <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="X"
         xmlns:tns="X"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/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;
+    }
+}


[4/6] tomee git commit: Re-use the connection for the datasource and transaction rather than fetch another one only to throw it away later. Slightly experimental change to prevent the db pool locking up.

Posted by jg...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/PojoInvoker.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/PojoInvoker.java b/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/PojoInvoker.java
index 61468be..805d813 100644
--- a/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/PojoInvoker.java
+++ b/server/openejb-cxf-rs/src/main/java/org/apache/openejb/server/cxf/rs/PojoInvoker.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.rs;
-
-import org.apache.cxf.jaxrs.JAXRSInvoker;
-import org.apache.cxf.message.Exchange;
-import org.apache.cxf.message.Message;
-import org.apache.openejb.ApplicationException;
-import org.apache.openejb.InvalidateReferenceException;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.rmi.RemoteException;
-import java.util.Arrays;
-import java.util.logging.Level;
-
-public class PojoInvoker extends JAXRSInvoker {
-    protected Object performInvocation(final Exchange exchange, final Object serviceObject,
-                                       final Method m, final Object[] paramArray) throws Exception {
-        final Object[] args = insertExchange(m, paramArray, exchange);
-        final ClassLoader tcclToUse = getClassLoader(exchange);
-        final Thread thread = Thread.currentThread();
-        ClassLoader oldLoader = null;
-        if (tcclToUse != null) {
-            oldLoader = thread.getContextClassLoader();
-            thread.setContextClassLoader(tcclToUse);
-        }
-        try {
-            return m.invoke(serviceObject, args);
-        } finally {
-            if (tcclToUse != null) {
-                thread.setContextClassLoader(oldLoader);
-            }
-        }
-    }
-
-    private ClassLoader getClassLoader(final Exchange exchange) {
-        final Message inMessage = exchange.getInMessage();
-        if (inMessage == null) {
-            return null;
-        }
-        final OpenEJBPerRequestPojoResourceProvider requestPojoResourceProvider = inMessage.get(OpenEJBPerRequestPojoResourceProvider.class);
-        if (requestPojoResourceProvider != null) {
-            return requestPojoResourceProvider.getClassLoader();
-        }
-        return null;
-    }
-}
+/*
+ * 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.cxf.message.Message;
+import org.apache.openejb.ApplicationException;
+import org.apache.openejb.InvalidateReferenceException;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.rmi.RemoteException;
+import java.util.Arrays;
+import java.util.logging.Level;
+
+public class PojoInvoker extends JAXRSInvoker {
+    protected Object performInvocation(final Exchange exchange, final Object serviceObject,
+                                       final Method m, final Object[] paramArray) throws Exception {
+        final Object[] args = insertExchange(m, paramArray, exchange);
+        final ClassLoader tcclToUse = getClassLoader(exchange);
+        final Thread thread = Thread.currentThread();
+        ClassLoader oldLoader = null;
+        if (tcclToUse != null) {
+            oldLoader = thread.getContextClassLoader();
+            thread.setContextClassLoader(tcclToUse);
+        }
+        try {
+            return m.invoke(serviceObject, args);
+        } finally {
+            if (tcclToUse != null) {
+                thread.setContextClassLoader(oldLoader);
+            }
+        }
+    }
+
+    private ClassLoader getClassLoader(final Exchange exchange) {
+        final Message inMessage = exchange.getInMessage();
+        if (inMessage == null) {
+            return null;
+        }
+        final OpenEJBPerRequestPojoResourceProvider requestPojoResourceProvider = inMessage.get(OpenEJBPerRequestPojoResourceProvider.class);
+        if (requestPojoResourceProvider != null) {
+            return requestPojoResourceProvider.getClassLoader();
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorService.java
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorService.java b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorService.java
index 6a29e16..1358cdd 100644
--- a/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorService.java
+++ b/server/openejb-cxf/src/test/java/org/apache/openejb/server/cxf/fault/AuthenticatorService.java
@@ -1,31 +1,31 @@
-/**
- * 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.jws.WebService;
-
-/**
- * @version $Rev$
- */
-@WebService(targetNamespace = "http://superbiz.org/wsdl")
-public interface AuthenticatorService {
-
-    boolean authenticate(String name, String password) throws WrongPasswordException;
-
-    boolean authenticateRuntime(String name, String password);
-
+/**
+ * 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.jws.WebService;
+
+/**
+ * @version $Rev$
+ */
+@WebService(targetNamespace = "http://superbiz.org/wsdl")
+public interface AuthenticatorService {
+
+    boolean authenticate(String name, String password) throws WrongPasswordException;
+
+    boolean authenticateRuntime(String name, String password);
+
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/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


[5/6] tomee git commit: Re-use the connection for the datasource and transaction rather than fetch another one only to throw it away later. Slightly experimental change to prevent the db pool locking up.

Posted by jg...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/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);
+    }
+}


[3/6] tomee git commit: Re-use the connection for the datasource and transaction rather than fetch another one only to throw it away later. Slightly experimental change to prevent the db pool locking up.

Posted by jg...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/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/bd7dbd0f/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

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-cxf/src/test/resources/META-INF/ejb-jar.xml
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/resources/META-INF/ejb-jar.xml b/server/openejb-cxf/src/test/resources/META-INF/ejb-jar.xml
index 00a4cbe..676b4ba 100644
--- a/server/openejb-cxf/src/test/resources/META-INF/ejb-jar.xml
+++ b/server/openejb-cxf/src/test/resources/META-INF/ejb-jar.xml
@@ -1,19 +1,19 @@
-<!--
-  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.
--->
+<!--
+  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.
+-->
 <ejb-jar/>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-cxf/src/test/resources/org/apache/openejb/server/cxf/fault/handler.xml
----------------------------------------------------------------------
diff --git a/server/openejb-cxf/src/test/resources/org/apache/openejb/server/cxf/fault/handler.xml b/server/openejb-cxf/src/test/resources/org/apache/openejb/server/cxf/fault/handler.xml
index 337711f..8a3c7c4 100644
--- a/server/openejb-cxf/src/test/resources/org/apache/openejb/server/cxf/fault/handler.xml
+++ b/server/openejb-cxf/src/test/resources/org/apache/openejb/server/cxf/fault/handler.xml
@@ -1,27 +1,27 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  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.
--->
-<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
-  <handler-chain>
-    <handler>
-      <handler-name>org.apache.openejb.server.cxf.fault.DummyInterceptor</handler-name>
-      <handler-class>org.apache.openejb.server.cxf.fault.DummyInterceptor</handler-class>
-    </handler>
-  </handler-chain>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  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.
+-->
+<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
+  <handler-chain>
+    <handler>
+      <handler-name>org.apache.openejb.server.cxf.fault.DummyInterceptor</handler-name>
+      <handler-class>org.apache.openejb.server.cxf.fault.DummyInterceptor</handler-class>
+    </handler>
+  </handler-chain>
 </handler-chains>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/RequestHandler.java
----------------------------------------------------------------------
diff --git a/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/RequestHandler.java b/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/RequestHandler.java
index 93fcd3d..18f1c8d 100644
--- a/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/RequestHandler.java
+++ b/server/openejb-ejbd/src/main/java/org/apache/openejb/server/ejbd/RequestHandler.java
@@ -1,45 +1,45 @@
-/**
- * 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.ejbd;
-
-import org.apache.openejb.client.ProtocolMetaData;
-import org.apache.openejb.client.Response;
-import org.apache.openejb.util.Logger;
-
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-public abstract class RequestHandler {
-
-    final EjbDaemon daemon;
-
-    protected RequestHandler(final EjbDaemon daemon) {
-        this.daemon = daemon;
-    }
-
-    public EjbDaemon getDaemon() {
-        return daemon;
-    }
-
-    public abstract String getName();
-
-    public abstract Logger getLogger();
-
-    public abstract Response processRequest(final ObjectInputStream in, final ProtocolMetaData metaData) throws Exception;
-
-    public abstract void processResponse(final Response response, final ObjectOutputStream out, final ProtocolMetaData metaData) throws 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.ejbd;
+
+import org.apache.openejb.client.ProtocolMetaData;
+import org.apache.openejb.client.Response;
+import org.apache.openejb.util.Logger;
+
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+public abstract class RequestHandler {
+
+    final EjbDaemon daemon;
+
+    protected RequestHandler(final EjbDaemon daemon) {
+        this.daemon = daemon;
+    }
+
+    public EjbDaemon getDaemon() {
+        return daemon;
+    }
+
+    public abstract String getName();
+
+    public abstract Logger getLogger();
+
+    public abstract Response processRequest(final ObjectInputStream in, final ProtocolMetaData metaData) throws Exception;
+
+    public abstract void processResponse(final Response response, final ObjectOutputStream out, final ProtocolMetaData metaData) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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/bd7dbd0f/server/openejb-multicast/src/main/resources/META-INF/org.apache.openejb.server.ServerService/multipulse
----------------------------------------------------------------------
diff --git a/server/openejb-multicast/src/main/resources/META-INF/org.apache.openejb.server.ServerService/multipulse b/server/openejb-multicast/src/main/resources/META-INF/org.apache.openejb.server.ServerService/multipulse
index 9f6f174..1ac80f9 100644
--- a/server/openejb-multicast/src/main/resources/META-INF/org.apache.openejb.server.ServerService/multipulse
+++ b/server/openejb-multicast/src/main/resources/META-INF/org.apache.openejb.server.ServerService/multipulse
@@ -1,4 +1,4 @@
-server      = org.apache.openejb.server.discovery.MulticastPulseAgent
-bind        = 239.255.2.3
-port        = 6142
+server      = org.apache.openejb.server.discovery.MulticastPulseAgent
+bind        = 239.255.2.3
+port        = 6142
 disabled    = ${openejb.profile.custom}
\ No newline at end of file


[2/6] tomee git commit: Re-use the connection for the datasource and transaction rather than fetch another one only to throw it away later. Slightly experimental change to prevent the db pool locking up.

Posted by jg...@apache.org.
http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-multicast/src/test/java/org/apache/openejb/server/discovery/MulticastPulseAgentTest.java
----------------------------------------------------------------------
diff --git a/server/openejb-multicast/src/test/java/org/apache/openejb/server/discovery/MulticastPulseAgentTest.java b/server/openejb-multicast/src/test/java/org/apache/openejb/server/discovery/MulticastPulseAgentTest.java
index 223a768..92147ed 100644
--- a/server/openejb-multicast/src/test/java/org/apache/openejb/server/discovery/MulticastPulseAgentTest.java
+++ b/server/openejb-multicast/src/test/java/org/apache/openejb/server/discovery/MulticastPulseAgentTest.java
@@ -1,513 +1,513 @@
-/**
- * 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.discovery;
-
-import org.apache.openejb.server.DiscoveryListener;
-import org.apache.openejb.util.NetworkUtil;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import sun.net.util.IPAddressUtil;
-
-import java.net.DatagramPacket;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.MulticastSocket;
-import java.net.SocketAddress;
-import java.net.URI;
-import java.net.UnknownHostException;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Properties;
-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.Logger;
-
-@SuppressWarnings("UseOfSystemOutOrSystemErr")
-public class MulticastPulseAgentTest {
-
-    private static final Set<String> schemes = new HashSet<String>(Arrays.asList("ejbd", "ejbds", "http"));
-    private static ExecutorService executor;
-    private static final Charset utf8 = Charset.forName("UTF-8");
-    private static final String forGroup = "*";
-    private static final String host = "239.255.3.2";
-    private static final int port = NetworkUtil.getNextAvailablePort();
-    private static MulticastPulseAgent agent;
-
-    @BeforeClass
-    public static void beforeClass() throws Exception {
-
-        executor = Executors.newFixedThreadPool(10);
-
-        final Properties p = new Properties();
-        p.setProperty("bind", host);
-        p.setProperty("port", "" + port);
-
-        agent = new MulticastPulseAgent();
-        agent.init(p);
-        agent.setDiscoveryListener(new MyDiscoveryListener("MulticastPulseAgentTest"));
-        agent.registerService(new URI("ejb:ejbd://[::]:4201"));
-        agent.registerService(new URI("ejb:ejbd://0.0.0.0:4201"));
-        agent.registerService(new URI("ejb:http://127.0.0.1:4201"));
-        agent.registerService(new URI("ejb:https://0.0.0.1:4201"));
-        agent.start();
-
-        System.out.println();
-    }
-
-    @AfterClass
-    public static void afterClass() throws Exception {
-        agent.stop();
-        executor.shutdownNow();
-    }
-
-    /**
-     * Most of this code is identical to org.apache.openejb.client.MulticastPulseClient#discoverURIs
-     * <p/>
-     * The MulticastPulseClient class is not shared or available here so the test has to emulate it.
-     *
-     * @throws Exception On error
-     */
-    @Test
-    public void test() throws Exception {
-        if ("true".equals(System.getProperty("skipMulticastTests"))) {
-            Logger.getLogger(this.getClass().getName()).warning("Skipping MulticastTest " + this.getClass().getName());
-            return;
-        }
-
-        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");
-        }
-
-        //Returns at least one socket per valid network interface
-        final MulticastSocket[] clientSockets = MulticastPulseAgent.getSockets(host, port);
-
-        //No point going on if we don't have sockets...
-        if (clientSockets.length < 1) {
-            System.out.println("Cannnot perform multipulse test without a valid interface");
-            return;
-        }
-
-        final byte[] bytes = (MulticastPulseAgent.CLIENT + forGroup).getBytes(utf8);
-        final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
-        final AtomicBoolean running = new AtomicBoolean(true);
-        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 Throwable 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 ArrayList<Future> futures = new ArrayList<Future>();
-        final CountDownLatch latch = new CountDownLatch(clientSockets.length);
-
-        for (final MulticastSocket socket : clientSockets) {
-
-            futures.add(executor.submit(new Runnable() {
-                @Override
-                public void run() {
-
-                    String name = "Unknown interface";
-                    try {
-                        name = socket.getNetworkInterface().getDisplayName();
-                    } catch (final Throwable e) {
-                        //Ignore
-                    }
-                    System.out.println("Entered MulticastPulse client thread on: " + name);
-
-                    final DatagramPacket response = new DatagramPacket(new byte[2048], 2048);
-
-                    latch.countDown();
-
-                    while (running.get()) {
-                        try {
-
-                            socket.receive(response);
-
-                            final SocketAddress sa = response.getSocketAddress();
-
-                            if ((sa instanceof InetSocketAddress)) {
-
-                                int len = response.getLength();
-                                if (len > 2048) {
-                                    len = 2048;
-                                }
-
-                                String s = new String(response.getData(), 0, len);
-
-                                if (s.startsWith(MulticastPulseAgent.SERVER)) {
-
-                                    s = (s.replace(MulticastPulseAgent.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(",");
-
-                                    System.out.println(String.format("\n" + name + " received Server pulse:\n\tGroup: %1$s\n\tServices: %2$s\n\tServer: %3$s\n",
-                                            group,
-                                            services,
-                                            s));
-
-                                    for (final String svc : serviceList) {
-
-                                        if (MulticastPulseAgent.EMPTY.equals(svc)) {
-                                            continue;
-                                        }
-
-                                        final URI serviceUri;
-                                        try {
-                                            serviceUri = URI.create(svc);
-                                        } catch (final Throwable 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 (MulticastPulseAgent.isLocalAddress(serviceHost, false)) {
-                                                if (!MulticastPulseAgent.isLocalAddress(serverHost, false)) {
-                                                    //A local service is only available to a local client
-                                                    continue;
-                                                }
-                                            }
-
-                                            final String fullsvc = ("mp-" + serverHost + ":" + group + ":" + svc);
-
-                                            setLock.lock();
-
-                                            try {
-                                                if (fullsvc.contains("0.0.0.0")) {
-                                                    for (final String h : hosts) {
-                                                        if (!h.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
-                                                            set.add(URI.create(fullsvc.replace("0.0.0.0", ipFormat(h))));
-                                                        }
-                                                    }
-                                                } else if (fullsvc.contains("[::]")) {
-                                                    for (final String h : hosts) {
-                                                        if (!h.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
-                                                            set.add(URI.create(fullsvc.replace("[::]", ipFormat(h))));
-                                                        }
-                                                    }
-                                                } else {
-                                                    //Just add as is
-                                                    set.add(URI.create(fullsvc));
-                                                }
-                                            } catch (final Throwable e) {
-                                                //Ignore
-                                            } finally {
-                                                setLock.unlock();
-                                            }
-                                        } else {
-                                            System.out.println("Reject service: " + serviceUri.toASCIIString() + " - Not looking for scheme: " + serviceUri.getScheme());
-                                        }
-                                    }
-                                }
-                            }
-
-                        } catch (final Throwable e) {
-                            //Ignore
-                        }
-                    }
-
-                    System.out.println("Exit MulticastPulse client thread on: " + name);
-                    System.out.flush();
-                }
-            }));
-        }
-
-        //Allow slow thread starts
-        System.out.println("Wait for threads to start");
-        int timeout = 5000;
-        try {
-
-            //Give threads a generous amount of time to start
-            if (latch.await(15, TimeUnit.SECONDS)) {
-                System.out.println("Threads have started");
-
-                //Pulse the server - It is thread safe to use same sockets as send/receive synchronization is only on the packet
-                for (final MulticastSocket socket : clientSockets) {
-                    try {
-                        socket.send(request);
-                    } catch (final Throwable e) {
-                        //Ignore
-                    }
-                }
-            } else {
-                timeout = 1;
-                System.out.println("Giving up on threads");
-            }
-
-        } catch (final InterruptedException e) {
-            timeout = 1;
-        }
-
-        //Kill the threads after timeout
-        timer.schedule(new TimerTask() {
-            @Override
-            public void run() {
-
-                running.set(false);
-
-                for (final Future future : futures) {
-                    try {
-                        future.cancel(true);
-                    } catch (final Throwable e) {
-                        //Ignore
-                    }
-                }
-
-                for (final MulticastSocket socket : clientSockets) {
-
-                    try {
-                        socket.leaveGroup(ia);
-                    } catch (final Throwable e) {
-                        //Ignore
-                    }
-                    try {
-                        socket.close();
-                    } catch (final Throwable e) {
-                        //Ignore
-                    }
-                }
-            }
-        }, timeout);
-
-        //Wait for threads to complete
-        for (final Future future : futures) {
-            try {
-                future.get();
-            } catch (final Throwable e) {
-                //Ignore
-            }
-        }
-
-        System.out.println();
-        System.out.flush();
-
-        final ArrayList<String> list = new ArrayList<String>();
-
-        final TreeSet<URI> uris = new TreeSet<URI>(set);
-        for (final URI uri : uris) {
-            final String astr = uri.toASCIIString();
-            System.out.println("MultiPulse discovered: " + astr);
-
-            if (list.contains(astr)) {
-                System.out.println("Duplicate uri: " + uri);
-            }
-
-            org.junit.Assert.assertTrue(!list.contains(astr));
-            list.add(astr);
-        }
-
-        System.out.println("Multipulse complete");
-
-        //If timeout == 1 assume either a cancel or the test took too long (Will not fail)
-        org.junit.Assert.assertTrue(timeout == 1 || set.size() > 0);
-    }
-
-    @Test
-    public void testBroadcastBadUri() throws Exception {
-        if ("true".equals(System.getProperty("skipMulticastTests"))) {
-            Logger.getLogger(this.getClass().getName()).warning("Skipping MulticastTest " + this.getClass().getName());
-            return;
-        }
-
-        final DiscoveryListener original = agent.getDiscoveryListener();
-
-        final CountDownLatch latch = new CountDownLatch(1);
-
-        final DiscoveryListener listener = new DiscoveryListener() {
-            @Override
-            public void serviceAdded(final URI service) {
-                latch.countDown();
-                System.out.println("added = " + service);
-            }
-
-            @Override
-            public void serviceRemoved(final URI service) {
-                latch.countDown();
-                System.out.println("removed = " + service);
-            }
-        };
-
-        agent.setDiscoveryListener(listener);
-
-        final String[] hosts = agent.getHosts().split(",");
-        final String host = hosts[hosts.length - 1];
-
-        boolean removed = agent.removeFromIgnore(host);
-        org.junit.Assert.assertTrue("Host is already ignored", !removed);
-
-        final Future<?> future = executor.submit(new Runnable() {
-            @Override
-            public void run() {
-                try {
-                    final InetAddress ia = getAddress(MulticastPulseAgentTest.host);
-
-                    final byte[] bytes = (MulticastPulseAgent.CLIENT + forGroup + MulticastPulseAgent.BADURI + host).getBytes(Charset.forName("UTF-8"));
-                    final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
-
-                    final MulticastSocket[] multicastSockets = MulticastPulseAgent.getSockets(MulticastPulseAgentTest.host, port);
-
-                    for (int i = 0; i < 5; i++) {
-                        for (final MulticastSocket socket : multicastSockets) {
-
-                            try {
-                                socket.send(request);
-                                Thread.sleep(100);
-                            } catch (final Exception e) {
-                                System.out.println("Failed to broadcast bad URI on: " + socket.getInterface().getHostAddress());
-                                e.printStackTrace();
-                            }
-                        }
-                    }
-                } catch (final Exception e) {
-                    System.out.println("Failed to broadcast bad URI");
-                    e.printStackTrace();
-                }
-            }
-        });
-
-        final boolean await = latch.await(20, TimeUnit.SECONDS);
-        removed = agent.removeFromIgnore(host);
-
-        agent.setDiscoveryListener(original);
-
-        org.junit.Assert.assertTrue("Failed to remove host", removed);
-        org.junit.Assert.assertTrue("Failed to unlatch", await);
-    }
-
-    private String ipFormat(final String h) throws UnknownHostException {
-
-        final InetAddress ia = InetAddress.getByName(h);
-        if (ia instanceof Inet6Address) {
-            return "[" + ia.getHostAddress() + "]";
-        } else {
-            return h;
-        }
-    }
-
-    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;
-    }
-
-    private static class MyDiscoveryListener implements DiscoveryListener {
-
-        private final String id;
-
-        public MyDiscoveryListener(final String id) {
-            this.id = id;
-        }
-
-        @Override
-        public void serviceAdded(final URI service) {
-            System.out.println(id + ": add : " + service.toString());
-        }
-
-        @Override
-        public void serviceRemoved(final URI service) {
-            System.out.println(id + ": remove : " + service.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.openejb.server.discovery;
+
+import org.apache.openejb.server.DiscoveryListener;
+import org.apache.openejb.util.NetworkUtil;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import sun.net.util.IPAddressUtil;
+
+import java.net.DatagramPacket;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MulticastSocket;
+import java.net.SocketAddress;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Properties;
+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.Logger;
+
+@SuppressWarnings("UseOfSystemOutOrSystemErr")
+public class MulticastPulseAgentTest {
+
+    private static final Set<String> schemes = new HashSet<String>(Arrays.asList("ejbd", "ejbds", "http"));
+    private static ExecutorService executor;
+    private static final Charset utf8 = Charset.forName("UTF-8");
+    private static final String forGroup = "*";
+    private static final String host = "239.255.3.2";
+    private static final int port = NetworkUtil.getNextAvailablePort();
+    private static MulticastPulseAgent agent;
+
+    @BeforeClass
+    public static void beforeClass() throws Exception {
+
+        executor = Executors.newFixedThreadPool(10);
+
+        final Properties p = new Properties();
+        p.setProperty("bind", host);
+        p.setProperty("port", "" + port);
+
+        agent = new MulticastPulseAgent();
+        agent.init(p);
+        agent.setDiscoveryListener(new MyDiscoveryListener("MulticastPulseAgentTest"));
+        agent.registerService(new URI("ejb:ejbd://[::]:4201"));
+        agent.registerService(new URI("ejb:ejbd://0.0.0.0:4201"));
+        agent.registerService(new URI("ejb:http://127.0.0.1:4201"));
+        agent.registerService(new URI("ejb:https://0.0.0.1:4201"));
+        agent.start();
+
+        System.out.println();
+    }
+
+    @AfterClass
+    public static void afterClass() throws Exception {
+        agent.stop();
+        executor.shutdownNow();
+    }
+
+    /**
+     * Most of this code is identical to org.apache.openejb.client.MulticastPulseClient#discoverURIs
+     * <p/>
+     * The MulticastPulseClient class is not shared or available here so the test has to emulate it.
+     *
+     * @throws Exception On error
+     */
+    @Test
+    public void test() throws Exception {
+        if ("true".equals(System.getProperty("skipMulticastTests"))) {
+            Logger.getLogger(this.getClass().getName()).warning("Skipping MulticastTest " + this.getClass().getName());
+            return;
+        }
+
+        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");
+        }
+
+        //Returns at least one socket per valid network interface
+        final MulticastSocket[] clientSockets = MulticastPulseAgent.getSockets(host, port);
+
+        //No point going on if we don't have sockets...
+        if (clientSockets.length < 1) {
+            System.out.println("Cannnot perform multipulse test without a valid interface");
+            return;
+        }
+
+        final byte[] bytes = (MulticastPulseAgent.CLIENT + forGroup).getBytes(utf8);
+        final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
+        final AtomicBoolean running = new AtomicBoolean(true);
+        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 Throwable 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 ArrayList<Future> futures = new ArrayList<Future>();
+        final CountDownLatch latch = new CountDownLatch(clientSockets.length);
+
+        for (final MulticastSocket socket : clientSockets) {
+
+            futures.add(executor.submit(new Runnable() {
+                @Override
+                public void run() {
+
+                    String name = "Unknown interface";
+                    try {
+                        name = socket.getNetworkInterface().getDisplayName();
+                    } catch (final Throwable e) {
+                        //Ignore
+                    }
+                    System.out.println("Entered MulticastPulse client thread on: " + name);
+
+                    final DatagramPacket response = new DatagramPacket(new byte[2048], 2048);
+
+                    latch.countDown();
+
+                    while (running.get()) {
+                        try {
+
+                            socket.receive(response);
+
+                            final SocketAddress sa = response.getSocketAddress();
+
+                            if ((sa instanceof InetSocketAddress)) {
+
+                                int len = response.getLength();
+                                if (len > 2048) {
+                                    len = 2048;
+                                }
+
+                                String s = new String(response.getData(), 0, len);
+
+                                if (s.startsWith(MulticastPulseAgent.SERVER)) {
+
+                                    s = (s.replace(MulticastPulseAgent.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(",");
+
+                                    System.out.println(String.format("\n" + name + " received Server pulse:\n\tGroup: %1$s\n\tServices: %2$s\n\tServer: %3$s\n",
+                                            group,
+                                            services,
+                                            s));
+
+                                    for (final String svc : serviceList) {
+
+                                        if (MulticastPulseAgent.EMPTY.equals(svc)) {
+                                            continue;
+                                        }
+
+                                        final URI serviceUri;
+                                        try {
+                                            serviceUri = URI.create(svc);
+                                        } catch (final Throwable 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 (MulticastPulseAgent.isLocalAddress(serviceHost, false)) {
+                                                if (!MulticastPulseAgent.isLocalAddress(serverHost, false)) {
+                                                    //A local service is only available to a local client
+                                                    continue;
+                                                }
+                                            }
+
+                                            final String fullsvc = ("mp-" + serverHost + ":" + group + ":" + svc);
+
+                                            setLock.lock();
+
+                                            try {
+                                                if (fullsvc.contains("0.0.0.0")) {
+                                                    for (final String h : hosts) {
+                                                        if (!h.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
+                                                            set.add(URI.create(fullsvc.replace("0.0.0.0", ipFormat(h))));
+                                                        }
+                                                    }
+                                                } else if (fullsvc.contains("[::]")) {
+                                                    for (final String h : hosts) {
+                                                        if (!h.replace("[", "").startsWith("2001:0:")) { //Filter Teredo
+                                                            set.add(URI.create(fullsvc.replace("[::]", ipFormat(h))));
+                                                        }
+                                                    }
+                                                } else {
+                                                    //Just add as is
+                                                    set.add(URI.create(fullsvc));
+                                                }
+                                            } catch (final Throwable e) {
+                                                //Ignore
+                                            } finally {
+                                                setLock.unlock();
+                                            }
+                                        } else {
+                                            System.out.println("Reject service: " + serviceUri.toASCIIString() + " - Not looking for scheme: " + serviceUri.getScheme());
+                                        }
+                                    }
+                                }
+                            }
+
+                        } catch (final Throwable e) {
+                            //Ignore
+                        }
+                    }
+
+                    System.out.println("Exit MulticastPulse client thread on: " + name);
+                    System.out.flush();
+                }
+            }));
+        }
+
+        //Allow slow thread starts
+        System.out.println("Wait for threads to start");
+        int timeout = 5000;
+        try {
+
+            //Give threads a generous amount of time to start
+            if (latch.await(15, TimeUnit.SECONDS)) {
+                System.out.println("Threads have started");
+
+                //Pulse the server - It is thread safe to use same sockets as send/receive synchronization is only on the packet
+                for (final MulticastSocket socket : clientSockets) {
+                    try {
+                        socket.send(request);
+                    } catch (final Throwable e) {
+                        //Ignore
+                    }
+                }
+            } else {
+                timeout = 1;
+                System.out.println("Giving up on threads");
+            }
+
+        } catch (final InterruptedException e) {
+            timeout = 1;
+        }
+
+        //Kill the threads after timeout
+        timer.schedule(new TimerTask() {
+            @Override
+            public void run() {
+
+                running.set(false);
+
+                for (final Future future : futures) {
+                    try {
+                        future.cancel(true);
+                    } catch (final Throwable e) {
+                        //Ignore
+                    }
+                }
+
+                for (final MulticastSocket socket : clientSockets) {
+
+                    try {
+                        socket.leaveGroup(ia);
+                    } catch (final Throwable e) {
+                        //Ignore
+                    }
+                    try {
+                        socket.close();
+                    } catch (final Throwable e) {
+                        //Ignore
+                    }
+                }
+            }
+        }, timeout);
+
+        //Wait for threads to complete
+        for (final Future future : futures) {
+            try {
+                future.get();
+            } catch (final Throwable e) {
+                //Ignore
+            }
+        }
+
+        System.out.println();
+        System.out.flush();
+
+        final ArrayList<String> list = new ArrayList<String>();
+
+        final TreeSet<URI> uris = new TreeSet<URI>(set);
+        for (final URI uri : uris) {
+            final String astr = uri.toASCIIString();
+            System.out.println("MultiPulse discovered: " + astr);
+
+            if (list.contains(astr)) {
+                System.out.println("Duplicate uri: " + uri);
+            }
+
+            org.junit.Assert.assertTrue(!list.contains(astr));
+            list.add(astr);
+        }
+
+        System.out.println("Multipulse complete");
+
+        //If timeout == 1 assume either a cancel or the test took too long (Will not fail)
+        org.junit.Assert.assertTrue(timeout == 1 || set.size() > 0);
+    }
+
+    @Test
+    public void testBroadcastBadUri() throws Exception {
+        if ("true".equals(System.getProperty("skipMulticastTests"))) {
+            Logger.getLogger(this.getClass().getName()).warning("Skipping MulticastTest " + this.getClass().getName());
+            return;
+        }
+
+        final DiscoveryListener original = agent.getDiscoveryListener();
+
+        final CountDownLatch latch = new CountDownLatch(1);
+
+        final DiscoveryListener listener = new DiscoveryListener() {
+            @Override
+            public void serviceAdded(final URI service) {
+                latch.countDown();
+                System.out.println("added = " + service);
+            }
+
+            @Override
+            public void serviceRemoved(final URI service) {
+                latch.countDown();
+                System.out.println("removed = " + service);
+            }
+        };
+
+        agent.setDiscoveryListener(listener);
+
+        final String[] hosts = agent.getHosts().split(",");
+        final String host = hosts[hosts.length - 1];
+
+        boolean removed = agent.removeFromIgnore(host);
+        org.junit.Assert.assertTrue("Host is already ignored", !removed);
+
+        final Future<?> future = executor.submit(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    final InetAddress ia = getAddress(MulticastPulseAgentTest.host);
+
+                    final byte[] bytes = (MulticastPulseAgent.CLIENT + forGroup + MulticastPulseAgent.BADURI + host).getBytes(Charset.forName("UTF-8"));
+                    final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
+
+                    final MulticastSocket[] multicastSockets = MulticastPulseAgent.getSockets(MulticastPulseAgentTest.host, port);
+
+                    for (int i = 0; i < 5; i++) {
+                        for (final MulticastSocket socket : multicastSockets) {
+
+                            try {
+                                socket.send(request);
+                                Thread.sleep(100);
+                            } catch (final Exception e) {
+                                System.out.println("Failed to broadcast bad URI on: " + socket.getInterface().getHostAddress());
+                                e.printStackTrace();
+                            }
+                        }
+                    }
+                } catch (final Exception e) {
+                    System.out.println("Failed to broadcast bad URI");
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        final boolean await = latch.await(20, TimeUnit.SECONDS);
+        removed = agent.removeFromIgnore(host);
+
+        agent.setDiscoveryListener(original);
+
+        org.junit.Assert.assertTrue("Failed to remove host", removed);
+        org.junit.Assert.assertTrue("Failed to unlatch", await);
+    }
+
+    private String ipFormat(final String h) throws UnknownHostException {
+
+        final InetAddress ia = InetAddress.getByName(h);
+        if (ia instanceof Inet6Address) {
+            return "[" + ia.getHostAddress() + "]";
+        } else {
+            return h;
+        }
+    }
+
+    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;
+    }
+
+    private static class MyDiscoveryListener implements DiscoveryListener {
+
+        private final String id;
+
+        public MyDiscoveryListener(final String id) {
+            this.id = id;
+        }
+
+        @Override
+        public void serviceAdded(final URI service) {
+            System.out.println(id + ": add : " + service.toString());
+        }
+
+        @Override
+        public void serviceRemoved(final URI service) {
+            System.out.println(id + ": remove : " + service.toString());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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;
+    }
+}

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/InternalApplication.java
----------------------------------------------------------------------
diff --git a/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/InternalApplication.java b/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/InternalApplication.java
index 2035805..cb36fda 100644
--- a/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/InternalApplication.java
+++ b/server/openejb-rest/src/main/java/org/apache/openejb/server/rest/InternalApplication.java
@@ -1,45 +1,45 @@
-/*
- * 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 javax.ws.rs.core.Application;
-import java.util.HashSet;
-import java.util.Set;
-
-public class InternalApplication extends Application {
-    private final Set<Class<?>> classes = new HashSet<Class<?>>();
-    private final Set<Object> singletons = new HashSet<Object>();
-    private final Application original;
-
-    public InternalApplication(final Application original) {
-        this.original = original;
-    }
-
-    @Override
-    public Set<Class<?>> getClasses() {
-        return classes;
-    }
-
-    @Override
-    public Set<Object> getSingletons() {
-        return singletons;
-    }
-
-    public Application getOriginal() {
-        return original;
-    }
-}
+/*
+ * 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 javax.ws.rs.core.Application;
+import java.util.HashSet;
+import java.util.Set;
+
+public class InternalApplication extends Application {
+    private final Set<Class<?>> classes = new HashSet<Class<?>>();
+    private final Set<Object> singletons = new HashSet<Object>();
+    private final Application original;
+
+    public InternalApplication(final Application original) {
+        this.original = original;
+    }
+
+    @Override
+    public Set<Class<?>> getClasses() {
+        return classes;
+    }
+
+    @Override
+    public Set<Object> getSingletons() {
+        return singletons;
+    }
+
+    public Application getOriginal() {
+        return original;
+    }
+}

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-server/src/main/resources/META-INF/openejb-server.xml
----------------------------------------------------------------------
diff --git a/server/openejb-server/src/main/resources/META-INF/openejb-server.xml b/server/openejb-server/src/main/resources/META-INF/openejb-server.xml
index 42cd306..05473d9 100644
--- a/server/openejb-server/src/main/resources/META-INF/openejb-server.xml
+++ b/server/openejb-server/src/main/resources/META-INF/openejb-server.xml
@@ -1,36 +1,36 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-    
-    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.
-    
--->
-
-<!-- $Rev$ $Date$ -->
-
-<beans xmlns:s="http://tomee.apache.org/schemas/server" xmlns:c="http://tomee.apache.org/schemas/core"
-    xmlns:l="http://tomee.apache.org/schemas/loader">
-    <s:server id="server" init-method="init">
-        <property name="serviceManager" ref="serviceManager" />
-        <property name="propertiesService" ref="propertiesService" />
-    </s:server>
-    <c:propertiesService id="propertiesService" />
-    <bean id="serviceManager" class="org.apache.openejb.server.ServiceManager" factory-method="getManager" />
-    <!--
-       - FIXME: The only singleton class with lots of static code - really hard to get it XBean-ized properly
-       - 
-    <l:system factory-method="get" init-method="init" />
-    -->
-</beans>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+    
+    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.
+    
+-->
+
+<!-- $Rev$ $Date$ -->
+
+<beans xmlns:s="http://tomee.apache.org/schemas/server" xmlns:c="http://tomee.apache.org/schemas/core"
+    xmlns:l="http://tomee.apache.org/schemas/loader">
+    <s:server id="server" init-method="init">
+        <property name="serviceManager" ref="serviceManager" />
+        <property name="propertiesService" ref="propertiesService" />
+    </s:server>
+    <c:propertiesService id="propertiesService" />
+    <bean id="serviceManager" class="org.apache.openejb.server.ServiceManager" factory-method="getManager" />
+    <!--
+       - FIXME: The only singleton class with lots of static code - really hard to get it XBean-ized properly
+       - 
+    <l:system factory-method="get" init-method="init" />
+    -->
+</beans>

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/server/openejb-server/src/main/resources/META-INF/org.apache.openejb.cli/stop.help
----------------------------------------------------------------------
diff --git a/server/openejb-server/src/main/resources/META-INF/org.apache.openejb.cli/stop.help b/server/openejb-server/src/main/resources/META-INF/org.apache.openejb.cli/stop.help
index 9632aa8..ce00fe0 100644
--- a/server/openejb-server/src/main/resources/META-INF/org.apache.openejb.cli/stop.help
+++ b/server/openejb-server/src/main/resources/META-INF/org.apache.openejb.cli/stop.help
@@ -1,15 +1,15 @@
-Usage: openejb stop [options]
-
-Stops the OpenEJB Server running on host 127.0.0.1 and port 4201
-
-OPTIONS
- -h host    Stops the server at the specified host address
-            Default host is 127.0.0.1
- -p port    Stops the server running on the specified port. 
-            Default port is 4201.
-
-OpenEJB -- EJB Container System and EJB Server.
-For OpenEJB updates and additional information, visit
-http://tomee.apache.org
-
+Usage: openejb stop [options]
+
+Stops the OpenEJB Server running on host 127.0.0.1 and port 4201
+
+OPTIONS
+ -h host    Stops the server at the specified host address
+            Default host is 127.0.0.1
+ -p port    Stops the server running on the specified port. 
+            Default port is 4201.
+
+OpenEJB -- EJB Container System and EJB Server.
+For OpenEJB updates and additional information, visit
+http://tomee.apache.org
+
 Bug Reports to <us...@tomee.apache.org>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/src/main/style/checkstyle.xml
----------------------------------------------------------------------
diff --git a/src/main/style/checkstyle.xml b/src/main/style/checkstyle.xml
index 4cc9921..a1524f1 100644
--- a/src/main/style/checkstyle.xml
+++ b/src/main/style/checkstyle.xml
@@ -1,165 +1,165 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  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.
--->
-<!DOCTYPE module PUBLIC
-    "-//Puppy Crawl//DTD Check Configuration 1.2//EN"
-    "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
-<module name="Checker">
-  <!--
-      If you set the basedir property below, then all reported file
-      names will be relative to the specified directory. See
-      http://checkstyle.sourceforge.net/5.x/config.html#Checker
-
-      <property name="basedir" value="${basedir}"/>
-  -->
-
-  <!-- Checks that property files contain the same keys.         -->
-  <!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
-  <!--<module name="Translation"/>-->
-
-  <!--<module name="FileLength"/>-->
-
-  <!-- Following interprets the header file as regular expressions. -->
-  <!-- <module name="RegexpHeader"/>                                -->
-
-  <module name="SuppressWarningsFilter" />
-
-  <module name="FileTabCharacter">
-    <property name="eachLine" value="true"/>
-  </module>
-
-  <!--<module name="RegexpSingleline">-->
-    <!--&lt;!&ndash; \s matches whitespace character, $ matches end of line. &ndash;&gt;-->
-    <!--<property name="format" value="\s+$"/>-->
-    <!--<property name="message" value="Line has trailing spaces."/>-->
-  <!--</module>-->
-
-    <!-- Checks for Headers                                -->
-    <!-- See http://checkstyle.sf.net/config_header.html   -->
-     <!--<module name="Header">-->
-        <!--<property name="headerFile" value="${checkstyle.header.file}"/>-->
-         <!--<property name="fileExtensions" value="java"/>-->
-     <!--</module>-->
-
-  <module name="TreeWalker">
-    <module name="SuppressWarningsHolder" />
-
-    <property name="cacheFile" value="${checkstyle.cache.file}"/>
-
-    <!-- Checks for Javadoc comments.                     -->
-    <!-- See http://checkstyle.sf.net/config_javadoc.html -->
-    <!--<module name="JavadocMethod"/>-->
-    <!--<module name="JavadocType"/>-->
-    <!--<module name="JavadocVariable"/>-->
-    <!--<module name="JavadocStyle"/>-->
-
-
-    <!-- Checks for Naming Conventions.                  -->
-    <!-- See http://checkstyle.sf.net/config_naming.html -->
-    <!--<module name="ConstantName"/>-->
-    <module name="LocalFinalVariableName"/>
-    <module name="LocalVariableName"/>
-    <module name="MemberName"/>
-    <!--<module name="MethodName"/>-->
-    <module name="PackageName"/>
-    <module name="ParameterName"/>
-    <!--<module name="StaticVariableName"/>-->
-    <!--<module name="TypeName"/>-->
-
-
-    <!-- Checks for imports                              -->
-    <!-- See http://checkstyle.sf.net/config_import.html -->
-    <module name="IllegalImport"/>
-    <!-- defaults to sun.* packages -->
-    <module name="RedundantImport"/>
-    <module name="UnusedImports">
-      <property name="processJavadoc" value="true" />
-    </module>
-
-
-    <!-- Checks for Size Violations.                    -->
-    <!-- See http://checkstyle.sf.net/config_sizes.html -->
-    <!--<module name="LineLength">-->
-      <!--<property name="max" value="120"/>-->
-    <!--</module>-->
-    <!--<module name="MethodLength"/>-->
-    <!--<module name="ParameterNumber"/>-->
-
-
-    <!-- Checks for whitespace                               -->
-    <!-- See http://checkstyle.sf.net/config_whitespace.html -->
-    <!--<module name="EmptyForIteratorPad"/>-->
-    <!--<module name="MethodParamPad"/>-->
-    <!--<module name="NoWhitespaceAfter"/>-->
-    <!--<module name="NoWhitespaceBefore"/>-->
-    <!--<module name="OperatorWrap"/>-->
-    <!--<module name="ParenPad"/>-->
-    <!--<module name="TypecastParenPad"/>-->
-    <!--<module name="WhitespaceAfter"/>-->
-
-    <!-- Modifier Checks                                    -->
-    <!-- See http://checkstyle.sf.net/config_modifiers.html -->
-    <module name="ModifierOrder"/>
-    <module name="RedundantModifier"/>
-
-
-    <!-- Checks for blocks. You know, those {}'s         -->
-    <!-- See http://checkstyle.sf.net/config_blocks.html -->
-    <!--<module name="AvoidNestedBlocks"/>-->
-    <!--<module name="LeftCurly"/>-->
-    <module name="NeedBraces"/>
-    <!--<module name="RightCurly"/>-->
-
-
-    <!-- Checks for common coding problems               -->
-    <!-- See http://checkstyle.sf.net/config_coding.html -->
-    <!--<module name="EmptyStatement"/>-->
-    <!--<module name="EqualsHashCode"/>-->
-    <!--<module name="HiddenField">-->
-      <!--<property name="ignoreSetter" value="true"/>-->
-    <!--</module>-->
-    <module name="IllegalInstantiation"/>
-    <!--<module name="InnerAssignment"/>-->
-    <!--<module name="MagicNumber">-->
-      <!--<property name="ignoreHashCodeMethod" value="true"/>-->
-    <!--</module>-->
-    <!--<module name="MissingSwitchDefault"/>-->
-    <!--<module name="RedundantThrows"/>-->
-    <module name="SimplifyBooleanExpression"/>
-    <module name="SimplifyBooleanReturn"/>
-
-    <!-- Checks for class design                         -->
-    <!-- See http://checkstyle.sf.net/config_design.html -->
-    <module name="FinalClass"/>
-    <!--<module name="HideUtilityClassConstructor"/>-->
-    <!--<module name="InterfaceIsType"/>-->
-    <!--<module name="VisibilityModifier">-->
-      <!--<property name="packageAllowed" value="true"/>-->
-      <!--<property name="protectedAllowed" value="true"/>-->
-    <!--</module>-->
-
-    <!-- Miscellaneous other checks.                   -->
-    <!-- See http://checkstyle.sf.net/config_misc.html -->
-    <module name="ArrayTypeStyle"/>
-    <!--<module name="TodoComment"/>-->
-    <!--<module name="UpperEll"/>-->
-
-  </module>
-
-</module>
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  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.
+-->
+<!DOCTYPE module PUBLIC
+    "-//Puppy Crawl//DTD Check Configuration 1.2//EN"
+    "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
+<module name="Checker">
+  <!--
+      If you set the basedir property below, then all reported file
+      names will be relative to the specified directory. See
+      http://checkstyle.sourceforge.net/5.x/config.html#Checker
+
+      <property name="basedir" value="${basedir}"/>
+  -->
+
+  <!-- Checks that property files contain the same keys.         -->
+  <!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
+  <!--<module name="Translation"/>-->
+
+  <!--<module name="FileLength"/>-->
+
+  <!-- Following interprets the header file as regular expressions. -->
+  <!-- <module name="RegexpHeader"/>                                -->
+
+  <module name="SuppressWarningsFilter" />
+
+  <module name="FileTabCharacter">
+    <property name="eachLine" value="true"/>
+  </module>
+
+  <!--<module name="RegexpSingleline">-->
+    <!--&lt;!&ndash; \s matches whitespace character, $ matches end of line. &ndash;&gt;-->
+    <!--<property name="format" value="\s+$"/>-->
+    <!--<property name="message" value="Line has trailing spaces."/>-->
+  <!--</module>-->
+
+    <!-- Checks for Headers                                -->
+    <!-- See http://checkstyle.sf.net/config_header.html   -->
+     <!--<module name="Header">-->
+        <!--<property name="headerFile" value="${checkstyle.header.file}"/>-->
+         <!--<property name="fileExtensions" value="java"/>-->
+     <!--</module>-->
+
+  <module name="TreeWalker">
+    <module name="SuppressWarningsHolder" />
+
+    <property name="cacheFile" value="${checkstyle.cache.file}"/>
+
+    <!-- Checks for Javadoc comments.                     -->
+    <!-- See http://checkstyle.sf.net/config_javadoc.html -->
+    <!--<module name="JavadocMethod"/>-->
+    <!--<module name="JavadocType"/>-->
+    <!--<module name="JavadocVariable"/>-->
+    <!--<module name="JavadocStyle"/>-->
+
+
+    <!-- Checks for Naming Conventions.                  -->
+    <!-- See http://checkstyle.sf.net/config_naming.html -->
+    <!--<module name="ConstantName"/>-->
+    <module name="LocalFinalVariableName"/>
+    <module name="LocalVariableName"/>
+    <module name="MemberName"/>
+    <!--<module name="MethodName"/>-->
+    <module name="PackageName"/>
+    <module name="ParameterName"/>
+    <!--<module name="StaticVariableName"/>-->
+    <!--<module name="TypeName"/>-->
+
+
+    <!-- Checks for imports                              -->
+    <!-- See http://checkstyle.sf.net/config_import.html -->
+    <module name="IllegalImport"/>
+    <!-- defaults to sun.* packages -->
+    <module name="RedundantImport"/>
+    <module name="UnusedImports">
+      <property name="processJavadoc" value="true" />
+    </module>
+
+
+    <!-- Checks for Size Violations.                    -->
+    <!-- See http://checkstyle.sf.net/config_sizes.html -->
+    <!--<module name="LineLength">-->
+      <!--<property name="max" value="120"/>-->
+    <!--</module>-->
+    <!--<module name="MethodLength"/>-->
+    <!--<module name="ParameterNumber"/>-->
+
+
+    <!-- Checks for whitespace                               -->
+    <!-- See http://checkstyle.sf.net/config_whitespace.html -->
+    <!--<module name="EmptyForIteratorPad"/>-->
+    <!--<module name="MethodParamPad"/>-->
+    <!--<module name="NoWhitespaceAfter"/>-->
+    <!--<module name="NoWhitespaceBefore"/>-->
+    <!--<module name="OperatorWrap"/>-->
+    <!--<module name="ParenPad"/>-->
+    <!--<module name="TypecastParenPad"/>-->
+    <!--<module name="WhitespaceAfter"/>-->
+
+    <!-- Modifier Checks                                    -->
+    <!-- See http://checkstyle.sf.net/config_modifiers.html -->
+    <module name="ModifierOrder"/>
+    <module name="RedundantModifier"/>
+
+
+    <!-- Checks for blocks. You know, those {}'s         -->
+    <!-- See http://checkstyle.sf.net/config_blocks.html -->
+    <!--<module name="AvoidNestedBlocks"/>-->
+    <!--<module name="LeftCurly"/>-->
+    <module name="NeedBraces"/>
+    <!--<module name="RightCurly"/>-->
+
+
+    <!-- Checks for common coding problems               -->
+    <!-- See http://checkstyle.sf.net/config_coding.html -->
+    <!--<module name="EmptyStatement"/>-->
+    <!--<module name="EqualsHashCode"/>-->
+    <!--<module name="HiddenField">-->
+      <!--<property name="ignoreSetter" value="true"/>-->
+    <!--</module>-->
+    <module name="IllegalInstantiation"/>
+    <!--<module name="InnerAssignment"/>-->
+    <!--<module name="MagicNumber">-->
+      <!--<property name="ignoreHashCodeMethod" value="true"/>-->
+    <!--</module>-->
+    <!--<module name="MissingSwitchDefault"/>-->
+    <!--<module name="RedundantThrows"/>-->
+    <module name="SimplifyBooleanExpression"/>
+    <module name="SimplifyBooleanReturn"/>
+
+    <!-- Checks for class design                         -->
+    <!-- See http://checkstyle.sf.net/config_design.html -->
+    <module name="FinalClass"/>
+    <!--<module name="HideUtilityClassConstructor"/>-->
+    <!--<module name="InterfaceIsType"/>-->
+    <!--<module name="VisibilityModifier">-->
+      <!--<property name="packageAllowed" value="true"/>-->
+      <!--<property name="protectedAllowed" value="true"/>-->
+    <!--</module>-->
+
+    <!-- Miscellaneous other checks.                   -->
+    <!-- See http://checkstyle.sf.net/config_misc.html -->
+    <module name="ArrayTypeStyle"/>
+    <!--<module name="TodoComment"/>-->
+    <!--<module name="UpperEll"/>-->
+
+  </module>
+
+</module>

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/tck/tck-common/src/main/java/org/apache/openejb/tck/util/ServerLocal.java
----------------------------------------------------------------------
diff --git a/tck/tck-common/src/main/java/org/apache/openejb/tck/util/ServerLocal.java b/tck/tck-common/src/main/java/org/apache/openejb/tck/util/ServerLocal.java
index 856c429..422b12b 100644
--- a/tck/tck-common/src/main/java/org/apache/openejb/tck/util/ServerLocal.java
+++ b/tck/tck-common/src/main/java/org/apache/openejb/tck/util/ServerLocal.java
@@ -1,50 +1,50 @@
-/*
- * 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.util;
-
-import org.apache.tomee.util.QuickServerXmlParser;
-
-import java.io.File;
-
-public class ServerLocal {
-
-    private ServerLocal() {
-    }
-
-    /**
-     * If the TCK is running against a local server extracted to the target dir
-     * then the server.xml will have the port defined already.
-     *
-     * @param def Default port to use if none is found
-     * @return The determined port, the value of 'server.http.port' or the provided default
-     */
-    public static int getPort(final int def) {
-        final String home = System.getProperty("openejb.home", "empty");
-
-        if (!"empty".equals(home)) {
-            final File serverXml = new File(home, "conf/server.xml");
-
-            if (serverXml.exists() && serverXml.isFile()) {
-                final QuickServerXmlParser parser = QuickServerXmlParser.parse(serverXml);
-
-                return Integer.parseInt(parser.http());
-            }
-        }
-
-        return Integer.getInteger("server.http.port", def);
-    }
-}
+/*
+ * 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.util;
+
+import org.apache.tomee.util.QuickServerXmlParser;
+
+import java.io.File;
+
+public class ServerLocal {
+
+    private ServerLocal() {
+    }
+
+    /**
+     * If the TCK is running against a local server extracted to the target dir
+     * then the server.xml will have the port defined already.
+     *
+     * @param def Default port to use if none is found
+     * @return The determined port, the value of 'server.http.port' or the provided default
+     */
+    public static int getPort(final int def) {
+        final String home = System.getProperty("openejb.home", "empty");
+
+        if (!"empty".equals(home)) {
+            final File serverXml = new File(home, "conf/server.xml");
+
+            if (serverXml.exists() && serverXml.isFile()) {
+                final QuickServerXmlParser parser = QuickServerXmlParser.parse(serverXml);
+
+                return Integer.parseInt(parser.http());
+            }
+        }
+
+        return Integer.getInteger("server.http.port", def);
+    }
+}

http://git-wip-us.apache.org/repos/asf/tomee/blob/bd7dbd0f/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%"