Search in sources :

Example 1 with WebApplication

use of cloud.piranha.core.api.WebApplication in project piranha by piranhacloud.

the class MicroInnerDeployer method getWebApplication.

WebApplication getWebApplication(Archive<?> archive, ClassLoader newClassLoader) {
    WebApplication webApplication = new DefaultWebApplication();
    webApplication.setClassLoader(newClassLoader);
    // The main resource representing the (war) archive itself.
    webApplication.addResource(new ShrinkWrapResource(archive));
    // Get the list of embedded archives containing a "/META-INF/resources" folder.
    Node resourceNodes = archive.get("/META-INF/piranha/resource-libs");
    if (resourceNodes != null) {
        for (Node resourceNode : resourceNodes.getChildren()) {
            ArchiveAsset resourceArchiveAsset = (ArchiveAsset) resourceNode.getAsset();
            // Add the archive as a resource with the "/META-INF/resources" folder shifted to its root
            webApplication.addResource(new ShrinkWrapResource("/META-INF/resources", resourceArchiveAsset.getArchive()));
        }
    }
    return webApplication;
}
Also used : DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) ShrinkWrapResource(cloud.piranha.resource.shrinkwrap.ShrinkWrapResource) Node(org.jboss.shrinkwrap.api.Node) ArchiveAsset(org.jboss.shrinkwrap.api.asset.ArchiveAsset) DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) WebApplication(cloud.piranha.core.api.WebApplication)

Example 2 with WebApplication

use of cloud.piranha.core.api.WebApplication 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 3 with WebApplication

use of cloud.piranha.core.api.WebApplication in project piranha by piranhacloud.

the class EmbeddedResponseBuilderTest method testWebApplication.

/**
 * Test webApplication method.
 *
 * @throws Exception when an error occurs.
 */
@Test
void testWebApplication() throws Exception {
    DefaultWebApplication webApplication = new DefaultWebApplication();
    EmbeddedResponse response = new EmbeddedResponseBuilder().webApplication(webApplication).build();
    assertTrue(response.getWebApplication() instanceof WebApplication);
    assertEquals(webApplication, response.getWebApplication());
}
Also used : DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) WebApplication(cloud.piranha.core.api.WebApplication) Test(org.junit.jupiter.api.Test)

Example 4 with WebApplication

use of cloud.piranha.core.api.WebApplication in project piranha by piranhacloud.

the class WebXmlInitializer method onStartup.

/**
 * On startup.
 *
 * @param classes the classes.
 * @param servletContext the servlet context.
 * @throws ServletException when a servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    LOGGER.log(DEBUG, () -> "Entering WebXmlInitializer.onStartup");
    try {
        WebApplication webApplication = (WebApplication) servletContext;
        InternalWebXmlManager manager = new InternalWebXmlManager();
        webApplication.getManager().setWebXmlManager(manager);
        InternalWebXmlParser parser = new InternalWebXmlParser();
        InputStream inputStream = servletContext.getResourceAsStream("WEB-INF/web.xml");
        if (inputStream != null) {
            WebXml webXml = parser.parse(servletContext.getResourceAsStream("WEB-INF/web.xml"));
            manager.setWebXml(webXml);
            manager.setInitialWebXml(webXml);
        }
        ArrayList<WebXml> webFragments = new ArrayList<>();
        List<URL> webFragmentUrls = Collections.list(servletContext.getClassLoader().getResources("META-INF/web-fragment.xml"));
        for (URL url : webFragmentUrls) {
            try (InputStream stream = url.openStream()) {
                WebXml webFragment = parser.parse(stream);
                webFragment.setFragment(true);
                webFragments.add(webFragment);
            }
        }
        if (!webFragments.isEmpty()) {
            manager.setWebFragments(webFragments);
        }
        if (manager.getWebXml() == null) {
            manager.setWebXml(new WebXml());
        }
        if (manager.getWebXml() != null) {
            WebXml webXml = manager.getWebXml();
            InternalWebXmlProcessor processor = new InternalWebXmlProcessor();
            processor.process(webXml, webApplication);
            if (webXml.getMetadataComplete()) {
                return;
            }
            removeExistingServletMappings(webApplication, manager);
            manager.getOrderedFragments().forEach(fragment -> processor.process(fragment, webApplication));
        } else {
            LOGGER.log(DEBUG, "No web.xml found!");
        }
    } catch (IOException e) {
        LOGGER.log(WARNING, "Unable to parse web.xml", e);
    }
    LOGGER.log(DEBUG, () -> "Exiting WebXmlInitializer.onStartup");
}
Also used : InternalWebXmlManager(cloud.piranha.extension.webxml.internal.InternalWebXmlManager) WebXml(cloud.piranha.core.api.WebXml) InternalWebXmlProcessor(cloud.piranha.extension.webxml.internal.InternalWebXmlProcessor) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) InternalWebXmlParser(cloud.piranha.extension.webxml.internal.InternalWebXmlParser) IOException(java.io.IOException) WebApplication(cloud.piranha.core.api.WebApplication) URL(java.net.URL)

Example 5 with WebApplication

use of cloud.piranha.core.api.WebApplication in project piranha by piranhacloud.

the class SoteriaInitializer method onStartup.

/**
 * Initialize Soteria.
 *
 * @param classes the classes.
 * @param servletContext the Servlet context.
 * @throws ServletException when a Servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    LOGGER.log(DEBUG, "Initializing Soteria");
    WebApplication webApplication = (WebApplication) servletContext;
    webApplication.getManager().getSecurityManager().setUsernamePasswordLoginHandler(new IdentityStoreLoginHandler());
    SamRegistrationInstaller installer = new SamRegistrationInstaller();
    installer.onStartup(classes, servletContext);
    LOGGER.log(DEBUG, "Initialized Soteria");
}
Also used : WebApplication(cloud.piranha.core.api.WebApplication) SamRegistrationInstaller(org.glassfish.soteria.servlet.SamRegistrationInstaller)

Aggregations

WebApplication (cloud.piranha.core.api.WebApplication)33 Test (org.junit.jupiter.api.Test)8 DefaultWebApplication (cloud.piranha.core.impl.DefaultWebApplication)5 EmbeddedPiranha (cloud.piranha.embedded.EmbeddedPiranha)5 EmbeddedPiranhaBuilder (cloud.piranha.embedded.EmbeddedPiranhaBuilder)5 EmbeddedResponse (cloud.piranha.embedded.EmbeddedResponse)5 IOException (java.io.IOException)3 SecurityManager (cloud.piranha.core.api.SecurityManager)2 ShrinkWrapResource (cloud.piranha.resource.shrinkwrap.ShrinkWrapResource)2 InputStream (java.io.InputStream)2 URL (java.net.URL)2 Node (org.jboss.shrinkwrap.api.Node)2 ArchiveAsset (org.jboss.shrinkwrap.api.asset.ArchiveAsset)2 AnnotationManager (cloud.piranha.core.api.AnnotationManager)1 LocaleEncodingManager (cloud.piranha.core.api.LocaleEncodingManager)1 WebApplicationExtension (cloud.piranha.core.api.WebApplicationExtension)1 WebXml (cloud.piranha.core.api.WebXml)1 DefaultWebApplicationExtensionContext (cloud.piranha.core.impl.DefaultWebApplicationExtensionContext)1 EmbeddedRequest (cloud.piranha.embedded.EmbeddedRequest)1 EmbeddedRequestBuilder (cloud.piranha.embedded.EmbeddedRequestBuilder)1