Search in sources :

Example 1 with HTTPContext

use of org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext in project tomee by apache.

the class OpenEJBDeployableContainer method deploy.

@Override
public ProtocolMetaData deploy(final Archive<?> archive) throws DeploymentException {
    final DeploymentInfo info;
    try {
        final Closeables cl = new Closeables();
        closeablesProducer.set(cl);
        info = quickDeploy(archive, testClass.get(), cl);
        // container rules (CDI) which is not the case with this solution
        if (archive.getName().endsWith(".war")) {
            final List<BeanContext> beanContexts = info.appCtx.getBeanContexts();
            if (beanContexts.size() > 1) {
                final Iterator<BeanContext> it = beanContexts.iterator();
                while (it.hasNext()) {
                    final BeanContext next = it.next();
                    if (ModuleTestContext.class.isInstance(next.getModuleContext()) && BeanContext.Comp.class != next.getBeanClass()) {
                        for (final BeanContext b : beanContexts) {
                            if (b.getModuleContext() != next.getModuleContext()) {
                                ModuleTestContext.class.cast(next.getModuleContext()).setModuleJndiContextOverride(b.getModuleContext().getModuleJndiContext());
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        servletContextProducer.set(info.appServletContext);
        sessionProducer.set(info.appSession);
        appInfoProducer.set(info.appInfo);
        appContextProducer.set(info.appCtx);
        final ClassLoader loader = info.appCtx.getWebContexts().isEmpty() ? info.appCtx.getClassLoader() : info.appCtx.getWebContexts().iterator().next().getClassLoader();
        final ClassLoader classLoader = loader == null ? info.appCtx.getClassLoader() : loader;
        TestObserver.ClassLoaders classLoaders = this.classLoader.get();
        if (classLoaders == null) {
            classLoaders = new TestObserver.ClassLoaders();
            this.classLoader.set(classLoaders);
        }
        classLoaders.register(archive.getName(), classLoader);
    } catch (final Exception e) {
        throw new DeploymentException("can't deploy " + archive.getName(), e);
    }
    // if service manager is started allow @ArquillianResource URL injection
    if (PROPERTIES.containsKey(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE)) {
        final ProtocolMetaData metaData = ServiceManagers.protocolMetaData(appInfoProducer.get());
        HTTPContext http = null;
        for (final WebAppInfo webapp : info.appInfo.webApps) {
            for (final ServletInfo servletInfo : webapp.servlets) {
                if (http == null) {
                    http = HTTPContext.class.cast(metaData.getContexts().iterator().next());
                    http.add(new Servlet(servletInfo.servletName, webapp.contextRoot));
                }
            }
            for (final ClassListInfo classListInfo : webapp.webAnnotatedClasses) {
                for (final String path : classListInfo.list) {
                    if (!path.contains("!")) {
                        continue;
                    }
                    if (http == null) {
                        http = HTTPContext.class.cast(metaData.getContexts().iterator().next());
                    }
                    http.add(new Servlet(path.substring(path.lastIndexOf('!') + 2).replace(".class", "").replace("/", "."), webapp.contextRoot));
                }
            }
        }
        if (metaData != null) {
            return metaData;
        }
    }
    return new ProtocolMetaData();
}
Also used : HTTPContext(org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext) TestObserver(org.apache.openejb.arquillian.common.TestObserver) NamingException(javax.naming.NamingException) LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) IOException(java.io.IOException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException) ClassListInfo(org.apache.openejb.assembler.classic.ClassListInfo) ServletInfo(org.apache.openejb.assembler.classic.ServletInfo) BeanContext(org.apache.openejb.BeanContext) ModuleTestContext(org.apache.openejb.ModuleTestContext) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) Servlet(org.jboss.arquillian.container.spi.client.protocol.metadata.Servlet) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException) ProtocolMetaData(org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData)

Example 2 with HTTPContext

use of org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext in project tomee by apache.

the class ServiceManagers method newHttpProtocolMetaData.

private static ProtocolMetaData newHttpProtocolMetaData(final ServerService ss, final String contextRoot) {
    final HTTPContext httpContext = new HTTPContext(ss.getIP(), ss.getPort());
    httpContext.add(new Servlet("ArquillianServletRunner", contextRoot));
    return new ProtocolMetaData().addContext(httpContext);
}
Also used : Servlet(org.jboss.arquillian.container.spi.client.protocol.metadata.Servlet) HTTPContext(org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext) ProtocolMetaData(org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData)

Example 3 with HTTPContext

use of org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext in project tomee by apache.

the class RemoteInitialContextObserver method beforeSuite.

public void beforeSuite(@Observes final BeforeEnrichment event) {
    final ProtocolMetaData metaData = protocolMetadata.get();
    if (metaData == null || !metaData.hasContext(HTTPContext.class)) {
        return;
    }
    try {
        Thread.currentThread().getContextClassLoader().loadClass(REMOTE_INITIAL_CONTEXT_FACTORY);
        final HTTPContext httpContext = metaData.getContexts(HTTPContext.class).iterator().next();
        final Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, REMOTE_INITIAL_CONTEXT_FACTORY);
        props.setProperty(Context.PROVIDER_URL, "http://" + httpContext.getHost() + ":" + httpContext.getPort() + "/tomee/ejb");
        Context existing = null;
        try {
            existing = existingContext.get();
        } catch (final Throwable t) {
        // no-op
        }
        final Context proxyInstance = (Context) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { Context.class }, new MultipleContextHandler(props, existing));
        // cause ContextProducer of arquillian supports InitialContext
        context.set(new InitialContextWrapper(proxyInstance));
    } catch (final ClassNotFoundException | NamingException e) {
    // no-op
    }
}
Also used : InitialContext(javax.naming.InitialContext) HTTPContext(org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext) Context(javax.naming.Context) HTTPContext(org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext) NamingException(javax.naming.NamingException) ProtocolMetaData(org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData) Properties(java.util.Properties)

Example 4 with HTTPContext

use of org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext in project Payara by payara.

the class PayaraContainer method deploy.

@Override
public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException {
    String deploymentName = createDeploymentName(archive.getName());
    try {
        glassfish.getDeployer().deploy(toURL(archive).toURI(), "--name", deploymentName);
    } catch (Exception e) {
        throw new DeploymentException("Could not deploy " + archive.getName(), e);
    }
    try {
        HTTPContext httpContext = new HTTPContext(ADDRESS, bindHttpPort);
        findServlets(httpContext, resolveWebArchiveNames(archive));
        return new ProtocolMetaData().addContext(httpContext);
    } catch (GlassFishException e) {
        throw new DeploymentException("Could not probe Payara embedded for environment", e);
    }
}
Also used : GlassFishException(org.glassfish.embeddable.GlassFishException) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException) HTTPContext(org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext) ProtocolMetaData(org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData) NamingException(javax.naming.NamingException) GlassFishException(org.glassfish.embeddable.GlassFishException) LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException)

