[jboss-svn-commits] JBoss Common SVN: r4714 - in arquillian/trunk/containers/tomcat-embedded-6: src/main/java/org and 10 other directories.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Sat Jul 10 16:57:50 EDT 2010


Author: dan.j.allen
Date: 2010-07-10 16:57:49 -0400 (Sat, 10 Jul 2010)
New Revision: 4714

Added:
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/catalina/
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/catalina/startup/
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/catalina/startup/ContextConfig.java
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/naming/
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/naming/resources/
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/naming/resources/DirContextURLConnection.java
   arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/MavenArtifactResolver.java
   arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TestBean.java
   arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TestServlet.java
   arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/client-web.xml
   arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/in-container-context.xml
   arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/in-container-web.xml
Removed:
   arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/test/war/
   arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/in-container-web.xml
   arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/web.xml
Modified:
   arquillian/trunk/containers/tomcat-embedded-6/pom.xml
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatConfiguration.java
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatContainer.java
   arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedDeploymentAppender.java
   arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedClientTestCase.java
   arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedInContainerTestCase.java
   arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/arquillian.xml
Log:
ARQ-189 reorganize test files
add CDI injection with test
add patched Tomcat files to:
load META-INF/context,
unpack WAR correctly,
delete unpacked WAR,
locate WEB-INF/beans.xml


Modified: arquillian/trunk/containers/tomcat-embedded-6/pom.xml
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/pom.xml	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/pom.xml	2010-07-10 20:57:49 UTC (rev 4714)
@@ -94,6 +94,28 @@
          <scope>test</scope>
       </dependency>
 
+      <!-- Weld servlet required for testing CDI injections -->
+      <dependency>
+         <groupId>org.jboss.weld.servlet</groupId>
+         <artifactId>weld-servlet</artifactId>
+         <version>1.0.1-Final</version>
+         <scope>test</scope>
+      </dependency>
+
+      <dependency>
+         <groupId>org.glassfish.web</groupId>
+         <artifactId>el-impl</artifactId>
+         <version>2.2</version>
+         <scope>test</scope>
+      </dependency>
+
+      <dependency>
+         <groupId>javax.servlet.jsp</groupId>
+         <artifactId>jsp-api</artifactId>
+         <version>2.2</version>
+         <scope>test</scope>
+      </dependency>
+
    </dependencies>
 
 </project>

