Search in sources :

Example 1 with HttpWebApplicationServer

use of cloud.piranha.http.webapp.HttpWebApplicationServer in project piranha by piranhacloud.

the class MicroInnerDeployer method start.

/**
 * Start the application.
 *
 * @param applicationArchive the application archive.
 * @param classLoader the classloader.
 * @param handlers the handlers.
 * @param config the configuration.
 * @return the map.
 */
public Map<String, Object> start(Archive<?> applicationArchive, ClassLoader classLoader, Map<String, Function<URL, URLConnection>> handlers, Map<String, Object> config) {
    try {
        WebApplication webApplication = getWebApplication(applicationArchive, classLoader);
        LOGGER.log(INFO, "Starting web application " + applicationArchive.getName() + " on Piranha Micro " + webApplication.getAttribute(MICRO_PIRANHA));
        // The global archive stream handler is set to resolve "shrinkwrap://" URLs (created from strings).
        // Such URLs come into being primarily when code takes resolves a class or resource from the class loader by URL
        // and then takes the string form of the URL representing the class or resource.
        GlobalArchiveStreamHandler streamHandler = new GlobalArchiveStreamHandler(webApplication);
        // Life map to the StaticURLStreamHandlerFactory used by the root class loader
        handlers.put("shrinkwrap", streamHandler::connect);
        // Source of annotations
        Index index = getIndex();
        // Target of annotations
        AnnotationManager annotationManager = new InternalAnnotationScanAnnotationManager();
        webApplication.getManager().setAnnotationManager(annotationManager);
        // Copy annotations from our "annotations" collection from source index to target manager
        forEachWebAnnotation(webAnnotation -> addAnnotationToIndex(index, webAnnotation, annotationManager));
        // Collect sub-classes/interfaces of our "instances" collection from source index to target manager
        forEachInstance(instanceClass -> addInstanceToIndex(index, instanceClass, annotationManager));
        // Collect any sub-classes/interfaces from any HandlesTypes annotation
        getAnnotations(index, HandlesTypes.class).map(this::getTarget).forEach(annotationTarget -> getAnnotationInstances(annotationTarget, HandlesTypes.class).map(HandlesTypes.class::cast).forEach(handlesTypesInstance -> stream(handlesTypesInstance.value()).forEach(e -> {
            if (e.isAnnotation()) {
                addAnnotationToIndex(index, e, annotationManager);
            } else {
                addInstanceToIndex(index, e, annotationManager);
            }
        })));
        // Setup the default identity store, which is used as the default "username and roles database" for
        // (Servlet) security.
        initIdentityStore(webApplication);
        setApplicationContextPath(webApplication, config, applicationArchive);
        DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
        for (WebApplicationExtension extension : ServiceLoader.load(WebApplicationExtension.class)) {
            extensionContext.add(extension);
        }
        extensionContext.configure(webApplication);
        webApplication.initialize();
        webApplication.start();
        if ((boolean) config.get("micro.http.start")) {
            HttpWebApplicationServer webApplicationServer = new HttpWebApplicationServer();
            webApplicationServer.addWebApplication(webApplication);
            ServiceLoader<HttpServer> httpServers = ServiceLoader.load(HttpServer.class);
            httpServer = httpServers.findFirst().orElseThrow();
            httpServer.setServerPort((Integer) config.get("micro.port"));
            httpServer.setSSL(Boolean.getBoolean("piranha.http.ssl"));
            httpServer.setHttpServerProcessor(webApplicationServer);
            httpServer.start();
        }
        return Map.of("deployedServlets", webApplication.getServletRegistrations().keySet(), "deployedApplication", new MicroInnerApplication(webApplication), "deployedContextRoot", webApplication.getContextPath());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } catch (Exception e) {
        throw e;
    }
}
Also used : AnnotationManager(cloud.piranha.core.api.AnnotationManager) InternalAnnotationScanAnnotationManager(cloud.piranha.extension.annotationscan.internal.InternalAnnotationScanAnnotationManager) DefaultWebApplicationExtensionContext(cloud.piranha.core.impl.DefaultWebApplicationExtensionContext) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URL(java.net.URL) RunAs(jakarta.annotation.security.RunAs) PostConstruct(jakarta.annotation.PostConstruct) ClassInfo(org.jboss.jandex.ClassInfo) Node(org.jboss.shrinkwrap.api.Node) HttpWebApplicationServer(cloud.piranha.http.webapp.HttpWebApplicationServer) Resource(jakarta.annotation.Resource) ByteArrayInputStream(java.io.ByteArrayInputStream) DeclareRoles(jakarta.annotation.security.DeclareRoles) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) WebFilter(jakarta.servlet.annotation.WebFilter) AnnotationTarget(org.jboss.jandex.AnnotationTarget) ShrinkWrapResource(cloud.piranha.resource.shrinkwrap.ShrinkWrapResource) HttpServer(cloud.piranha.http.api.HttpServer) ServiceLoader(java.util.ServiceLoader) PreDestroy(jakarta.annotation.PreDestroy) PermitAll(jakarta.annotation.security.PermitAll) WebApplicationExtension(cloud.piranha.core.api.WebApplicationExtension) Objects(java.util.Objects) Stream(java.util.stream.Stream) AnnotationInstance(org.jboss.jandex.AnnotationInstance) DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) MultipartConfig(jakarta.servlet.annotation.MultipartConfig) CLASS(org.jboss.jandex.AnnotationTarget.Kind.CLASS) SAXException(org.xml.sax.SAXException) WebApplication(cloud.piranha.core.api.WebApplication) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TRUE(java.lang.Boolean.TRUE) Arrays.stream(java.util.Arrays.stream) Level(java.lang.System.Logger.Level) ArchiveAsset(org.jboss.shrinkwrap.api.asset.ArchiveAsset) ServletSecurity(jakarta.servlet.annotation.ServletSecurity) XPath(javax.xml.xpath.XPath) AnnotationManager(cloud.piranha.core.api.AnnotationManager) NODESET(javax.xml.xpath.XPathConstants.NODESET) Resources(jakarta.annotation.Resources) Function(java.util.function.Function) URLConnection(java.net.URLConnection) NamedNodeMap(org.w3c.dom.NamedNodeMap) Priority(jakarta.annotation.Priority) Index(org.jboss.jandex.Index) RolesAllowed(jakarta.annotation.security.RolesAllowed) HandlesTypes(jakarta.servlet.annotation.HandlesTypes) IndexReader(org.jboss.jandex.IndexReader) NodeList(org.w3c.dom.NodeList) DenyAll(jakarta.annotation.security.DenyAll) UTF_8(java.nio.charset.StandardCharsets.UTF_8) INFO(java.lang.System.Logger.Level.INFO) DotName.createSimple(org.jboss.jandex.DotName.createSimple) IOException(java.io.IOException) Archive(org.jboss.shrinkwrap.api.Archive) GlobalArchiveStreamHandler(cloud.piranha.resource.shrinkwrap.GlobalArchiveStreamHandler) Consumer(java.util.function.Consumer) WebListener(jakarta.servlet.annotation.WebListener) FIELD(org.jboss.jandex.AnnotationTarget.Kind.FIELD) XPathFactory(javax.xml.xpath.XPathFactory) METHOD(org.jboss.jandex.AnnotationTarget.Kind.METHOD) Logger(java.lang.System.Logger) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) WebInitParam(jakarta.servlet.annotation.WebInitParam) InternalAnnotationScanAnnotationManager(cloud.piranha.extension.annotationscan.internal.InternalAnnotationScanAnnotationManager) WebServlet(jakarta.servlet.annotation.WebServlet) InputStream(java.io.InputStream) DefaultWebApplicationExtensionContext(cloud.piranha.core.impl.DefaultWebApplicationExtensionContext) WebApplicationExtension(cloud.piranha.core.api.WebApplicationExtension) Index(org.jboss.jandex.Index) IOException(java.io.IOException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HttpWebApplicationServer(cloud.piranha.http.webapp.HttpWebApplicationServer) GlobalArchiveStreamHandler(cloud.piranha.resource.shrinkwrap.GlobalArchiveStreamHandler) InternalAnnotationScanAnnotationManager(cloud.piranha.extension.annotationscan.internal.InternalAnnotationScanAnnotationManager) HttpServer(cloud.piranha.http.api.HttpServer) DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) WebApplication(cloud.piranha.core.api.WebApplication) HandlesTypes(jakarta.servlet.annotation.HandlesTypes)