Example 5 with HTTPContext

use of org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext in project Payara by payara.

the class PayaraMicroDeployableContainer method deploy.

@Override
public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException {
    if (archive == null) {
        throw new IllegalArgumentException("archive must not be null");
    }
    try {
        // The main directory from which we'll conduct our business
        Path arquillianMicroDir = Files.createTempDirectory("arquillian-payara-micro");
        // Create paths for the directories we'll be using
        Path deploymentDir = arquillianMicroDir.resolve("deployments/");
        // Create the directories
        deploymentDir.toFile().mkdir();
        // Create the path for the deployment archive (e.g. the application war or ear)
        File deploymentFile = deploymentDir.resolve(archive.getName()).toFile();
        // Create the deployment file itself
        archive.as(ZipExporter.class).exportTo(deploymentFile);
        // Create the list of commands to start Payara Micro
        List<String> cmd = new ArrayList<>(asList("java", "-jar", configuration.getMicroJarFile().getAbsolutePath(), "--deploy", deploymentFile.getAbsolutePath()));
        // Start at a random port so multiple instances won't run in to eachother all the time
        if (configuration.isRandomHttpPort()) {
            cmd.addAll(asList("--port", (8080 + new SecureRandom().nextInt(1000)) + ""));
        }
        // Add --autoBindHttp if it's enabled
        if (configuration.isAutoBindHttp()) {
            cmd.addAll(asList("--autoBindHttp", "--autoBindRange", "1000"));
        }
        // Disable clustering if it's not explicitly enabled
        if (!configuration.isClusterEnabled()) {
            cmd.add("--nocluster");
        }
        // Enable --showServletMappings if it's supported
        if (configuration.getMicroVersion().isMoreRecentThan(new PayaraVersion("5.181-SNAPSHOT"))) {
            cmd.add("--showServletMappings");
        }
        // Start Payara Micro in debug mode if it's been enabled
        if (configuration.isDebug()) {
            cmd.add(1, "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5006");
        }
        // Add the extra cmd options to the Payara Micro instance
        if (configuration.getCmdOptions() != null) {
            int index = 1;
            // Split on non-escaped spaces
            for (String option : configuration.getCmdOptions().split("(?<!\\\\) ")) {
                // Unescape any path spaces before adding the string
                cmd.add(index, option.replace("\\ ", " "));
                index++;
            }
        }
        // Add the extra micro options to the Payara Micro instance
        if (configuration.getExtraMicroOptions() != null) {
            // Split on non-escaped spaces
            for (String option : configuration.getExtraMicroOptions().split("(?<!\\\\) ")) {
                // Unescape any path spaces before adding the string
                cmd.add(option.replace("\\ ", " "));
            }
        }
        logger.info("Starting Payara Micro using cmd: " + cmd);
        // Allow Ctrl-C to stop the test, then start Payara Micro
        registerShutdownHook();
        payaraMicroProcess = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        // Create an executor for handling the log reading and writing
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
        // Create a consumer for reading Payara Micro output
        BufferingConsumer consumer = new BufferingConsumer(createProcessOutputConsumer());
        ConsoleReader logReader = new ConsoleReader(payaraMicroProcess, consumer);
        executor.execute(logReader);
        // Check at intervals if Payara Micro has finished starting up or failed to start.
        CountDownLatch payaraMicroStarted = new CountDownLatch(1);
        executor.scheduleAtFixedRate(() -> {
            log = consumer.getBuffer().toString();
            // Check for app deployed
            Matcher startupMatcher = instanceConfigPattern.matcher(log);
            if (startupMatcher.find()) {
                payaraMicroStarted.countDown();
            }
        }, 1500, 200, MILLISECONDS);
        int startupTimeoutInSeconds = configuration.isDebug() ? -1 : configuration.getStartupTimeoutInSeconds();
        boolean microStarted = false;
        // Wait for Payara Micro to start up, or time out after the specified timeout
        if (startupTimeoutInSeconds == -1) {
            payaraMicroStarted.await();
            microStarted = true;
        } else {
            microStarted = payaraMicroStarted.await(startupTimeoutInSeconds, SECONDS);
        }
        if (microStarted) {
            // Shutdown log reading executor
            executor.shutdownNow();
            // Create a matcher for the 'Instance Configured' message
            Matcher instanceConfigMatcher = instanceConfigPattern.matcher(log);
            if (instanceConfigMatcher.find()) {
                // Get the host and port that the application started on.
                String host = instanceConfigMatcher.group("host").trim();
                String[] ports = instanceConfigMatcher.group("ports").trim().split(" ");
                int firstPort = Integer.parseInt(ports[0].trim());
                logger.info("Payara Micro running on host: " + host + " port: " + firstPort);
                HTTPContext httpContext = new HTTPContext(host, firstPort);
                // If the instance config is in the new JSON format, parse the JSON object.
                if (instanceConfigMatcher.group("jsonFormat") != null) {
                    processDeploymentAsJson(log.substring(instanceConfigMatcher.start()), httpContext);
                } else {
                    // Otherwise, parse it the old way
                    processDeploymentOldMethod(log.substring(instanceConfigMatcher.start()), httpContext);
                }
                ProtocolMetaData protocolMetaData = new ProtocolMetaData();
                protocolMetaData.addContext(httpContext);
                return protocolMetaData;
            }
        }
    } catch (IOException e) {
        // Occurs when there was an error starting the Payara Micro thread or the ConsoleReader thread.
        logger.severe("Failed in creating a thread for Payara Micro.\n" + e.getMessage());
        Thread.currentThread().interrupt();
        return null;
    } catch (InterruptedException e) {
        // Occurs when the timeout is reached in waiting for Payara Micro to start
        logger.severe("Timeout reached waiting for Payara Micro to start.\n" + e.getMessage());
        Thread.currentThread().interrupt();
        return null;
    }
    throw new DeploymentException("No applications were found deployed to Payara Micro.");
}
Also used : Path(java.nio.file.Path) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ConsoleReader(fish.payara.arquillian.container.payara.process.ConsoleReader) Matcher(java.util.regex.Matcher) ZipExporter(org.jboss.shrinkwrap.api.exporter.ZipExporter) ArrayList(java.util.ArrayList) SecureRandom(java.security.SecureRandom) HTTPContext(org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) BufferingConsumer(fish.payara.arquillian.container.payara.process.BufferingConsumer) PayaraVersion(fish.payara.arquillian.container.payara.PayaraVersion) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException) ProtocolMetaData(org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData) File(java.io.File)