Added: arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/catalina/startup/ContextConfig.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/catalina/startup/ContextConfig.java	                        (rev 0)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/catalina/startup/ContextConfig.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -0,0 +1,1451 @@
+/*
+ * 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.catalina.startup;
+
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.servlet.ServletContext;
+
+import org.apache.catalina.Authenticator;
+import org.apache.catalina.Container;
+import org.apache.catalina.Context;
+import org.apache.catalina.Engine;
+import org.apache.catalina.Globals;
+import org.apache.catalina.Host;
+import org.apache.catalina.Lifecycle;
+import org.apache.catalina.LifecycleEvent;
+import org.apache.catalina.LifecycleListener;
+import org.apache.catalina.Pipeline;
+import org.apache.catalina.Valve;
+import org.apache.catalina.Wrapper;
+import org.apache.catalina.core.ContainerBase;
+import org.apache.catalina.core.StandardContext;
+import org.apache.catalina.core.StandardEngine;
+import org.apache.catalina.core.StandardHost;
+import org.apache.catalina.deploy.ErrorPage;
+import org.apache.catalina.deploy.FilterDef;
+import org.apache.catalina.deploy.FilterMap;
+import org.apache.catalina.deploy.LoginConfig;
+import org.apache.catalina.deploy.SecurityConstraint;
+import org.apache.catalina.util.StringManager;
+import org.apache.tomcat.util.digester.Digester;
+import org.apache.tomcat.util.digester.RuleSet;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXParseException;
+
+/**
+ * Startup event listener for a <b>Context</b> that configures the properties
+ * of that Context, and the associated defined servlets.
+ * <p/>
+ * This file has been copied into the Tomcat Embedded container integration
+ * because by default the META-INF/context.xml is not loaded from the
+ * application and the directory into which the WAR is unpacked has a truncated
+ * name (est instead of test) and is not removed during undeployment. All
+ * of these problems are corrected in this patched version.
+ *
+ * @author Craig R. McClanahan
+ * @author Jean-Francois Arcand
+ * @version $Revision: 892815 $ $Date: 2009-12-21 14:27:57 +0100 (Mon, 21 Dec 2009) $
+ */
+
+public class ContextConfig
+    implements LifecycleListener {
+
+    protected static org.apache.juli.logging.Log log=
+        org.apache.juli.logging.LogFactory.getLog( ContextConfig.class );
+
+    // ----------------------------------------------------- Instance Variables
+
+
+    /**
+     * Custom mappings of login methods to authenticators
+     */
+    protected Map customAuthenticators;
+
+
+    /**
+     * The set of Authenticators that we know how to configure.  The key is
+     * the name of the implemented authentication method, and the value is
+     * the fully qualified Java class name of the corresponding Valve.
+     */
+    protected static Properties authenticators = null;
+
+
+    /**
+     * The Context we are associated with.
+     */
+    protected Context context = null;
+
+
+    /**
+     * The default web application's context file location.
+     */
+    protected String defaultContextXml = null;
+    
+    
+    /**
+     * The default web application's deployment descriptor location.
+     */
+    protected String defaultWebXml = null;
+    
+    
+    /**
+     * Track any fatal errors during startup configuration processing.
+     */
+    protected boolean ok = false;
+
+
+    /**
+     * Any parse error which occurred while parsing XML descriptors.
+     */
+    protected SAXParseException parseException = null;
+
+    
+    /**
+     * Original docBase.
+     */
+    protected String originalDocBase = null;
+    
+
+    /**
+     * The string resources for this package.
+     */
+    protected static final StringManager sm =
+        StringManager.getManager(Constants.Package);
+
+
+    /**
+     * The <code>Digester</code> we will use to process web application
+     * context files.
+     */
+    protected static Digester contextDigester = null;
+
+    /**
+     * The <code>Digester</code> we will use to process web application
+     * deployment descriptor files.
+     */
+    protected static Digester webDigester = null;
+    
+    
+    /**
+     * The <code>Rule</code> used to parse the web.xml
+     */
+    protected static WebRuleSet webRuleSet = new WebRuleSet();
+
+    /**
+     * Attribute value used to turn on/off XML validation
+     */
+     protected static boolean xmlValidation = false;
+
+
+    /**
+     * Attribute value used to turn on/off XML namespace awarenes.
+     */
+    protected static boolean xmlNamespaceAware = false;
+
+    
+    /**
+     * Deployment count.
+     */
+    protected static long deploymentCount = 0L;
+    
+    
+    protected static final LoginConfig DUMMY_LOGIN_CONFIG =
+                                new LoginConfig("NONE", null, null, null);
+
+
+    // ------------------------------------------------------------- Properties
+
+
+    /**
+     * Return the location of the default deployment descriptor
+     */
+    public String getDefaultWebXml() {
+        if( defaultWebXml == null ) {
+            defaultWebXml=Constants.DefaultWebXml;
+        }
+
+        return (this.defaultWebXml);
+
+    }
+
+
+    /**
+     * Set the location of the default deployment descriptor
+     *
+     * @param path Absolute/relative path to the default web.xml
+     */
+    public void setDefaultWebXml(String path) {
+
+        this.defaultWebXml = path;
+
+    }
+
+
+    /**
+     * Return the location of the default context file
+     */
+    public String getDefaultContextXml() {
+        if( defaultContextXml == null ) {
+            defaultContextXml=Constants.DefaultContextXml;
+        }
+
+        return (this.defaultContextXml);
+
+    }
+
+
+    /**
+     * Set the location of the default context file
+     *
+     * @param path Absolute/relative path to the default context.xml
+     */
+    public void setDefaultContextXml(String path) {
+
+        this.defaultContextXml = path;
+
+    }
+
+
+    /**
+     * Sets custom mappings of login methods to authenticators.
+     *
+     * @param customAuthenticators Custom mappings of login methods to
+     * authenticators
+     */
+    public void setCustomAuthenticators(Map customAuthenticators) {
+        this.customAuthenticators = customAuthenticators;
+    }
+
+
+    // --------------------------------------------------------- Public Methods
+
+
+    /**
+     * Process events for an associated Context.
+     *
+     * @param event The lifecycle event that has occurred
+     */
+    public void lifecycleEvent(LifecycleEvent event) {
+
+        // Identify the context we are associated with
+        try {
+            context = (Context) event.getLifecycle();
+        } catch (ClassCastException e) {
+            log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e);
+            return;
+        }
+
+        // Process the event that has occurred
+        if (event.getType().equals(Lifecycle.START_EVENT)) {
+            start();
+        } else if (event.getType().equals(StandardContext.BEFORE_START_EVENT)) {
+            beforeStart();
+        } else if (event.getType().equals(StandardContext.AFTER_START_EVENT)) {
+            // Restore docBase for management tools
+            if (originalDocBase != null) {
+                String docBase = context.getDocBase();
+                context.setDocBase(originalDocBase);
+                originalDocBase = docBase;
+            }
+        } else if (event.getType().equals(Lifecycle.STOP_EVENT)) {
+            if (originalDocBase != null) {
+                String docBase = context.getDocBase();
+                context.setDocBase(originalDocBase);
+                originalDocBase = docBase;
+            }
+            stop();
+        } else if (event.getType().equals(Lifecycle.INIT_EVENT)) {
+            init();
+        } else if (event.getType().equals(Lifecycle.DESTROY_EVENT)) {
+            destroy();
+        }
+
+    }
+
+
+    // -------------------------------------------------------- protected Methods
+
+
+    /**
+     * Process the application classes annotations, if it exists.
+     */
+    protected void applicationAnnotationsConfig() {
+        
+        long t1=System.currentTimeMillis();
+        
+        WebAnnotationSet.loadApplicationAnnotations(context);
+        
+        long t2=System.currentTimeMillis();
+        if (context instanceof StandardContext) {
+            ((StandardContext) context).setStartupTime(t2-t1+
+                    ((StandardContext) context).getStartupTime());
+        }
+    }
+
+    /**
+     * Process the META-INF/context.xml in the web application.
+     */
+    protected void applicationContextConfig() {
+       ServletContext servletContext = context.getServletContext();
+       InputStream stream = servletContext.getResourceAsStream("/" + Constants.ApplicationContextXml);
+       if (stream == null)
+       {
+          return;
+       }
+       synchronized(contextDigester)
+       {
+          URL url = null;
+          try {
+            url = servletContext.getResource("/" + Constants.ApplicationContextXml);
+          }
+          catch (MalformedURLException e)
+          {
+             throw new AssertionError("/" + Constants.ApplicationContextXml + " should not be considered a malformed URL");
+          }
+          InputSource is = new InputSource(url.toExternalForm());
+          is.setByteStream(stream);
+          contextDigester.push(context);
+          try
+          {
+            contextDigester.parse(is);
+          }
+          catch (Exception e)
+          {
+             ok = false;
+             log.error(sm.getString("contextConfig.contextParse", context.getName()), e);
+          }
+          finally {
+             contextDigester.reset();
+             try {
+                 if (stream != null) {
+                     stream.close();
+                 }
+             } catch (IOException e) {
+                log.error(sm.getString("contextConfig.contextClose"), e);
+             }
+          }
+       }
+    }
+
+    /**
+     * Process the application configuration file, if it exists.
+     */
+    protected void applicationWebConfig() {
+
+        String altDDName = null;
+
+        // Open the application web.xml file, if it exists
+        InputStream stream = null;
+        ServletContext servletContext = context.getServletContext();
+        if (servletContext != null) {
+            altDDName = (String)servletContext.getAttribute(
+                                                        Globals.ALT_DD_ATTR);
+            if (altDDName != null) {
+                try {
+                    stream = new FileInputStream(altDDName);
+                } catch (FileNotFoundException e) {
+                    log.error(sm.getString("contextConfig.altDDNotFound",
+                                           altDDName));
+                }
+            }
+            else {
+                stream = servletContext.getResourceAsStream
+                    (Constants.ApplicationWebXml);
+            }
+        }
+        if (stream == null) {
+            if (log.isDebugEnabled()) {
+                log.debug(sm.getString("contextConfig.applicationMissing") + " " + context);
+            }
+            return;
+        }
+        
+        long t1=System.currentTimeMillis();
+
+        URL url=null;
+        // Process the application web.xml file
+        synchronized (webDigester) {
+            try {
+                if (altDDName != null) {
+                    url = new File(altDDName).toURL();
+                } else {
+                    url = servletContext.getResource(
+                                                Constants.ApplicationWebXml);
+                }
+                if( url!=null ) {
+                    InputSource is = new InputSource(url.toExternalForm());
+                    is.setByteStream(stream);
+                    if (context instanceof StandardContext) {
+                        ((StandardContext) context).setReplaceWelcomeFiles(true);
+                    }
+                    webDigester.push(context);
+                    webDigester.setErrorHandler(new ContextErrorHandler());
+
+                    if(log.isDebugEnabled()) {
+                        log.debug("Parsing application web.xml file at " + url.toExternalForm());
+                    }
+
+                    webDigester.parse(is);
+
+                    if (parseException != null) {
+                        ok = false;
+                    }
+                } else {
+                    log.info("No web.xml, using defaults " + context );
+                }
+            } catch (SAXParseException e) {
+                log.error(sm.getString("contextConfig.applicationParse", url.toExternalForm()), e);
+                log.error(sm.getString("contextConfig.applicationPosition",
+                                 "" + e.getLineNumber(),
+                                 "" + e.getColumnNumber()));
+                ok = false;
+            } catch (Exception e) {
+                log.error(sm.getString("contextConfig.applicationParse", url.toExternalForm()), e);
+                ok = false;
+            } finally {
+                webDigester.reset();
+                parseException = null;
+                try {
+                    if (stream != null) {
+                        stream.close();
+                    }
+                } catch (IOException e) {
+                    log.error(sm.getString("contextConfig.applicationClose"), e);
+                }
+            }
+        }
+        webRuleSet.recycle();
+
+        long t2=System.currentTimeMillis();
+        if (context instanceof StandardContext) {
+            ((StandardContext) context).setStartupTime(t2-t1);
+        }
+    }
+
+
+    /**
+     * Set up an Authenticator automatically if required, and one has not
+     * already been configured.
+     */
+    protected synchronized void authenticatorConfig() {
+
+        // Does this Context require an Authenticator?
+        SecurityConstraint constraints[] = context.findConstraints();
+        if ((constraints == null) || (constraints.length == 0))
+            return;
+        LoginConfig loginConfig = context.getLoginConfig();
+        if (loginConfig == null) {
+            loginConfig = DUMMY_LOGIN_CONFIG;
+            context.setLoginConfig(loginConfig);
+        }
+
+        // Has an authenticator been configured already?
+        if (context instanceof Authenticator)
+            return;
+        if (context instanceof ContainerBase) {
+            Pipeline pipeline = ((ContainerBase) context).getPipeline();
+            if (pipeline != null) {
+                Valve basic = pipeline.getBasic();
+                if ((basic != null) && (basic instanceof Authenticator))
+                    return;
+                Valve valves[] = pipeline.getValves();
+                for (int i = 0; i < valves.length; i++) {
+                    if (valves[i] instanceof Authenticator)
+                        return;
+                }
+            }
+        } else {
+            return;     // Cannot install a Valve even if it would be needed
+        }
+
+        // Has a Realm been configured for us to authenticate against?
+        if (context.getRealm() == null) {
+            log.error(sm.getString("contextConfig.missingRealm"));
+            ok = false;
+            return;
+        }
+
+        /*
+         * First check to see if there is a custom mapping for the login
+         * method. If so, use it. Otherwise, check if there is a mapping in
+         * org/apache/catalina/startup/Authenticators.properties.
+         */
+        Valve authenticator = null;
+        if (customAuthenticators != null) {
+            authenticator = (Valve)
+                customAuthenticators.get(loginConfig.getAuthMethod());
+        }
+        if (authenticator == null) {
+            // Load our mapping properties if necessary
+            if (authenticators == null) {
+                try {
+                    InputStream is=this.getClass().getClassLoader().getResourceAsStream("org/apache/catalina/startup/Authenticators.properties");
+                    if( is!=null ) {
+                        authenticators = new Properties();
+                        authenticators.load(is);
+                    } else {
+                        log.error(sm.getString(
+                                "contextConfig.authenticatorResources"));
+                        ok=false;
+                        return;
+                    }
+                } catch (IOException e) {
+                    log.error(sm.getString(
+                                "contextConfig.authenticatorResources"), e);
+                    ok = false;
+                    return;
+                }
+            }
+
+            // Identify the class name of the Valve we should configure
+            String authenticatorName = null;
+            authenticatorName =
+                    authenticators.getProperty(loginConfig.getAuthMethod());
+            if (authenticatorName == null) {
+                log.error(sm.getString("contextConfig.authenticatorMissing",
+                                 loginConfig.getAuthMethod()));
+                ok = false;
+                return;
+            }
+
+            // Instantiate and install an Authenticator of the requested class
+            try {
+                Class authenticatorClass = Class.forName(authenticatorName);
+                authenticator = (Valve) authenticatorClass.newInstance();
+            } catch (Throwable t) {
+                log.error(sm.getString(
+                                    "contextConfig.authenticatorInstantiate",
+                                    authenticatorName),
+                          t);
+                ok = false;
+            }
+        }
+
+        if (authenticator != null && context instanceof ContainerBase) {
+            Pipeline pipeline = ((ContainerBase) context).getPipeline();
+            if (pipeline != null) {
+                ((ContainerBase) context).addValve(authenticator);
+                if (log.isDebugEnabled()) {
+                    log.debug(sm.getString(
+                                    "contextConfig.authenticatorConfigured",
+                                    loginConfig.getAuthMethod()));
+                }
+            }
+        }
+
+    }
+
+
+    /**
+     * Create (if necessary) and return a Digester configured to process the
+     * web application deployment descriptor (web.xml).
+     */
+    protected static Digester createWebDigester() {
+        Digester webDigester =
+            createWebXmlDigester(xmlNamespaceAware, xmlValidation);
+        return webDigester;
+    }
+
+
+    /**
+     * Create (if necessary) and return a Digester configured to process the
+     * web application deployment descriptor (web.xml).
+     */
+    public static Digester createWebXmlDigester(boolean namespaceAware,
+                                                boolean validation) {
+        
+        Digester webDigester =  DigesterFactory.newDigester(xmlValidation,
+                                                            xmlNamespaceAware,
+                                                            webRuleSet);
+        return webDigester;
+    }
+
+    
+    /**
+     * Create (if necessary) and return a Digester configured to process the
+     * context configuration descriptor for an application.
+     */
+    protected Digester createContextDigester() {
+        Digester digester = new Digester();
+        digester.setValidating(false);
+        RuleSet contextRuleSet = new ContextRuleSet("", false);
+        digester.addRuleSet(contextRuleSet);
+        RuleSet namingRuleSet = new NamingRuleSet("Context/");
+        digester.addRuleSet(namingRuleSet);
+        return digester;
+    }
+
+    protected Digester createApplicationContextDigester() {
+        Digester digester = new Digester();
+        digester.setValidating(false);
+        RuleSet namingRuleSet = new NamingRuleSet("Context/");
+        digester.addRuleSet(namingRuleSet);
+        return digester;
+    }
+
+    protected String getBaseDir() {
+        Container engineC=context.getParent().getParent();
+        if( engineC instanceof StandardEngine ) {
+            return ((StandardEngine)engineC).getBaseDir();
+        }
+        return System.getProperty("catalina.base");
+    }
+
+    /**
+     * Process the default configuration file, if it exists.
+     * The default config must be read with the container loader - so
+     * container servlets can be loaded
+     */
+    protected void defaultWebConfig() {
+        long t1=System.currentTimeMillis();
+
+        // Open the default web.xml file, if it exists
+        if( defaultWebXml==null && context instanceof StandardContext ) {
+            defaultWebXml=((StandardContext)context).getDefaultWebXml();
+        }
+        // set the default if we don't have any overrides
+        if( defaultWebXml==null ) getDefaultWebXml();
+
+        File file = new File(this.defaultWebXml);
+        if (!file.isAbsolute()) {
+            file = new File(getBaseDir(),
+                            this.defaultWebXml);
+        }
+
+        InputStream stream = null;
+        InputSource source = null;
+
+        try {
+            if ( ! file.exists() ) {
+                // Use getResource and getResourceAsStream
+                stream = getClass().getClassLoader()
+                    .getResourceAsStream(defaultWebXml);
+                if( stream != null ) {
+                    source = new InputSource
+                            (getClass().getClassLoader()
+                            .getResource(defaultWebXml).toString());
+                } 
+                if( stream== null ) { 
+                    // maybe embedded
+                    stream = getClass().getClassLoader()
+                        .getResourceAsStream("web-embed.xml");
+                    if( stream != null ) {
+                        source = new InputSource
+                        (getClass().getClassLoader()
+                                .getResource("web-embed.xml").toString());
+                    }                                         
+                }
+                
+                if( stream== null ) {
+                    log.info("No default web.xml");
+                }
+            } else {
+                source =
+                    new InputSource("file://" + file.getAbsolutePath());
+                stream = new FileInputStream(file);
+                context.addWatchedResource(file.getAbsolutePath());
+            }
+        } catch (Exception e) {
+            log.error(sm.getString("contextConfig.defaultMissing") 
+                      + " " + defaultWebXml + " " + file , e);
+        }
+
+        if (stream != null) {
+            processDefaultWebConfig(webDigester, stream, source);
+            webRuleSet.recycle();
+        }
+
+        long t2=System.currentTimeMillis();
+        if( (t2-t1) > 200 )
+            log.debug("Processed default web.xml " + file + " "  + ( t2-t1));
+
+        stream = null;
+        source = null;
+
+        String resourceName = getHostConfigPath(Constants.HostWebXml);
+        file = new File(getConfigBase(), resourceName);
+        
+        try {
+            if ( ! file.exists() ) {
+                // Use getResource and getResourceAsStream
+                stream = getClass().getClassLoader()
+                    .getResourceAsStream(resourceName);
+                if( stream != null ) {
+                    source = new InputSource
+                            (getClass().getClassLoader()
+                            .getResource(resourceName).toString());
+                }
+            } else {
+                source =
+                    new InputSource("file://" + file.getAbsolutePath());
+                stream = new FileInputStream(file);
+            }
+        } catch (Exception e) {
+            log.error(sm.getString("contextConfig.defaultMissing") 
+                      + " " + resourceName + " " + file , e);
+        }
+
+        if (stream != null) {
+            processDefaultWebConfig(webDigester, stream, source);
+            webRuleSet.recycle();
+        }
+
+    }
+
+
+    /**
+     * Process a default web.xml.
+     */
+    protected void processDefaultWebConfig(Digester digester, InputStream stream, 
+            InputSource source) {
+
+        if (log.isDebugEnabled())
+            log.debug("Processing context [" + context.getName() 
+                    + "] web configuration resource " + source.getSystemId());
+
+        // Process the default web.xml file
+        synchronized (digester) {
+            try {
+                source.setByteStream(stream);
+                
+                if (context instanceof StandardContext)
+                    ((StandardContext) context).setReplaceWelcomeFiles(true);
+                digester.setClassLoader(this.getClass().getClassLoader());
+                digester.setUseContextClassLoader(false);
+                digester.push(context);
+                digester.setErrorHandler(new ContextErrorHandler());
+                digester.parse(source);
+                if (parseException != null) {
+                    ok = false;
+                }
+            } catch (SAXParseException e) {
+                log.error(sm.getString("contextConfig.defaultParse"), e);
+                log.error(sm.getString("contextConfig.defaultPosition",
+                                 "" + e.getLineNumber(),
+                                 "" + e.getColumnNumber()));
+                ok = false;
+            } catch (Exception e) {
+                log.error(sm.getString("contextConfig.defaultParse"), e);
+                ok = false;
+            } finally {
+                digester.reset();
+                parseException = null;
+                try {
+                    if (stream != null) {
+                        stream.close();
+                    }
+                } catch (IOException e) {
+                    log.error(sm.getString("contextConfig.defaultClose"), e);
+                }
+            }
+        }
+    }
+
+
+    /**
+     * Process the default configuration file, if it exists.
+     */
+    protected void contextConfig() {
+        
+        // Open the default web.xml file, if it exists
+        if( defaultContextXml==null && context instanceof StandardContext ) {
+            defaultContextXml = ((StandardContext)context).getDefaultContextXml();
+        }
+        // set the default if we don't have any overrides
+        if( defaultContextXml==null ) getDefaultContextXml();
+
+        if (!context.getOverride()) {
+            processContextConfig(new File(getBaseDir()), defaultContextXml);
+            processContextConfig(getConfigBase(), getHostConfigPath(Constants.HostContextXml));
+        }
+        if (context.getConfigFile() != null)
+            processContextConfig(new File(context.getConfigFile()), null);
+        
+    }
+
+    
+    /**
+     * Process a context.xml.
+     */
+    protected void processContextConfig(File baseDir, String resourceName) {
+        
+        if (log.isDebugEnabled())
+            log.debug("Processing context [" + context.getName() 
+                    + "] configuration file " + baseDir + " " + resourceName);
+
+        InputSource source = null;
+        InputStream stream = null;
+
+        File file = baseDir;
+        if (resourceName != null) {
+            file = new File(baseDir, resourceName);
+        }
+        
+        try {
+            if ( !file.exists() ) {
+                if (resourceName != null) {
+                    // Use getResource and getResourceAsStream
+                    stream = getClass().getClassLoader()
+                        .getResourceAsStream(resourceName);
+                    if( stream != null ) {
+                        source = new InputSource
+                            (getClass().getClassLoader()
+                            .getResource(resourceName).toString());
+                    }
+                }
+            } else {
+                source =
+                    new InputSource("file://" + file.getAbsolutePath());
+                stream = new FileInputStream(file);
+                // Add as watched resource so that cascade reload occurs if a default
+                // config file is modified/added/removed
+                context.addWatchedResource(file.getAbsolutePath());
+            }
+        } catch (Exception e) {
+            log.error(sm.getString("contextConfig.contextMissing",  
+                      resourceName + " " + file) , e);
+        }
+        
+        if (source == null)
+            return;
+        synchronized (contextDigester) {
+            try {
+                source.setByteStream(stream);
+                contextDigester.setClassLoader(this.getClass().getClassLoader());
+                contextDigester.setUseContextClassLoader(false);
+                contextDigester.push(context.getParent());
+                contextDigester.push(context);
+                contextDigester.setErrorHandler(new ContextErrorHandler());
+                contextDigester.parse(source);
+                if (parseException != null) {
+                    ok = false;
+                }
+                if (log.isDebugEnabled())
+                    log.debug("Successfully processed context [" + context.getName() 
+                            + "] configuration file " + baseDir + " " + resourceName);
+            } catch (SAXParseException e) {
+                log.error(sm.getString("contextConfig.contextParse",
+                        context.getName()), e);
+                log.error(sm.getString("contextConfig.defaultPosition",
+                                 "" + e.getLineNumber(),
+                                 "" + e.getColumnNumber()));
+                ok = false;
+            } catch (Exception e) {
+                log.error(sm.getString("contextConfig.contextParse",
+                        context.getName()), e);
+                ok = false;
+            } finally {
+                contextDigester.reset();
+                parseException = null;
+                try {
+                    if (stream != null) {
+                        stream.close();
+                    }
+                } catch (IOException e) {
+                    log.error(sm.getString("contextConfig.contextClose"), e);
+                }
+            }
+        }
+    }
+
+    
+    /**
+     * Adjust docBase.
+     */
+    protected void fixDocBase()
+        throws IOException {
+        
+        Host host = (Host) context.getParent();
+        String appBase = host.getAppBase();
+
+        boolean unpackWARs = true;
+        if (host instanceof StandardHost) {
+            unpackWARs = ((StandardHost) host).isUnpackWARs() 
+                && ((StandardContext) context).getUnpackWAR();
+        }
+
+        File canonicalAppBase = new File(appBase);
+        if (canonicalAppBase.isAbsolute()) {
+            canonicalAppBase = canonicalAppBase.getCanonicalFile();
+        } else {
+            canonicalAppBase = 
+                new File(System.getProperty("catalina.base"), appBase)
+                .getCanonicalFile();
+        }
+
+        String docBase = context.getDocBase();
+        if (docBase == null) {
+            // Trying to guess the docBase according to the path
+            String path = context.getPath();
+            if (path == null) {
+                return;
+            }
+            if (path.equals("")) {
+                docBase = "ROOT";
+            } else {
+                if (path.startsWith("/")) {
+                    docBase = path.substring(1).replace('/', '#');
+                } else {
+                    docBase = path.replace('/', '#');
+                }
+            }
+        }
+
+        File file = new File(docBase);
+        if (!file.isAbsolute()) {
+            docBase = (new File(canonicalAppBase, docBase)).getPath();
+        } else {
+            docBase = file.getCanonicalPath();
+        }
+        file = new File(docBase);
+        String origDocBase = docBase;
+        
+        String pathName = context.getPath();
+        if (pathName.equals("")) {
+            pathName = "ROOT";
+        } else {
+            if (pathName.startsWith("/")) {
+               pathName = pathName.substring(1);
+            }
+            pathName = pathName.replace('/', '#');
+        }
+        if (docBase.toLowerCase().endsWith(".war") && !file.isDirectory() && unpackWARs) {
+            URL war = new URL("jar:" + (new File(docBase)).toURI().toURL() + "!/");
+            docBase = ExpandWar.expand(host, war, pathName);
+            file = new File(docBase);
+            docBase = file.getCanonicalPath();
+            if (context instanceof StandardContext) {
+                ((StandardContext) context).setOriginalDocBase(origDocBase);
+            }
+        } else if (docBase.toLowerCase().endsWith(".war") &&
+                !file.isDirectory() && !unpackWARs) {
+            URL war =
+                new URL("jar:" + (new File (docBase)).toURI().toURL() + "!/");
+            ExpandWar.validate(host, war, pathName);
+        } else {
+            File docDir = new File(docBase);
+            if (!docDir.exists()) {
+                File warFile = new File(docBase + ".war");
+                if (warFile.exists()) {
+                    URL war =
+                        new URL("jar:" + warFile.toURI().toURL() + "!/");
+                    if (unpackWARs) {
+                        docBase = ExpandWar.expand(host, war, pathName);
+                        file = new File(docBase);
+                        docBase = file.getCanonicalPath();
+                    } else {
+                        docBase = warFile.getCanonicalPath();
+                        ExpandWar.validate(host, war, pathName);
+                    }
+                }
+                if (context instanceof StandardContext) {
+                    ((StandardContext) context).setOriginalDocBase(origDocBase);
+                }
+            }
+        }
+
+        if (docBase.startsWith(canonicalAppBase.getPath() + File.separatorChar)) {
+            docBase = docBase.substring(canonicalAppBase.getPath().length());
+            docBase = docBase.replace(File.separatorChar, '/');
+            if (docBase.startsWith("/")) {
+                docBase = docBase.substring(1);
+            }
+        } else {
+            docBase = docBase.replace(File.separatorChar, '/');
+        }
+
+        context.setDocBase(docBase);
+        originalDocBase = docBase;
+    }
+    
+    
+    protected void antiLocking()
+        throws IOException {
+
+        if ((context instanceof StandardContext) 
+            && ((StandardContext) context).getAntiResourceLocking()) {
+            
+            Host host = (Host) context.getParent();
+            String appBase = host.getAppBase();
+            String docBase = context.getDocBase();
+            if (docBase == null)
+                return;
+            if (originalDocBase == null) {
+                originalDocBase = docBase;
+            } else {
+                docBase = originalDocBase;
+            }
+            File docBaseFile = new File(docBase);
+            if (!docBaseFile.isAbsolute()) {
+                File file = new File(appBase);
+                if (!file.isAbsolute()) {
+                    file = new File(System.getProperty("catalina.base"), appBase);
+                }
+                docBaseFile = new File(file, docBase);
+            }
+            
+            String path = context.getPath();
+            if (path == null) {
+                return;
+            }
+            if (path.equals("")) {
+                docBase = "ROOT";
+            } else {
+                if (path.startsWith("/")) {
+                    docBase = path.substring(1);
+                } else {
+                    docBase = path;
+                }
+            }
+
+            File file = null;
+            if (docBase.toLowerCase().endsWith(".war")) {
+                file = new File(System.getProperty("java.io.tmpdir"),
+                        deploymentCount++ + "-" + docBase + ".war");
+            } else {
+                file = new File(System.getProperty("java.io.tmpdir"), 
+                        deploymentCount++ + "-" + docBase);
+            }
+            
+            if (log.isDebugEnabled())
+                log.debug("Anti locking context[" + context.getPath() 
+                        + "] setting docBase to " + file);
+            
+            // Cleanup just in case an old deployment is lying around
+            ExpandWar.delete(file);
+            if (ExpandWar.copy(docBaseFile, file)) {
+                context.setDocBase(file.getAbsolutePath());
+            }
+            
+        }
+        
+    }
+    
+
+    /**
+     * Process a "init" event for this Context.
+     */
+    protected void init() {
+        // Called from StandardContext.init()
+
+        if (webDigester == null){
+            webDigester = createWebDigester();
+            webDigester.getParser();
+        }
+        
+        if (contextDigester == null){
+            contextDigester = createContextDigester();
+            contextDigester.getParser();
+        }
+
+        if (log.isDebugEnabled())
+            log.debug(sm.getString("contextConfig.init"));
+        context.setConfigured(false);
+        ok = true;
+        
+        contextConfig();
+        
+        try {
+            fixDocBase();
+        } catch (IOException e) {
+            log.error(sm.getString(
+                    "contextConfig.fixDocBase", context.getPath()), e);
+        }
+        
+    }
+    
+    
+    /**
+     * Process a "before start" event for this Context.
+     */
+    protected synchronized void beforeStart() {
+        
+        try {
+            antiLocking();
+        } catch (IOException e) {
+            log.error(sm.getString("contextConfig.antiLocking"), e);
+        }
+        
+    }
+    
+    
+    /**
+     * Process a "start" event for this Context.
+     */
+    protected synchronized void start() {
+        // Called from StandardContext.start()
+
+        if (log.isDebugEnabled())
+            log.debug(sm.getString("contextConfig.start"));
+
+        // Set properties based on DefaultContext
+        Container container = context.getParent();
+        if( !context.getOverride() ) {
+            if( container instanceof Host ) {
+                // Reset the value only if the attribute wasn't
+                // set on the context.
+                xmlValidation = context.getXmlValidation();
+                if (!xmlValidation) {
+                    xmlValidation = ((Host)container).getXmlValidation();
+                }
+                
+                xmlNamespaceAware = context.getXmlNamespaceAware();
+                if (!xmlNamespaceAware){
+                    xmlNamespaceAware 
+                                = ((Host)container).getXmlNamespaceAware();
+                }
+
+                container = container.getParent();
+            }
+        }
+
+        applicationContextConfig();
+        // Process the default and application web.xml files
+        defaultWebConfig();
+        applicationWebConfig();
+        if (!context.getIgnoreAnnotations()) {
+            applicationAnnotationsConfig();
+        }
+        if (ok) {
+            validateSecurityRoles();
+        }
+
+        // Configure an authenticator if we need one
+        if (ok)
+            authenticatorConfig();
+
+        // Dump the contents of this pipeline if requested
+        if ((log.isDebugEnabled()) && (context instanceof ContainerBase)) {
+            log.debug("Pipeline Configuration:");
+            Pipeline pipeline = ((ContainerBase) context).getPipeline();
+            Valve valves[] = null;
+            if (pipeline != null)
+                valves = pipeline.getValves();
+            if (valves != null) {
+                for (int i = 0; i < valves.length; i++) {
+                    log.debug("  " + valves[i].getInfo());
+                }
+            }
+            log.debug("======================");
+        }
+
+        // Make our application available if no problems were encountered
+        if (ok)
+            context.setConfigured(true);
+        else {
+            log.error(sm.getString("contextConfig.unavailable"));
+            context.setConfigured(false);
+        }
+
+    }
+
+
+    /**
+     * Process a "stop" event for this Context.
+     */
+    protected synchronized void stop() {
+
+        if (log.isDebugEnabled())
+            log.debug(sm.getString("contextConfig.stop"));
+
+        int i;
+
+        // Removing children
+        Container[] children = context.findChildren();
+        for (i = 0; i < children.length; i++) {
+            context.removeChild(children[i]);
+        }
+
+        // Removing application parameters
+        /*
+        ApplicationParameter[] applicationParameters =
+            context.findApplicationParameters();
+        for (i = 0; i < applicationParameters.length; i++) {
+            context.removeApplicationParameter
+                (applicationParameters[i].getName());
+        }
+        */
+
+        // Removing security constraints
+        SecurityConstraint[] securityConstraints = context.findConstraints();
+        for (i = 0; i < securityConstraints.length; i++) {
+            context.removeConstraint(securityConstraints[i]);
+        }
+
+        // Removing Ejbs
+        /*
+        ContextEjb[] contextEjbs = context.findEjbs();
+        for (i = 0; i < contextEjbs.length; i++) {
+            context.removeEjb(contextEjbs[i].getName());
+        }
+        */
+
+        // Removing environments
+        /*
+        ContextEnvironment[] contextEnvironments = context.findEnvironments();
+        for (i = 0; i < contextEnvironments.length; i++) {
+            context.removeEnvironment(contextEnvironments[i].getName());
+        }
+        */
+
+        // Removing errors pages
+        ErrorPage[] errorPages = context.findErrorPages();
+        for (i = 0; i < errorPages.length; i++) {
+            context.removeErrorPage(errorPages[i]);
+        }
+
+        // Removing filter defs
+        FilterDef[] filterDefs = context.findFilterDefs();
+        for (i = 0; i < filterDefs.length; i++) {
+            context.removeFilterDef(filterDefs[i]);
+        }
+
+        // Removing filter maps
+        FilterMap[] filterMaps = context.findFilterMaps();
+        for (i = 0; i < filterMaps.length; i++) {
+            context.removeFilterMap(filterMaps[i]);
+        }
+
+        // Removing local ejbs
+        /*
+        ContextLocalEjb[] contextLocalEjbs = context.findLocalEjbs();
+        for (i = 0; i < contextLocalEjbs.length; i++) {
+            context.removeLocalEjb(contextLocalEjbs[i].getName());
+        }
+        */
+
+        // Removing Mime mappings
+        String[] mimeMappings = context.findMimeMappings();
+        for (i = 0; i < mimeMappings.length; i++) {
+            context.removeMimeMapping(mimeMappings[i]);
+        }
+
+        // Removing parameters
+        String[] parameters = context.findParameters();
+        for (i = 0; i < parameters.length; i++) {
+            context.removeParameter(parameters[i]);
+        }
+
+        // Removing resource env refs
+        /*
+        String[] resourceEnvRefs = context.findResourceEnvRefs();
+        for (i = 0; i < resourceEnvRefs.length; i++) {
+            context.removeResourceEnvRef(resourceEnvRefs[i]);
+        }
+        */
+
+        // Removing resource links
+        /*
+        ContextResourceLink[] contextResourceLinks =
+            context.findResourceLinks();
+        for (i = 0; i < contextResourceLinks.length; i++) {
+            context.removeResourceLink(contextResourceLinks[i].getName());
+        }
+        */
+
+        // Removing resources
+        /*
+        ContextResource[] contextResources = context.findResources();
+        for (i = 0; i < contextResources.length; i++) {
+            context.removeResource(contextResources[i].getName());
+        }
+        */
+
+        // Removing sercurity role
+        String[] securityRoles = context.findSecurityRoles();
+        for (i = 0; i < securityRoles.length; i++) {
+            context.removeSecurityRole(securityRoles[i]);
+        }
+
+        // Removing servlet mappings
+        String[] servletMappings = context.findServletMappings();
+        for (i = 0; i < servletMappings.length; i++) {
+            context.removeServletMapping(servletMappings[i]);
+        }
+
+        // FIXME : Removing status pages
+
+        // Removing taglibs
+        String[] taglibs = context.findTaglibs();
+        for (i = 0; i < taglibs.length; i++) {
+            context.removeTaglib(taglibs[i]);
+        }
+
+        // Removing welcome files
+        String[] welcomeFiles = context.findWelcomeFiles();
+        for (i = 0; i < welcomeFiles.length; i++) {
+            context.removeWelcomeFile(welcomeFiles[i]);
+        }
+
+        // Removing wrapper lifecycles
+        String[] wrapperLifecycles = context.findWrapperLifecycles();
+        for (i = 0; i < wrapperLifecycles.length; i++) {
+            context.removeWrapperLifecycle(wrapperLifecycles[i]);
+        }
+
+        // Removing wrapper listeners
+        String[] wrapperListeners = context.findWrapperListeners();
+        for (i = 0; i < wrapperListeners.length; i++) {
+            context.removeWrapperListener(wrapperListeners[i]);
+        }
+
+        // Remove (partially) folders and files created by antiLocking
+        Host host = (Host) context.getParent();
+        String appBase = host.getAppBase();
+        String docBase = context.getDocBase();
+        if ((docBase != null) && (originalDocBase != null)) {
+            File docBaseFile = new File(docBase);
+            if (!docBaseFile.isAbsolute()) {
+                docBaseFile = new File(appBase, docBase);
+            }
+            // No need to log failure - it is expected in this case
+            ExpandWar.delete(docBaseFile, false);
+        }
+        
+        ok = true;
+
+    }
+    
+    
+    /**
+     * Process a "destroy" event for this Context.
+     */
+    protected synchronized void destroy() {
+        // Called from StandardContext.destroy()
+        if (log.isDebugEnabled())
+            log.debug(sm.getString("contextConfig.destroy"));
+
+        // Changed to getWorkPath per Bugzilla 35819.
+        String workDir = ((StandardContext) context).getWorkPath();
+        if (workDir != null)
+            ExpandWar.delete(new File(workDir));
+    }
+    
+    
+    /**
+     * Validate the usage of security role names in the web application
+     * deployment descriptor.  If any problems are found, issue warning
+     * messages (for backwards compatibility) and add the missing roles.
+     * (To make these problems fatal instead, simply set the <code>ok</code>
+     * instance variable to <code>false</code> as well).
+     */
+    protected void validateSecurityRoles() {
+
+        // Check role names used in <security-constraint> elements
+        SecurityConstraint constraints[] = context.findConstraints();
+        for (int i = 0; i < constraints.length; i++) {
+            String roles[] = constraints[i].findAuthRoles();
+            for (int j = 0; j < roles.length; j++) {
+                if (!"*".equals(roles[j]) &&
+                    !context.findSecurityRole(roles[j])) {
+                    log.info(sm.getString("contextConfig.role.auth", roles[j]));
+                    context.addSecurityRole(roles[j]);
+                }
+            }
+        }
+
+        // Check role names used in <servlet> elements
+        Container wrappers[] = context.findChildren();
+        for (int i = 0; i < wrappers.length; i++) {
+            Wrapper wrapper = (Wrapper) wrappers[i];
+            String runAs = wrapper.getRunAs();
+            if ((runAs != null) && !context.findSecurityRole(runAs)) {
+                log.info(sm.getString("contextConfig.role.runas", runAs));
+                context.addSecurityRole(runAs);
+            }
+            String names[] = wrapper.findSecurityReferences();
+            for (int j = 0; j < names.length; j++) {
+                String link = wrapper.findSecurityReference(names[j]);
+                if ((link != null) && !context.findSecurityRole(link)) {
+                    log.info(sm.getString("contextConfig.role.link", link));
+                    context.addSecurityRole(link);
+                }
+            }
+        }
+
+    }
+
+
+    /**
+     * Get config base.
+     */
+    protected File getConfigBase() {
+        File configBase = 
+            new File(System.getProperty("catalina.base"), "conf");
+        if (!configBase.exists()) {
+            return null;
+        } else {
+            return configBase;
+        }
+    }  
+
+    
+    protected String getHostConfigPath(String resourceName) {
+        StringBuffer result = new StringBuffer();
+        Container container = context;
+        Container host = null;
+        Container engine = null;
+        while (container != null) {
+            if (container instanceof Host)
+                host = container;
+            if (container instanceof Engine)
+                engine = container;
+            container = container.getParent();
+        }
+        if (engine != null) {
+            result.append(engine.getName()).append('/');
+        }
+        if (host != null) {
+            result.append(host.getName()).append('/');
+        }
+        result.append(resourceName);
+        return result.toString();
+    }
+
+
+    protected class ContextErrorHandler
+        implements ErrorHandler {
+
+        public void error(SAXParseException exception) {
+            parseException = exception;
+        }
+
+        public void fatalError(SAXParseException exception) {
+            parseException = exception;
+        }
+
+        public void warning(SAXParseException exception) {
+            parseException = exception;
+        }
+
+    }
+
+
+}