Example 2 with HttpWebApplicationServer

use of cloud.piranha.http.webapp.HttpWebApplicationServer in project piranha by piranhacloud.

the class MicroPiranha method run.

/**
 * Run method.
 */
@Override
public void run() {
    long startTime = System.currentTimeMillis();
    LOGGER.log(INFO, () -> "Starting Piranha");
    webApplicationServer = new HttpWebApplicationServer();
    if (httpPort > 0) {
        HttpServer httpServer = ServiceLoader.load(HttpServer.class).findFirst().orElseThrow();
        httpServer.setServerPort(httpPort);
        httpServer.setHttpServerProcessor(webApplicationServer);
        httpServer.start();
    }
    if (httpsPort > 0) {
        HttpServer httpsServer = ServiceLoader.load(HttpServer.class).findFirst().orElseThrow();
        httpsServer.setHttpServerProcessor(webApplicationServer);
        httpsServer.setServerPort(httpsPort);
        httpsServer.setSSL(true);
        httpsServer.start();
    }
    String contextPath = null;
    if (warFile != null && warFile.getName().toLowerCase().endsWith(".war")) {
        contextPath = warFile.getName().substring(0, warFile.getName().length() - 4);
        if (webAppDir == null) {
            webAppDir = new File(contextPath);
        }
        extractWarFile(warFile, webAppDir);
    }
    if (webAppDir != null && webAppDir.exists()) {
        if (contextPath == null) {
            contextPath = webAppDir.getName();
        }
        DefaultWebApplication webApplication = new DefaultWebApplication();
        webApplication.addResource(new DirectoryResource(webAppDir));
        DefaultWebApplicationClassLoader classLoader = new DefaultWebApplicationClassLoader(webAppDir);
        webApplication.setClassLoader(classLoader);
        if (Boolean.getBoolean("cloud.piranha.modular.enable") || jpmsEnabled) {
            setupLayers(classLoader);
        }
        if (classLoader.getResource("/META-INF/services/" + WebApplicationExtension.class.getName()) == null) {
            DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
            extensionContext.add(extensionClass);
            extensionContext.configure(webApplication);
        } else {
            DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
            ServiceLoader<WebApplicationExtension> serviceLoader = ServiceLoader.load(WebApplicationExtension.class, classLoader);
            extensionContext.add(serviceLoader.iterator().next());
            extensionContext.configure(webApplication);
        }
        if (contextPath.equalsIgnoreCase("ROOT")) {
            contextPath = "";
        } else if (!contextPath.startsWith("/")) {
            contextPath = "/" + contextPath;
        }
        webApplication.setContextPath(contextPath);
        webApplicationServer.addWebApplication(webApplication);
        try {
            webApplication.initialize();
        } catch (Exception e) {
            LOGGER.log(ERROR, "Failed to initialize web application");
            System.exit(0);
        }
    }
    if (webAppDir == null && warFile == null) {
        LOGGER.log(WARNING, "No web application deployed");
    }
    webApplicationServer.start();
    long finishTime = System.currentTimeMillis();
    LOGGER.log(INFO, "Started Piranha");
    LOGGER.log(INFO, "It took {0} milliseconds", finishTime - startTime);
    if (pid != null) {
        File pidFile = new File("tmp", "piranha-micro.pid");
        if (!pidFile.getParentFile().exists()) {
            if (!pidFile.getParentFile().mkdirs()) {
                LOGGER.log(WARNING, "Unable to create tmp directory for PID file");
            }
        }
        try (PrintWriter writer = new PrintWriter(new FileWriter(pidFile))) {
            writer.println(pid);
            writer.flush();
        } catch (IOException ioe) {
            LOGGER.log(WARNING, "Unable to write PID file", ioe);
        }
    }
    while (!stop) {
        if (pid != null) {
            File pidFile = new File("tmp", "piranha-micro.pid");
            if (!pidFile.exists()) {
                stop();
            }
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }
}
Also used : DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) DefaultWebApplicationExtensionContext(cloud.piranha.core.impl.DefaultWebApplicationExtensionContext) DefaultWebApplicationClassLoader(cloud.piranha.core.impl.DefaultWebApplicationClassLoader) WebApplicationExtension(cloud.piranha.core.api.WebApplicationExtension) FileWriter(java.io.FileWriter) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) HttpWebApplicationServer(cloud.piranha.http.webapp.HttpWebApplicationServer) DirectoryResource(cloud.piranha.resource.impl.DirectoryResource) HttpServer(cloud.piranha.http.api.HttpServer) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 3 with HttpWebApplicationServer