Aggregations

HTTPContext (org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext)10 ProtocolMetaData (org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData)9 DeploymentException (org.jboss.arquillian.container.spi.client.container.DeploymentException)6 Servlet (org.jboss.arquillian.container.spi.client.protocol.metadata.Servlet)5 File (java.io.File)4 NamingException (javax.naming.NamingException)4 LifecycleException (org.jboss.arquillian.container.spi.client.container.LifecycleException)4 IOException (java.io.IOException)3 ZipExporter (org.jboss.shrinkwrap.api.exporter.ZipExporter)3 ArrayList (java.util.ArrayList)2 TestObserver (org.apache.openejb.arquillian.common.TestObserver)2 AppInfo (org.apache.openejb.assembler.classic.AppInfo)2 WebAppInfo (org.apache.openejb.assembler.classic.WebAppInfo)2 PayaraVersion (fish.payara.arquillian.container.payara.PayaraVersion)1 PayaraClientException (fish.payara.arquillian.container.payara.clientutils.PayaraClientException)1 BufferingConsumer (fish.payara.arquillian.container.payara.process.BufferingConsumer)1 ConsoleReader (fish.payara.arquillian.container.payara.process.ConsoleReader)1 InputStream (java.io.InputStream)1 Path (java.nio.file.Path)1 SecureRandom (java.security.SecureRandom)1