Added: arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/naming/resources/DirContextURLConnection.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/naming/resources/DirContextURLConnection.java	                        (rev 0)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/apache/naming/resources/DirContextURLConnection.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -0,0 +1,427 @@
+/*
+ * 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.naming.resources;
+
+import java.net.URL;
+import java.net.URLConnection;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.FileNotFoundException;
+import java.security.Permission;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Vector;
+import javax.naming.NamingException;
+import javax.naming.NamingEnumeration;
+import javax.naming.NameClassPair;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import org.apache.naming.JndiPermission;
+import org.apache.tomcat.util.http.FastHttpDateFormat;
+
+/**
+ * Connection to a JNDI directory context.
+ * <p/>
+ * Note: All the object attribute names are the WebDAV names, not the HTTP 
+ * names, so this class overrides some methods from URLConnection to do the
+ * queries using the right names. Content handler is also not used; the 
+ * content is directly returned.
+ * <p/>
+ * This file has been copied into the Tomcat Embedded container integration
+ * because there is an error in how the path is calculated to locate a file
+ * in the dir context cache.
+ * 
+ * @author <a href="mailto:remm at apache.org">Remy Maucherat</a>
+ * @version $Revision: 666821 $
+ */
+public class DirContextURLConnection 
+    extends URLConnection {
+    
+    
+    // ----------------------------------------------------------- Constructors
+    
+    
+    public DirContextURLConnection(DirContext context, URL url) {
+        super(url);
+        if (context == null)
+            throw new IllegalArgumentException
+                ("Directory context can't be null");
+        if (org.apache.naming.Constants.IS_SECURITY_ENABLED) {
+            this.permission = new JndiPermission(url.toString());
+	}
+        this.context = context;
+    }
+    
+    
+    // ----------------------------------------------------- Instance Variables
+    
+    
+    /**
+     * Directory context.
+     */
+    protected DirContext context;
+    
+    
+    /**
+     * Associated resource.
+     */
+    protected Resource resource;
+    
+    
+    /**
+     * Associated DirContext.
+     */
+    protected DirContext collection;
+    
+    
+    /**
+     * Other unknown object.
+     */
+    protected Object object;
+    
+    
+    /**
+     * Attributes.
+     */
+    protected Attributes attributes;
+    
+    
+    /**
+     * Date.
+     */
+    protected long date;
+    
+    
+    /**
+     * Permission
+     */
+    protected Permission permission;
+
+
+    // ------------------------------------------------------------- Properties
+    
+    
+    /**
+     * Connect to the DirContext, and retrive the bound object, as well as
+     * its attributes. If no object is bound with the name specified in the
+     * URL, then an IOException is thrown.
+     * 
+     * @throws IOException Object not found
+     */
+    public void connect()
+        throws IOException {
+        
+        if (!connected) {
+            
+            try {
+                date = System.currentTimeMillis();
+                String path = getURL().getFile();
+                if (context instanceof ProxyDirContext) {
+                    ProxyDirContext proxyDirContext = 
+                        (ProxyDirContext) context;
+                    String hostName = proxyDirContext.getHostName();
+                    String contextName = proxyDirContext.getContextName();
+                    if (hostName != null) {
+                        if (!path.startsWith("/" + hostName + "/"))
+                            return;
+                        path = path.substring(hostName.length()+ 1);
+                    }
+                    if (contextName != null) {
+                        if (!path.startsWith("/" + contextName + "/")) {
+                            return;
+                        } else {
+                            path = path.substring(contextName.length()+ 1);
+                        }
+                    }
+                }
+                object = context.lookup(path);
+                attributes = context.getAttributes(path);
+                if (object instanceof Resource)
+                    resource = (Resource) object;
+                if (object instanceof DirContext)
+                    collection = (DirContext) object;
+            } catch (NamingException e) {
+                // Object not found
+            }
+            
+            connected = true;
+            
+        }
+        
+    }
+    
+    
+    /**
+     * Return the content length value.
+     */
+    public int getContentLength() {
+        return getHeaderFieldInt(ResourceAttributes.CONTENT_LENGTH, -1);
+    }
+    
+    
+    /**
+     * Return the content type value.
+     */
+    public String getContentType() {
+        return getHeaderField(ResourceAttributes.CONTENT_TYPE);
+    }
+    
+    
+    /**
+     * Return the last modified date.
+     */
+    public long getDate() {
+        return date;
+    }
+    
+    
+    /**
+     * Return the last modified date.
+     */
+    public long getLastModified() {
+
+        if (!connected) {
+            // Try to connect (silently)
+            try {
+                connect();
+            } catch (IOException e) {
+            }
+        }
+
+        if (attributes == null)
+            return 0;
+
+        Attribute lastModified = 
+            attributes.get(ResourceAttributes.LAST_MODIFIED);
+        if (lastModified != null) {
+            try {
+                Date lmDate = (Date) lastModified.get();
+                return lmDate.getTime();
+            } catch (Exception e) {
+            }
+        }
+
+        return 0;
+    }
+    
+
+    protected String getHeaderValueAsString(Object headerValue) {
+        if (headerValue == null) return null;
+        if (headerValue instanceof Date) {
+            // return date strings (ie Last-Modified) in HTTP format, rather
+            // than Java format
+            return FastHttpDateFormat.formatDate(
+                    ((Date)headerValue).getTime(), null);
+        }
+        return headerValue.toString();
+    }
+
+
+    /**
+     * Returns an unmodifiable Map of the header fields.
+     */
+    public Map getHeaderFields() {
+
+      if (!connected) {
+          // Try to connect (silently)
+          try {
+              connect();
+          } catch (IOException e) {
+          }
+      }
+
+      if (attributes == null)
+          return (Collections.EMPTY_MAP);
+
+      HashMap headerFields = new HashMap(attributes.size());
+      NamingEnumeration attributeEnum = attributes.getIDs();
+      try {
+          while (attributeEnum.hasMore()) {
+              String attributeID = (String)attributeEnum.next();
+              Attribute attribute = attributes.get(attributeID);
+              if (attribute == null) continue;
+              ArrayList attributeValueList = new ArrayList(attribute.size());
+              NamingEnumeration attributeValues = attribute.getAll();
+              while (attributeValues.hasMore()) {
+                  Object attrValue = attributeValues.next();
+                  attributeValueList.add(getHeaderValueAsString(attrValue));
+              }
+              attributeValueList.trimToSize(); // should be a no-op if attribute.size() didn't lie
+              headerFields.put(attributeID, Collections.unmodifiableList(attributeValueList));
+          }
+      } catch (NamingException ne) {
+            // Shouldn't happen
+      }
+
+      return Collections.unmodifiableMap(headerFields);
+
+    }
+    
+    
+    /**
+     * Returns the name of the specified header field.
+     */
+    public String getHeaderField(String name) {
+
+        if (!connected) {
+            // Try to connect (silently)
+            try {
+                connect();
+            } catch (IOException e) {
+            }
+        }
+        
+        if (attributes == null)
+            return (null);
+
+        NamingEnumeration attributeEnum = attributes.getIDs();
+        try {
+            while (attributeEnum.hasMore()) {
+                String attributeID = (String)attributeEnum.next();
+                if (attributeID.equalsIgnoreCase(name)) {
+                    Attribute attribute = attributes.get(attributeID);
+                    if (attribute == null) return null;
+                    Object attrValue = attribute.get(attribute.size()-1);
+                    return getHeaderValueAsString(attrValue);
+                }
+            }
+        } catch (NamingException ne) {
+            // Shouldn't happen
+        }
+
+        return (null);
+        
+    }
+    
+    
+    /**
+     * Get object content.
+     */
+    public Object getContent()
+        throws IOException {
+        
+        if (!connected)
+            connect();
+        
+        if (resource != null)
+            return getInputStream();
+        if (collection != null)
+            return collection;
+        if (object != null)
+            return object;
+        
+        throw new FileNotFoundException();
+        
+    }
+    
+    
+    /**
+     * Get object content.
+     */
+    public Object getContent(Class[] classes)
+        throws IOException {
+        
+        Object object = getContent();
+        
+        for (int i = 0; i < classes.length; i++) {
+            if (classes[i].isInstance(object))
+                return object;
+        }
+        
+        return null;
+        
+    }
+    
+    
+    /**
+     * Get input stream.
+     */
+    public InputStream getInputStream() 
+        throws IOException {
+        
+        if (!connected)
+            connect();
+        
+        if (resource == null) {
+            throw new FileNotFoundException();
+        } else {
+            // Reopen resource
+            try {
+                resource = (Resource) context.lookup(getURL().getFile());
+            } catch (NamingException e) {
+            }
+        }
+        
+        return (resource.streamContent());
+        
+    }
+    
+    
+    /**
+     * Get the Permission for this URL
+     */
+    public Permission getPermission() {
+
+        return permission;
+    }
+
+
+    // --------------------------------------------------------- Public Methods
+    
+    
+    /**
+     * List children of this collection. The names given are relative to this
+     * URI's path. The full uri of the children is then : path + "/" + name.
+     */
+    public Enumeration list()
+        throws IOException {
+        
+        if (!connected) {
+            connect();
+        }
+        
+        if ((resource == null) && (collection == null)) {
+            throw new FileNotFoundException();
+        }
+        
+        Vector result = new Vector();
+        
+        if (collection != null) {
+            try {
+                NamingEnumeration enumeration = context.list(getURL().getFile());
+                while (enumeration.hasMoreElements()) {
+                    NameClassPair ncp = (NameClassPair) enumeration.nextElement();
+                    result.addElement(ncp.getName());
+                }
+            } catch (NamingException e) {
+                // Unexpected exception
+                throw new FileNotFoundException();
+            }
+        }
+        
+        return result.elements();
+        
+    }
+    
+    
+}