use of cloud.piranha.http.webapp.HttpWebApplicationServer in project piranha by piranhacloud.

the class ServerPiranha method run.

/**
 * Run method.
 */
@Override
public void run() {
    long startTime = System.currentTimeMillis();
    LOGGER.log(INFO, () -> "Starting Piranha");
    webApplicationServer = new HttpWebApplicationServer();
    startHttpServer();
    startHttpsServer();
    webApplicationServer.start();
    WebApplicationServerRequestMapper requestMapper = webApplicationServer.getRequestMapper();
    File[] webapps = webAppsDir.listFiles();
    if (webapps != null) {
        for (File webapp : webapps) {
            if (webapp.getName().toLowerCase().endsWith(".war")) {
                String contextPath = webapp.getName().substring(0, webapp.getName().length() - 4);
                File webAppDirectory = new File(webAppsDir, contextPath);
                extractWarFile(webapp, webAppDirectory);
                DefaultWebApplication webApplication = new ServerWebApplication(requestMapper);
                webApplication.addResource(new DirectoryResource(webAppDirectory));
                DefaultWebApplicationClassLoader classLoader = new DefaultWebApplicationClassLoader(webAppDirectory);
                webApplication.setClassLoader(classLoader);
                if (Boolean.getBoolean("cloud.piranha.modular.enable") || jpmsEnabled) {
                    setupLayers(classLoader);
                }
                if (classLoader.getResource("/META-INF/services/" + WebApplicationExtension.class.getName()) == null) {
                    DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
                    extensionContext.add(defaultExtensionClass);
                    extensionContext.configure(webApplication);
                } else {
                    DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
                    ServiceLoader<WebApplicationExtension> serviceLoader = ServiceLoader.load(WebApplicationExtension.class, classLoader);
                    extensionContext.add(serviceLoader.iterator().next());
                    extensionContext.configure(webApplication);
                }
                if (contextPath.equalsIgnoreCase("ROOT")) {
                    contextPath = "";
                } else if (!contextPath.startsWith("/")) {
                    contextPath = "/" + contextPath;
                }
                webApplication.setContextPath(contextPath);
                try {
                    webApplication.initialize();
                    webApplication.start();
                    LOGGER.log(INFO, "Deployed " + webapp.getName() + " at " + webApplication.getContextPath());
                } catch (Exception e) {
                    LOGGER.log(ERROR, () -> "Failed to initialize app " + webapp.getName(), e);
                }
                webApplicationServer.addWebApplication(webApplication);
            }
        }
    }
    long finishTime = System.currentTimeMillis();
    LOGGER.log(INFO, "Started Piranha");
    LOGGER.log(INFO, "It took {0} milliseconds", finishTime - startTime);
    started = true;
    File startedFile = new File("tmp/piranha.started");
    File stoppedFile = new File("tmp/piranha.stopped");
    if (stoppedFile.exists()) {
        try {
            Files.delete(stoppedFile.toPath());
        } catch (IOException ioe) {
            LOGGER.log(WARNING, "Error while deleting existing piranha.stopped file", ioe);
        }
    }
    if (!startedFile.exists()) {
        try {
            startedFile.createNewFile();
        } catch (IOException ioe) {
            LOGGER.log(WARNING, "Unable to create piranha.started file", ioe);
        }
    }
    File pidFile = new File(PID_FILE);
    while (isRunning()) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
        if (!pidFile.exists()) {
            webApplicationServer.stop();
            stopHttpServer();
            if (httpsServer != null) {
                httpsServer.stop();
            }
        }
    }
    finishTime = System.currentTimeMillis();
    LOGGER.log(INFO, "Stopped Piranha");
    LOGGER.log(INFO, "We ran for {0} milliseconds", finishTime - startTime);
    if (startedFile.exists()) {
        try {
            Files.delete(startedFile.toPath());
        } catch (IOException ioe) {
            LOGGER.log(WARNING, "Error while deleting existing piranha.started file", ioe);
        }
    }
    if (!stoppedFile.exists()) {
        try {
            stoppedFile.createNewFile();
        } catch (IOException ioe) {
            LOGGER.log(WARNING, "Unable to create piranha.stopped file", ioe);
        }
    }
    if (exitOnStop) {
        System.exit(0);
    }
}
Also used : DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) DefaultWebApplicationExtensionContext(cloud.piranha.core.impl.DefaultWebApplicationExtensionContext) DefaultWebApplicationClassLoader(cloud.piranha.core.impl.DefaultWebApplicationClassLoader) WebApplicationExtension(cloud.piranha.core.api.WebApplicationExtension) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) HttpWebApplicationServer(cloud.piranha.http.webapp.HttpWebApplicationServer) WebApplicationServerRequestMapper(cloud.piranha.core.api.WebApplicationServerRequestMapper) DirectoryResource(cloud.piranha.resource.impl.DirectoryResource) File(java.io.File)

Example 4 with HttpWebApplicationServer

use of cloud.piranha.http.webapp.HttpWebApplicationServer in project piranha by piranhacloud.

the class IsolatedServerPiranha method run.

/**
 * Start method.
 */
@Override
public void run() {
    long startTime = System.currentTimeMillis();
    LOGGER.log(INFO, () -> "Starting Piranha");
    webApplicationServer = new HttpWebApplicationServer();
    HttpServer httpServer = ServiceLoader.load(HttpServer.class).findFirst().orElseThrow();
    httpServer.setServerPort(8080);
    httpServer.setHttpServerProcessor(webApplicationServer);
    httpServer.setSSL(ssl);
    httpServer.start();
    webApplicationServer.start();
    File[] webapps = new File("webapps").listFiles();
    if (webapps != null) {
        if (webapps.length != 0) {
            // Limit threads used by Weld, since default is Runtime.getRuntime().availableProcessors(), which is per deployment.
            int threadsPerApp = Math.max(2, Runtime.getRuntime().availableProcessors() / webapps.length);
            System.setProperty("org.jboss.weld.executor.threadPoolSize", threadsPerApp + "");
        }
        File deployingFile = createDeployingFile();
        Arrays.stream(webapps).parallel().filter(warFile -> warFile.getName().toLowerCase().endsWith(".war")).forEach(warFile -> deploy(warFile, webApplicationServer));
        try {
            Files.delete(deployingFile.toPath());
        } catch (IOException ioe) {
            LOGGER.log(WARNING, "Unable to delete deploying file", ioe);
        }
    }
    long finishTime = System.currentTimeMillis();
    LOGGER.log(INFO, "Started Piranha");
    LOGGER.log(INFO, "It took {0} milliseconds", finishTime - startTime);
    File startedFile = createStartedFile();
    File pidFile = new File("tmp/piranha.pid");
    while (httpServer.isRunning()) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
        if (!pidFile.exists()) {
            webApplicationServer.stop();
            httpServer.stop();
            try {
                Files.delete(startedFile.toPath());
            } catch (IOException ioe) {
                LOGGER.log(WARNING, "Unable to delete PID file", ioe);
            }
            System.exit(0);
        }
    }
    finishTime = System.currentTimeMillis();
    LOGGER.log(INFO, "Stopped Piranha");
    LOGGER.log(INFO, "We ran for {0} milliseconds", finishTime - startTime);
}
Also used : Piranha(cloud.piranha.core.api.Piranha) ZipImporter(org.jboss.shrinkwrap.api.importer.ZipImporter) Arrays(java.util.Arrays) ShrinkWrap(org.jboss.shrinkwrap.api.ShrinkWrap) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) WebApplicationRequest(cloud.piranha.core.api.WebApplicationRequest) WARNING(java.lang.System.Logger.Level.WARNING) Files(java.nio.file.Files) HttpServer(cloud.piranha.http.api.HttpServer) INFO(java.lang.System.Logger.Level.INFO) IOException(java.io.IOException) ServiceLoader(java.util.ServiceLoader) ServletException(jakarta.servlet.ServletException) File(java.io.File) HttpWebApplicationServer(cloud.piranha.http.webapp.HttpWebApplicationServer) WebApplicationResponse(cloud.piranha.core.api.WebApplicationResponse) Logger(java.lang.System.Logger) MicroWebApplication(cloud.piranha.micro.shrinkwrap.builder.MicroWebApplication) MicroOuterDeployer(cloud.piranha.micro.shrinkwrap.loader.MicroOuterDeployer) MicroConfiguration(cloud.piranha.micro.shrinkwrap.loader.MicroConfiguration) Level(java.lang.System.Logger.Level) HttpServer(cloud.piranha.http.api.HttpServer) IOException(java.io.IOException) File(java.io.File) HttpWebApplicationServer(cloud.piranha.http.webapp.HttpWebApplicationServer)