Modified: arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatConfiguration.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatConfiguration.java	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatConfiguration.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -23,6 +23,7 @@
  * Arquillian Tomcat Container Configuration
  * 
  * @author <a href="mailto:jean.deruelle at gmail.com">Jean Deruelle</a>
+ * @author Dan Allen
  * @version $Revision: $
  */
 public class TomcatConfiguration implements ContainerConfiguration {
@@ -33,12 +34,14 @@
 
 	private String tomcatHome = null;
 	
-	private String appBase = null;
+	private String appBase = "webapps";
 
 	private String workDir = null;
 	
 	private String serverName = "tomcat";
 
+   private boolean unpackWar = true;
+
 	public ContainerProfile getContainerProfile() {
 		return ContainerProfile.CLIENT;
 	}
@@ -108,4 +111,24 @@
 	public String getServerName() {
 		return serverName;
 	}
+
+   /**
+    * @return a switch indicating whether the WAR should be unpacked
+    */
+   public boolean isUnpackWar()
+   {
+      return unpackWar;
+   }
+
+   /**
+    * Sets the WAR to be unpacked into the java.io.tmpdir when deployed.
+    * Unpacking is required if you are using Weld to provide CDI support
+    * in a servlet environment.
+    *
+    * @param a switch indicating whether the WAR should be unpacked
+    */
+   public void setUnpackWar(boolean unpackWar)
+   {
+      this.unpackWar = unpackWar;
+   }
 }

Modified: arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatContainer.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatContainer.java	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatContainer.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -136,8 +136,7 @@
          {
             standardContext.setWorkDir(configuration.getTomcatWorkDir());
          }
-         // possible option
-         standardContext.setUnpackWAR(false);
+         standardContext.setUnpackWAR(configuration.isUnpackWar());
 			standardHost.addChild(standardContext);
          context.add(StandardContext.class, standardContext);
 		} catch (Exception e) {
@@ -199,29 +198,39 @@
 		// creating the tomcat embedded == service tag in server.xml
 		embedded = new Embedded();
 		embedded.setName(serverName);
+      // TODO this needs to be a lot more robust
 		String tomcatHome = configuration.getTomcatHome();
+      File tomcatHomeFile = null;
 		if(tomcatHome != null) {
 			if(tomcatHome.startsWith(ENV_VAR)) {
 				String sysVar = tomcatHome.substring(ENV_VAR.length(), tomcatHome.length() -1);
 				tomcatHome = System.getProperty(sysVar);
-				System.out.println("Sys var for tomcat : " + tomcatHome);
+            tomcatHomeFile = new File(tomcatHome);
+				log.info("Using tomcat home from environment variable: " + tomcatHome);
 			} 
 			if(tomcatHome != null) {
-				tomcatHome = new File(tomcatHome).getAbsolutePath();
+            tomcatHomeFile = new File(tomcatHome);
+				tomcatHome = tomcatHomeFile.getAbsolutePath();
 				embedded.setCatalinaBase(tomcatHome);
 				embedded.setCatalinaHome(tomcatHome);
-			}						
+         }
+         if (tomcatHomeFile != null)
+         {
+            tomcatHomeFile.mkdirs();
+         }
 		}
 		// creates the engine == engine tag in server.xml
 		engine = embedded.createEngine();
 		engine.setName(serverName);