Aggregations

HttpWebApplicationServer (cloud.piranha.http.webapp.HttpWebApplicationServer)4 IOException (java.io.IOException)4 WebApplicationExtension (cloud.piranha.core.api.WebApplicationExtension)3 DefaultWebApplication (cloud.piranha.core.impl.DefaultWebApplication)3 DefaultWebApplicationExtensionContext (cloud.piranha.core.impl.DefaultWebApplicationExtensionContext)3 HttpServer (cloud.piranha.http.api.HttpServer)3 ServletException (jakarta.servlet.ServletException)3 File (java.io.File)3 DefaultWebApplicationClassLoader (cloud.piranha.core.impl.DefaultWebApplicationClassLoader)2 DirectoryResource (cloud.piranha.resource.impl.DirectoryResource)2 Logger (java.lang.System.Logger)2 Level (java.lang.System.Logger.Level)2 AnnotationManager (cloud.piranha.core.api.AnnotationManager)1 Piranha (cloud.piranha.core.api.Piranha)1 WebApplication (cloud.piranha.core.api.WebApplication)1 WebApplicationRequest (cloud.piranha.core.api.WebApplicationRequest)1 WebApplicationResponse (cloud.piranha.core.api.WebApplicationResponse)1 WebApplicationServerRequestMapper (cloud.piranha.core.api.WebApplicationServerRequestMapper)1 InternalAnnotationScanAnnotationManager (cloud.piranha.extension.annotationscan.internal.InternalAnnotationScanAnnotationManager)1 MicroWebApplication (cloud.piranha.micro.shrinkwrap.builder.MicroWebApplication)1