-		engine.setDefaultHost(bindAddress + SEPARATOR);
+		engine.setDefaultHost(bindAddress);
 		engine.setService(embedded);
 		embedded.setContainer(engine);
 		embedded.addEngine(engine);
 		// creates the host == host tag in server.xml
-		if(tomcatHome != null) {
-			standardHost = embedded.createHost(bindAddress + SEPARATOR, embedded.getCatalinaHome() + configuration.getAppBase());
+		if(tomcatHomeFile != null) {
+         File appBaseFile = new File(tomcatHomeFile, configuration.getAppBase());
+         appBaseFile.mkdirs();
+			standardHost = embedded.createHost(bindAddress + SEPARATOR, appBaseFile.getAbsolutePath());
 		} else {
 			standardHost = embedded.createHost(bindAddress + SEPARATOR, System.getProperty("java.io.tmpdir"));
 		}

Modified: arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedDeploymentAppender.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedDeploymentAppender.java	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedDeploymentAppender.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -39,11 +39,11 @@
       JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "arquillian-tomcat-testenrichers.jar")
                         .addPackages(
                               false,
-//                              CDIInjectionEnricher.class.getPackage(),
+                              CDIInjectionEnricher.class.getPackage(),
                               ResourceInjectionEnricher.class.getPackage())
                         .addServiceProvider(
                               TestEnricher.class,
-//                              CDIInjectionEnricher.class,
+                              CDIInjectionEnricher.class,
                               ResourceInjectionEnricher.class);
       return archive;
    }

Added: arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/MavenArtifactResolver.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/MavenArtifactResolver.java	                        (rev 0)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/MavenArtifactResolver.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -0,0 +1,63 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jboss.arquillian.container.tomcat.embedded_6;
+
+import java.io.File;
+
+/**
+ * A crude resolver that converts a Maven artifact reference
+ * into a {@link java.io.File} object.
+ * 
+ * <p>This approach is an interim solution for Maven projects
+ * until the open feature request to add formally add artifacts
+ * to a test (ARQ-66) is implementated.</p>
+ *
+ * <p>The testCompile goal will resolve any test dependencies and
+ * put them in your local Maven repository. By the time the test
+ * executes, you can be sure that the JAR files you need will be
+ * in your local repository.</p>
+ *
+ * <p>Example usage:</p>
+ * 
+ * <pre>
+ * WebArchive war = ShrinkWrap.create("test.war", WebArchive.class)
+ *     .addLibrary(MavenArtifactResolver.resolve("commons-lang:commons-lang:2.5"));
+ * </pre>
+ *
+ * @author Dan Allen
+ */
+public class MavenArtifactResolver
+{
+   private static final String LOCAL_MAVEN_REPO =
+         System.getProperty("user.home") + File.separatorChar +
+         ".m2" + File.separatorChar + "repository";
+
+   public static File resolve(String groupId, String artifactId, String version)
+   {
+      return new File(LOCAL_MAVEN_REPO + File.separatorChar +
+            groupId.replace(".", File.separator) + File.separatorChar +
+            artifactId + File.separatorChar +
+            version + File.separatorChar +
+            artifactId + "-" + version + ".jar");
+   }
+
+   public static File resolve(String qualifiedArtifactId)
+   {
+      String[] segments = qualifiedArtifactId.split(":");
+      return resolve(segments[0], segments[1], segments[2]);
+   }
+}

Added: arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TestBean.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TestBean.java	                        (rev 0)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TestBean.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -0,0 +1,33 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jboss.arquillian.container.tomcat.embedded_6;
+
+import javax.annotation.Resource;
+
+/**
+ * @author Dan Allen
+ */
+public class TestBean
+{
+   @Resource(name = "name")
+   private String name;
+
+   public String getName()
+   {
+      return name;
+   }
+}

Added: arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TestServlet.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TestServlet.java	                        (rev 0)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TestServlet.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -0,0 +1,45 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jboss.arquillian.container.tomcat.embedded_6;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * TestServlet
+ *
+ * @author <a href="mailto:aslak at redhat.com">Aslak Knutsen</a>
+ * @version $Revision: $
+ */
+public class TestServlet extends HttpServlet
+{
+   private static final long serialVersionUID = 1L;
+
+   public static final String URL_PATTERN = "/Test";
+
+   public static final String MESSAGE = "hello";
+
+   @Override
+   protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
+   {
+      response.getWriter().append(MESSAGE);
+   }
+}

Modified: arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedClientTestCase.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedClientTestCase.java	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedClientTestCase.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -23,7 +23,6 @@
 import org.jboss.arquillian.api.Deployment;
 import org.jboss.arquillian.api.Run;
 import org.jboss.arquillian.api.RunModeType;
-import org.jboss.arquillian.container.tomcat.embedded_6.test.war.HelloWorldServlet;
 import org.jboss.arquillian.junit.Arquillian;
 import org.jboss.shrinkwrap.api.ShrinkWrap;
 import org.jboss.shrinkwrap.api.spec.WebArchive;
@@ -36,13 +35,14 @@
  * Arquillian lifecycle
  * 
  * @author <a href="mailto:jean.deruelle at gmail.com">Jean Deruelle</a>
+ * @author Dan Allen
  * @version $Revision: $
  */
 @RunWith(Arquillian.class)
 @Run(RunModeType.AS_CLIENT)
 public class TomcatEmbeddedClientTestCase {
 
-	private static final String HELLO_WORLD_URL = "http://localhost:8888/test/hello";
+	private static final String HELLO_WORLD_URL = "http://localhost:8888/test/Test";
 
 	// -------------------------------------------------------------------------------------||
 	// Class Members
@@ -65,9 +65,9 @@
 	 */
 	@Deployment
 	public static WebArchive createDeployment() {
-		return ShrinkWrap.create(WebArchive.class, "test.war").addClasses(
-				HelloWorldServlet.class).addWebResource(
-				HelloWorldServlet.class.getPackage(), "web.xml", "web.xml");
+		return ShrinkWrap.create(WebArchive.class, "test.war")
+         .addClass(TestServlet.class)
+         .addWebResource("client-web.xml", "web.xml");
 	}
 
 	// -------------------------------------------------------------------------------------||
@@ -79,9 +79,9 @@
 	 * Ensures the {@link HelloWorldServlet} returns the expected response
 	 */
 	@Test
-	public void testHelloWorldServlet() throws Exception {
+	public void shouldBeAbleToInvokeServletInDeployedWebApp() throws Exception {
 		// Define the input and expected outcome
-		final String expected = "Hello, world!";
+		final String expected = "hello";
 
 		URL url = new URL(HELLO_WORLD_URL);
 		InputStream in = url.openConnection().getInputStream();

Modified: arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedInContainerTestCase.java
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedInContainerTestCase.java	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/java/org/jboss/arquillian/container/tomcat/embedded_6/TomcatEmbeddedInContainerTestCase.java	2010-07-10 20:57:49 UTC (rev 4714)
@@ -20,11 +20,12 @@
 import java.net.URL;
 import java.util.logging.Logger;
 import javax.annotation.Resource;
+import javax.inject.Inject;
 
 import org.jboss.arquillian.api.Deployment;
-import org.jboss.arquillian.container.tomcat.embedded_6.test.war.HelloWorldServlet;
 import org.jboss.arquillian.junit.Arquillian;
 import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.asset.ByteArrayAsset;
 import org.jboss.shrinkwrap.api.spec.WebArchive;
 import org.junit.Assert;
 import org.junit.Test;
@@ -34,13 +35,13 @@
  * Tests that Tomcat deployments into the Tomcat server work through the
  * Arquillian lifecycle
  * 
- * @author <a href="mailto:jean.deruelle at gmail.com">Jean Deruelle</a>
+ * @author Dan Allen
  * @version $Revision: $
  */
 @RunWith(Arquillian.class)
 public class TomcatEmbeddedInContainerTestCase {
 
-	private static final String HELLO_WORLD_URL = "http://localhost:8888/test/hello";
+	private static final String HELLO_WORLD_URL = "http://localhost:8888/test/Test";
 
 	// -------------------------------------------------------------------------------------||
 	// Class Members
@@ -50,8 +51,7 @@
 	/**
 	 * Logger
 	 */
-	private static final Logger log = Logger
-			.getLogger(TomcatEmbeddedInContainerTestCase.class.getName());
+	private static final Logger log = Logger.getLogger(TomcatEmbeddedInContainerTestCase.class.getName());
 
 	// -------------------------------------------------------------------------------------||
 	// Instance Members
@@ -64,8 +64,11 @@
 	@Deployment
 	public static WebArchive createTestArchive() {
 		return ShrinkWrap.create(WebArchive.class, "test.war")
-         .addClasses(HelloWorldServlet.class)
-         .addWebResource(HelloWorldServlet.class.getPackage(), "in-container-web.xml", "web.xml");
+         .addClasses(TestServlet.class, TestBean.class)
+         .addLibrary(MavenArtifactResolver.resolve("org.jboss.weld.servlet:weld-servlet:1.0.1-Final"))
+         .addWebResource(new ByteArrayAsset(new byte[0]), "beans.xml")
+         .addManifestResource("in-container-context.xml", "context.xml")
+         .setWebXML("in-container-web.xml");
 	}
 
 	// -------------------------------------------------------------------------------------||
@@ -75,13 +78,23 @@
 
    @Resource(name = "name") String name;
 
+   @Inject TestBean testBean;
+
 	/**
 	 * Ensures the {@link HelloWorldServlet} returns the expected response
 	 */
 	@Test
-	public void testHelloWorldServlet() throws Exception {
+	public void shouldBeAbleToInjectMembersIntoTestClass()
+   {
+      log.info("Name: " + name);
+      Assert.assertEquals("Tomcat", name);
+      Assert.assertEquals("Tomcat", testBean.getName());
+	}
+
+   @Test
+   public void shouldBeAbleToInvokeServletInDeployedWebApp() throws Exception {
 		// Define the input and expected outcome
-		final String expected = "Hello, world!";
+		final String expected = "hello";
 
 		URL url = new URL(HELLO_WORLD_URL);
 		InputStream in = url.openConnection().getInputStream();
@@ -90,12 +103,12 @@
 		int len = in.read(buffer);
 		String httpResponse = "";
 		for (int q = 0; q < len; q++)
+      {
 			httpResponse += (char) buffer[q];
+      }
 
 		// Test
-		Assert.assertEquals("Expected output was not equal by value", expected,
-				httpResponse);
+		Assert.assertEquals("Expected output was not equal by value", expected, httpResponse);
 		log.info("Got expected result from Http Servlet: " + httpResponse);
-      log.info("Name: " + name);
-	}
+   }
 }

Modified: arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/arquillian.xml
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/arquillian.xml	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/arquillian.xml	2010-07-10 20:57:49 UTC (rev 4714)
@@ -3,11 +3,19 @@
 		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 		xmlns:tomcat6="urn:arq:org.jboss.arquillian.container.tomcat.embedded_6">
 
+   <!-- Uncomment to have test archives exported to the file system for inspection -->
+   <!--
+   <engine>
+      <deploymentExportPath>target/test-archives</deploymentExportPath>
+   </engine>
+   -->
+
 	<tomcat6:container>
 		<!--tomcat6:tomcatHome>/path/to/apache-tomcat-6.0.20</tomcat6:tomcatHome-->
 		<!--tomcat6:tomcatHome>${env.CATALINA_HOME}</tomcat6:tomcatHome-->
-		<tomcat6:workDir>target/tomcat/work</tomcat6:workDir> 
-		<tomcat6:appBase>target/tomcat/webapps</tomcat6:appBase> 
+		<tomcat6:tomcatHome>target/tomcat</tomcat6:tomcatHome>
+		<tomcat6:workDir>work</tomcat6:workDir> 
+		<tomcat6:appBase>webapps</tomcat6:appBase> 
 		<tomcat6:bindHttpPort>8888</tomcat6:bindHttpPort>
 	</tomcat6:container>
 

Copied: arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/client-web.xml (from rev 4712, arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/web.xml)
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/client-web.xml	                        (rev 0)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/client-web.xml	2010-07-10 20:57:49 UTC (rev 4714)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app version="2.5"
+   xmlns="http://java.sun.com/xml/ns/javaee"
+   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+   xsi:schemaLocation="
+      http://java.sun.com/xml/ns/javaee
+      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+
+   <servlet>
+      <servlet-name>TestServlet</servlet-name>
+      <servlet-class>org.jboss.arquillian.container.tomcat.embedded_6.TestServlet</servlet-class>
+   </servlet>
+
+   <servlet-mapping>
+      <servlet-name>TestServlet</servlet-name>
+      <url-pattern>/Test</url-pattern>
+   </servlet-mapping>
+
+</web-app>

Added: arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/in-container-context.xml
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/in-container-context.xml	                        (rev 0)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/in-container-context.xml	2010-07-10 20:57:49 UTC (rev 4714)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Context>
+   <Resource name="BeanManager"
+      auth="Container"
+      type="javax.enterprise.inject.spi.BeanManager"
+      factory="org.jboss.weld.resources.ManagerObjectFactory"/>
+</Context>

Copied: arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/in-container-web.xml (from rev 4712, arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/in-container-web.xml)
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/in-container-web.xml	                        (rev 0)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/in-container-web.xml	2010-07-10 20:57:49 UTC (rev 4714)
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app version="2.5"
+   xmlns="http://java.sun.com/xml/ns/javaee"
+   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+   xsi:schemaLocation="
+      http://java.sun.com/xml/ns/javaee
+      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+
+   <env-entry>
+      <env-entry-name>name</env-entry-name>
+      <env-entry-type>java.lang.String</env-entry-type>
+      <env-entry-value>Tomcat</env-entry-value>
+   </env-entry>
+
+   <listener>
+      <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
+   </listener> 
+
+   <servlet>
+      <servlet-name>TestServlet</servlet-name>
+      <servlet-class>org.jboss.arquillian.container.tomcat.embedded_6.TestServlet</servlet-class>
+   </servlet>
+
+   <servlet-mapping>
+      <servlet-name>TestServlet</servlet-name>
+      <url-pattern>/Test</url-pattern>
+   </servlet-mapping>
+
+   <servlet>
+      <servlet-name>ServletTestRunner</servlet-name>
+      <servlet-class>org.jboss.arquillian.protocol.servlet_3.ServletTestRunner</servlet-class>
+   </servlet>
+
+   <servlet-mapping>
+      <servlet-name>ServletTestRunner</servlet-name>
+      <url-pattern>/ArquillianServletRunner</url-pattern>
+   </servlet-mapping>
+
+   <resource-env-ref>
+      <description>Object factory for the CDI Bean Manager</description>
+      <resource-env-ref-name>BeanManager</resource-env-ref-name>
+      <resource-env-ref-type>javax.enterprise.inject.spi.BeanManager</resource-env-ref-type>
+   </resource-env-ref>
+
+</web-app>

Deleted: arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/in-container-web.xml
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/in-container-web.xml	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/in-container-web.xml	2010-07-10 20:57:49 UTC (rev 4714)
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<web-app version="2.5"
-   xmlns="http://java.sun.com/xml/ns/javaee"
-   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-   xsi:schemaLocation="
-      http://java.sun.com/xml/ns/javaee
-      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
-
-   <env-entry>
-      <env-entry-name>name</env-entry-name>
-      <env-entry-type>java.lang.String</env-entry-type>
-      <env-entry-value>Tomcat</env-entry-value>
-   </env-entry>
-
-   <servlet>
-      <servlet-name>hello</servlet-name>
-      <servlet-class>org.jboss.arquillian.container.tomcat.embedded_6.test.war.HelloWorldServlet</servlet-class>
-   </servlet>
-
-   <servlet-mapping>
-      <servlet-name>hello</servlet-name>
-      <url-pattern>/hello</url-pattern>
-   </servlet-mapping>
-
-   <servlet>
-      <servlet-name>ServletTestRunner</servlet-name>
-      <servlet-class>org.jboss.arquillian.protocol.servlet_3.ServletTestRunner</servlet-class>
-   </servlet>
-
-   <servlet-mapping>
-      <servlet-name>ServletTestRunner</servlet-name>
-      <url-pattern>/ArquillianServletRunner</url-pattern>
-   </servlet-mapping>
-
-</web-app>

Deleted: arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/web.xml
===================================================================
--- arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/web.xml	2010-07-10 14:53:33 UTC (rev 4713)
+++ arquillian/trunk/containers/tomcat-embedded-6/src/test/resources/org/jboss/arquillian/container/tomcat/embedded_6/test/war/web.xml	2010-07-10 20:57:49 UTC (rev 4714)
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<web-app version="2.5"
-   xmlns="http://java.sun.com/xml/ns/javaee"
-   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-   xsi:schemaLocation="
-      http://java.sun.com/xml/ns/javaee
-      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
-
-   <servlet>
-      <servlet-name>hello</servlet-name>
-      <servlet-class>org.jboss.arquillian.container.tomcat.embedded_6.test.war.HelloWorldServlet</servlet-class>
-   </servlet>
-
-   <servlet-mapping>
-      <servlet-name>hello</servlet-name>
-      <url-pattern>/hello</url-pattern>
-   </servlet-mapping>
-
-</web-app>



More information about the jboss-svn-commits mailing list