repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/TaglibDescriptorImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import org.apache.jasper.deploy.TagLibraryInfo; import jakarta.servlet.descriptor.TaglibDescriptor; /** * @author Stuart Douglas */ public class TaglibDescriptorImpl implements TaglibDescriptor { private final TagLibraryInfo tagLibraryInfo; public TaglibDescriptorImpl(TagLibraryInfo tagLibraryInfo) { this.tagLibraryInfo = tagLibraryInfo; } @Override public String getTaglibURI() { return tagLibraryInfo.getUri(); } @Override public String getTaglibLocation() { return tagLibraryInfo.getLocation(); } }
1,648
31.98
70
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/TldParsingDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ResourceRoot; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.parser.jsp.TldMetaDataParser; import org.jboss.metadata.parser.util.NoopXMLResolver; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.JspConfigMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.TaglibMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.vfs.VirtualFile; /** * @author Remy Maucherat */ public class TldParsingDeploymentProcessor implements DeploymentUnitProcessor { private static final String TLD = ".tld"; private static final String META_INF = "META-INF"; private static final String WEB_INF = "WEB-INF"; private static final String CLASSES = "classes"; private static final String LIB = "lib"; private static final String IMPLICIT_TLD = "implicit.tld"; private static final String RESOURCES = "resources"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData == null || warMetaData.getMergedJBossWebMetaData() == null) { return; } TldsMetaData tldsMetaData = deploymentUnit.getAttachment(TldsMetaData.ATTACHMENT_KEY); if (tldsMetaData == null) { tldsMetaData = new TldsMetaData(); deploymentUnit.putAttachment(TldsMetaData.ATTACHMENT_KEY, tldsMetaData); } Map<String, TldMetaData> tlds = new HashMap<String, TldMetaData>(); tldsMetaData.setTlds(tlds); final List<TldMetaData> uniqueTlds = new ArrayList<>(); final VirtualFile deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot(); final List<VirtualFile> testRoots = new ArrayList<VirtualFile>(); testRoots.add(deploymentRoot); testRoots.add(deploymentRoot.getChild(WEB_INF)); testRoots.add(deploymentRoot.getChild(META_INF)); for (ResourceRoot root : deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS)) { testRoots.add(root.getRoot()); testRoots.add(root.getRoot().getChild(META_INF)); testRoots.add(root.getRoot().getChild(META_INF).getChild(RESOURCES)); } JspConfigMetaData merged = warMetaData.getMergedJBossWebMetaData().getJspConfig(); if (merged != null && merged.getTaglibs() != null) { for (final TaglibMetaData tld : merged.getTaglibs()) { boolean found = false; for (final VirtualFile root : testRoots) { VirtualFile child = root.getChild(tld.getTaglibLocation()); if (child.exists()) { if (isTldFile(child)) { TldMetaData value = processTld(deploymentRoot, child, tlds, uniqueTlds); if (!tlds.containsKey(tld.getTaglibUri())) { tlds.put(tld.getTaglibUri(), value); } } found = true; break; } } if (!found) { UndertowLogger.ROOT_LOGGER.tldNotFound(tld.getTaglibLocation()); } } } // TLDs are located in WEB-INF or any subdir (except the top level "classes" and "lib") // and in JARs from WEB-INF/lib, in META-INF or any subdir List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS); for (ResourceRoot resourceRoot : resourceRoots) { if (resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { VirtualFile webFragment = resourceRoot.getRoot().getChild(META_INF); if (webFragment.exists() && webFragment.isDirectory()) { processTlds(deploymentRoot, webFragment.getChildren(), tlds, uniqueTlds); } } } VirtualFile webInf = deploymentRoot.getChild(WEB_INF); if (webInf.exists() && webInf.isDirectory()) { for (VirtualFile file : webInf.getChildren()) { if (isTldFile(file)) { processTld(deploymentRoot, file, tlds, uniqueTlds); } else if (file.isDirectory() && !CLASSES.equals(file.getName()) && !LIB.equals(file.getName())) { processTlds(deploymentRoot, file.getChildren(), tlds, uniqueTlds); } } } JBossWebMetaData mergedMd = warMetaData.getMergedJBossWebMetaData(); if (mergedMd.getListeners() == null) { mergedMd.setListeners(new ArrayList<ListenerMetaData>()); } final ArrayList<TldMetaData> allTlds = new ArrayList<>(uniqueTlds); allTlds.addAll(tldsMetaData.getSharedTlds(deploymentUnit)); for (final TldMetaData tld : allTlds) { if (tld.getListeners() != null) { for (ListenerMetaData l : tld.getListeners()) { mergedMd.getListeners().add(l); } } } } private boolean isTldFile(VirtualFile file) { return file.isFile() && file.getName().toLowerCase(Locale.ENGLISH).endsWith(TLD); } private TldMetaData processTld(VirtualFile root, VirtualFile file, Map<String, TldMetaData> tlds, List<TldMetaData> uniqueTlds) throws DeploymentUnitProcessingException { String pathNameRelativeToRoot; try { pathNameRelativeToRoot = file.getPathNameRelativeTo(root); } catch (IllegalArgumentException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.tldFileNotContainedInRoot(file.getPathName(), root.getPathName()), e); } final TldMetaData value = parseTLD(file); String key = "/" + pathNameRelativeToRoot; uniqueTlds.add(value); if (!tlds.containsKey(key)) { tlds.put(key, value); } return value; } private void processTlds(VirtualFile root, List<VirtualFile> files, Map<String, TldMetaData> tlds, final List<TldMetaData> uniqueTlds) throws DeploymentUnitProcessingException { for (VirtualFile file : files) { if (isTldFile(file)) { processTld(root, file, tlds, uniqueTlds); } else if (file.isDirectory()) { processTlds(root, file.getChildren(), tlds, uniqueTlds); } } } private TldMetaData parseTLD(VirtualFile tld) throws DeploymentUnitProcessingException { if (IMPLICIT_TLD.equals(tld.getName())) { // Implicit TLDs are different from regular TLDs return new TldMetaData(); } InputStream is = null; try { is = tld.openStream(); final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setXMLResolver(NoopXMLResolver.create()); XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is); return TldMetaDataParser.parse(xmlReader); } catch (XMLStreamException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(tld.toString(), e.getLocation().getLineNumber(), e.getLocation().getColumnNumber()), e); } catch (IOException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(tld.toString()), e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } } } }
10,070
42.223176
174
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/DefaultDeploymentMappingProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.AbstractMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author Tomaz Cerar (c) 2016 Red Hat Inc. */ public final class DefaultDeploymentMappingProvider { private static DefaultDeploymentMappingProvider INSTANCE = new DefaultDeploymentMappingProvider(); public static DefaultDeploymentMappingProvider instance() { return INSTANCE; } private final ConcurrentHashMap<String, Map.Entry<String, String>> mappings; private DefaultDeploymentMappingProvider() { this.mappings = new ConcurrentHashMap<>(); } public Map.Entry<String, String> getMapping(String deploymentName) { return mappings.get(deploymentName); } public void removeMapping(String deploymentName) { mappings.remove(deploymentName); } public void addMapping(String deploymentName, String serverName, String hostName) { if (mappings.putIfAbsent(deploymentName, new AbstractMap.SimpleEntry<>(serverName, hostName)) != null) { throw UndertowLogger.ROOT_LOGGER.duplicateDefaultWebModuleMapping(deploymentName, serverName, hostName); } } public void clear(){ mappings.clear(); } }
2,359
34.223881
116
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/JspInitializationListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import org.apache.jasper.runtime.JspApplicationContextImpl; import org.jboss.as.web.common.ExpressionFactoryWrapper; import org.wildfly.extension.undertow.ImportedClassELResolver; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import jakarta.servlet.jsp.JspApplicationContext; import jakarta.servlet.jsp.JspFactory; import java.util.List; import org.wildfly.security.manager.WildFlySecurityManager; /** * Listener that sets up the {@link JspApplicationContext} with any wrapped EL expression factories and also * setting up any relevant {@link jakarta.el.ELResolver}s * * @author Stuart Douglas */ public class JspInitializationListener implements ServletContextListener { public static final String CONTEXT_KEY = "org.jboss.as.web.deployment.JspInitializationListener.wrappers"; private static final String DISABLE_IMPORTED_CLASS_EL_RESOLVER_PROPERTY = "org.wildfly.extension.undertow.deployment.disableImportedClassELResolver"; @Override public void contextInitialized(final ServletContextEvent sce) { // if the servlet version is 3.1 or higher, setup a ELResolver which allows usage of static fields java.lang.* final ServletContext servletContext = sce.getServletContext(); final JspApplicationContext jspApplicationContext = JspFactory.getDefaultFactory().getJspApplicationContext(servletContext); boolean disableImportedClassELResolver = Boolean.parseBoolean( WildFlySecurityManager.getSystemPropertiesPrivileged().getProperty(DISABLE_IMPORTED_CLASS_EL_RESOLVER_PROPERTY)); if (!disableImportedClassELResolver && (servletContext.getEffectiveMajorVersion() > 3 || (servletContext.getEffectiveMajorVersion() == 3 && servletContext.getEffectiveMinorVersion() >= 1))) { jspApplicationContext.addELResolver(new ImportedClassELResolver()); } // setup a wrapped JspApplicationContext if there are any EL expression factory wrappers for this servlet context final List<ExpressionFactoryWrapper> expressionFactoryWrappers = (List<ExpressionFactoryWrapper>) sce.getServletContext().getAttribute(CONTEXT_KEY); if (expressionFactoryWrappers != null && !expressionFactoryWrappers.isEmpty()) { final JspApplicationContextWrapper jspApplicationContextWrapper = new JspApplicationContextWrapper(JspApplicationContextImpl.getInstance(servletContext), expressionFactoryWrappers, sce.getServletContext()); sce.getServletContext().setAttribute(JspApplicationContextImpl.class.getName(), jspApplicationContextWrapper); } } @Override public void contextDestroyed(final ServletContextEvent sce) { } }
3,849
52.472222
218
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/WebJBossAllParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import org.jboss.as.ee.structure.JBossDescriptorPropertyReplacement; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.jbossallxml.JBossAllXMLParser; import org.jboss.metadata.parser.jbossweb.JBossWebMetaDataParser; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.staxmapper.XMLExtendedStreamReader; /** * The app client handler for jboss-all.xml * * @author Stuart Douglas */ public class WebJBossAllParser implements JBossAllXMLParser<JBossWebMetaData> { public static final AttachmentKey<JBossWebMetaData> ATTACHMENT_KEY = AttachmentKey.create(JBossWebMetaData.class); public static final QName ROOT_ELEMENT = new QName("http://www.jboss.com/xml/ns/javaee", "jboss-web"); @Override public JBossWebMetaData parse(final XMLExtendedStreamReader reader, final DeploymentUnit deploymentUnit) throws XMLStreamException { return JBossWebMetaDataParser.parse(reader, JBossDescriptorPropertyReplacement.propertyReplacer(deploymentUnit)); } }
2,246
41.396226
136
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowJSRWebSocketDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.websockets.jsr.JsrWebSocketLogger; import io.undertow.websockets.jsr.WebSocketDeploymentInfo; import org.jboss.as.controller.PathElement; import org.jboss.as.ee.utils.ClassLoadingUtils; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentResourceSupport; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.as.web.common.WarMetaData; import org.jboss.dmr.ModelNode; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.modules.Module; import org.wildfly.extension.undertow.UndertowExtension; import org.wildfly.extension.undertow.logging.UndertowLogger; import jakarta.websocket.ClientEndpoint; import jakarta.websocket.Endpoint; import jakarta.websocket.server.ServerApplicationConfig; import jakarta.websocket.server.ServerEndpoint; import jakarta.websocket.server.ServerEndpointConfig; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Deployment processor for native JSR-356 websockets * <p/> * * @author Stuart Douglas */ public class UndertowJSRWebSocketDeploymentProcessor implements DeploymentUnitProcessor { private static final DotName SERVER_ENDPOINT = DotName.createSimple(ServerEndpoint.class.getName()); private static final DotName CLIENT_ENDPOINT = DotName.createSimple(ClientEndpoint.class.getName()); private static final DotName SERVER_APPLICATION_CONFIG = DotName.createSimple(ServerApplicationConfig.class.getName()); private static final DotName ENDPOINT = DotName.createSimple(Endpoint.class.getName()); @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if (module == null) { return; } ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(module.getClassLoader()); WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (metaData == null || metaData.getMergedJBossWebMetaData() == null) { return; } if(!metaData.getMergedJBossWebMetaData().isEnableWebSockets()) { return; } final Set<Class<?>> annotatedEndpoints = new HashSet<>(); final Set<Class<? extends Endpoint>> endpoints = new HashSet<>(); final Set<Class<? extends ServerApplicationConfig>> config = new HashSet<>(); final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); final List<AnnotationInstance> serverEndpoints = index.getAnnotations(SERVER_ENDPOINT); if (serverEndpoints != null) { for (AnnotationInstance endpoint : serverEndpoints) { if (endpoint.target() instanceof ClassInfo) { ClassInfo clazz = (ClassInfo) endpoint.target(); try { Class<?> moduleClass = ClassLoadingUtils.loadClass(clazz.name().toString(), module); if (!Modifier.isAbstract(moduleClass.getModifiers())) { annotatedEndpoints.add(moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e); } } } } final List<AnnotationInstance> clientEndpoints = index.getAnnotations(CLIENT_ENDPOINT); if (clientEndpoints != null) { for (AnnotationInstance endpoint : clientEndpoints) { if (endpoint.target() instanceof ClassInfo) { ClassInfo clazz = (ClassInfo) endpoint.target(); try { Class<?> moduleClass = ClassLoadingUtils.loadClass(clazz.name().toString(), module); if (!Modifier.isAbstract(moduleClass.getModifiers())) { annotatedEndpoints.add(moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e); } } } } final Set<ClassInfo> subclasses = index.getAllKnownImplementors(SERVER_APPLICATION_CONFIG); if (subclasses != null) { for (final ClassInfo clazz : subclasses) { try { Class<?> moduleClass = ClassLoadingUtils.loadClass(clazz.name().toString(), module); if (!Modifier.isAbstract(moduleClass.getModifiers())) { config.add((Class) moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e); } } } final Set<ClassInfo> epClasses = index.getAllKnownSubclasses(ENDPOINT); if (epClasses != null) { for (final ClassInfo clazz : epClasses) { try { Class<?> moduleClass = ClassLoadingUtils.loadClass(clazz.name().toString(), module); if (!Modifier.isAbstract(moduleClass.getModifiers())) { endpoints.add((Class) moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e); } } } WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo(); doDeployment(deploymentUnit, webSocketDeploymentInfo, annotatedEndpoints, config, endpoints); installWebsockets(phaseContext, webSocketDeploymentInfo); } finally { Thread.currentThread().setContextClassLoader(oldCl); } } private void installWebsockets(final DeploymentPhaseContext phaseContext, final WebSocketDeploymentInfo webSocketDeploymentInfo) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); deploymentUnit.putAttachment(UndertowAttachments.WEB_SOCKET_DEPLOYMENT_INFO, webSocketDeploymentInfo); } private void doDeployment(DeploymentUnit deploymentUnit, final WebSocketDeploymentInfo container, final Set<Class<?>> annotatedEndpoints, final Set<Class<? extends ServerApplicationConfig>> serverApplicationConfigClasses, final Set<Class<? extends Endpoint>> endpoints) throws DeploymentUnitProcessingException { Set<Class<? extends Endpoint>> allScannedEndpointImplementations = new HashSet<>(endpoints); Set<Class<?>> allScannedAnnotatedEndpoints = new HashSet<>(annotatedEndpoints); Set<Class<?>> newAnnotatatedEndpoints = new HashSet<>(); Set<ServerEndpointConfig> serverEndpointConfigurations = new HashSet<>(); final Set<ServerApplicationConfig> configInstances = new HashSet<>(); for (Class<? extends ServerApplicationConfig> clazz : serverApplicationConfigClasses) { try { configInstances.add(clazz.newInstance()); } catch (InstantiationException | IllegalAccessException e) { JsrWebSocketLogger.ROOT_LOGGER.couldNotInitializeConfiguration(clazz, e); } } if (!configInstances.isEmpty()) { for (ServerApplicationConfig config : configInstances) { Set<Class<?>> returnedEndpoints = config.getAnnotatedEndpointClasses(allScannedAnnotatedEndpoints); if (returnedEndpoints != null) { newAnnotatatedEndpoints.addAll(returnedEndpoints); } Set<ServerEndpointConfig> endpointConfigs = config.getEndpointConfigs(allScannedEndpointImplementations); if (endpointConfigs != null) { serverEndpointConfigurations.addAll(endpointConfigs); } } } else { newAnnotatatedEndpoints.addAll(allScannedAnnotatedEndpoints); } //annotated endpoints first for (Class<?> endpoint : newAnnotatatedEndpoints) { if(endpoint != null ) { container.addEndpoint(endpoint); ServerEndpoint annotation = endpoint.getAnnotation(ServerEndpoint.class); if (annotation != null) { String path = annotation.value(); addManagementWebsocket(deploymentUnit, endpoint, path); } } } for (final ServerEndpointConfig endpoint : serverEndpointConfigurations) { if(endpoint != null) { container.addEndpoint(endpoint); addManagementWebsocket(deploymentUnit, endpoint.getEndpointClass(), endpoint.getPath()); } } } void addManagementWebsocket(final DeploymentUnit unit, Class endpoint, String path) { try { final DeploymentResourceSupport deploymentResourceSupport = unit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT); //websockets don't have the concept of a name, however the path much be unique final ModelNode node = deploymentResourceSupport.getDeploymentSubModel(UndertowExtension.SUBSYSTEM_NAME, PathElement.pathElement("websocket", path)); node.get("endpoint-class").set(endpoint.getName()); node.get("path").set(path); } catch (Exception e) { UndertowLogger.ROOT_LOGGER.failedToRegisterWebsocket(endpoint, path, e); } } }
11,571
46.818182
316
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/ConfiguredHandlerWrapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import org.jboss.common.beans.property.BeanUtils; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.security.manager.WildFlySecurityManager; import java.lang.reflect.Constructor; import java.util.Map; import java.util.Properties; /** * Handler wrapper that create a new instance of the specified {@link HandlerWrapper} or * {@link HttpHandler} class, and configures it via the specified properties. * * @author Stuart Douglas */ public class ConfiguredHandlerWrapper implements HandlerWrapper { private final Class<?> handlerClass; private final Map<String, String> properties; public ConfiguredHandlerWrapper(Class<?> handlerClass, Map<String, String> properties) { this.handlerClass = handlerClass; this.properties = properties; } @Override public HttpHandler wrap(HttpHandler handler) { try { final Object instance; if (HttpHandler.class.isAssignableFrom(handlerClass)) { final Constructor<?> ctor = handlerClass.getConstructor(HttpHandler.class); // instantiate the handler with the TCCL as the handler class' classloader final ClassLoader prevCL = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(handlerClass); try { instance = ctor.newInstance(handler); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(prevCL); } } else if (HandlerWrapper.class.isAssignableFrom(handlerClass)) { // instantiate the handler with the TCCL as the handler class' classloader final ClassLoader prevCL = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(handlerClass); try { instance = handlerClass.newInstance(); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(prevCL); } } else { throw UndertowLogger.ROOT_LOGGER.handlerWasNotAHandlerOrWrapper(handlerClass); } Properties p = new Properties(); p.putAll(properties); ClassLoader oldCl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(BeanUtils.class); BeanUtils.mapJavaBeanProperties(instance, p); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldCl); } if (HttpHandler.class.isAssignableFrom(handlerClass)) { return (HttpHandler) instance; } else { return ((HandlerWrapper) instance).wrap(handler); } } catch (Exception e) { throw UndertowLogger.ROOT_LOGGER.failedToConfigureHandler(handlerClass, e); } } }
4,132
42.968085
119
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/ExternalTldParsingDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.parser.jsp.TldMetaDataParser; import org.jboss.metadata.parser.util.NoopXMLResolver; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.Resource; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * * Looks for external TLD's * * @author Stuart Douglas */ public class ExternalTldParsingDeploymentProcessor implements DeploymentUnitProcessor { private static final String IMPLICIT_TLD = "implicit.tld"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData == null || warMetaData.getMergedJBossWebMetaData() == null) { return; } TldsMetaData tldsMetaData = deploymentUnit.getAttachment(TldsMetaData.ATTACHMENT_KEY); Map<String, TldMetaData> tlds = tldsMetaData.getTlds(); Set<String> sharedTldUris = new HashSet<>(); for(TldMetaData shared : tldsMetaData.getSharedTlds(deploymentUnit)) { sharedTldUris.add(shared.getUri()); } Module module = deploymentUnit.getAttachment(Attachments.MODULE); try { Iterator<Resource> resources = module.globResources("META-INF/**.tld"); while (resources.hasNext()) { final Resource resource = resources.next(); //horrible hack //we don't want to parse Jakarta Server Faces TLD's //this would be picked up by the shared tlds check below, but this means we don't //waste time re-parsing them if(resource.getURL().toString().contains("jakarta/faces/main")) { continue; } if(resource.getName().startsWith("META-INF/")) { if(tlds.containsKey(resource.getName())) { continue; } if(resource.getURL().getProtocol().equals("vfs")) { continue; } final TldMetaData value = parseTLD(resource); if(sharedTldUris.contains(value.getUri())) { //don't re-include shared TLD's continue; } String key = "/" + resource.getName(); if (!tlds.containsKey(key)) { tlds.put(key, value); } if (!tlds.containsKey(value.getUri())) { tlds.put(value.getUri(), value); } if (value.getListeners() != null) { for (ListenerMetaData l : value.getListeners()) { List<ListenerMetaData> listeners = warMetaData.getMergedJBossWebMetaData().getListeners(); if(listeners == null) { warMetaData.getMergedJBossWebMetaData().setListeners(listeners = new ArrayList<ListenerMetaData>()); } listeners.add(l); } } } } } catch (ModuleLoadException e) { throw new DeploymentUnitProcessingException(e); } } private TldMetaData parseTLD(Resource tld) throws DeploymentUnitProcessingException { if (IMPLICIT_TLD.equals(tld.getName())) { // Implicit TLDs are different from regular TLDs return new TldMetaData(); } InputStream is = null; try { is = tld.openStream(); final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setXMLResolver(NoopXMLResolver.create()); XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is); return TldMetaDataParser.parse(xmlReader); } catch (XMLStreamException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(tld.getName(), e.getLocation().getLineNumber(), e.getLocation().getColumnNumber()), e); } catch (IOException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(tld.getName()), e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } } } }
6,858
41.86875
155
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/WebComponentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import jakarta.servlet.AsyncListener; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.jboss.as.web.common.WarMetaData; import org.jboss.as.web.common.WebComponentDescription; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.ServletMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TldMetaData; /** * Processor that figures out what type of component a servlet/listener is, and registers the appropriate metadata. * The different types are: * <ul> * <li>Managed Bean - If the servlet is annotated with the <code>ManagedBean</code> annotation</li> * <li>Jakarta Contexts and Dependency Injection Bean - If the servlet is deployed in a bean archive</li> * <li>EE Component - If this is an EE deployment and the servlet is not one of the above</li> * <li>Normal Servlet - If the EE subsystem is disabled</li> * </ul> * <p/> * For ManagedBean Servlets no action is necessary at this stage, as the servlet is already registered as a component. * For Jakarta Contexts and Dependency Injection and EE components a component definition is added to the deployment. * <p/> * For now we are just using managed bean components as servlets. We may need a custom component type in future. */ public class WebComponentProcessor implements DeploymentUnitProcessor { /** * Tags in these packages do not need to be computerized */ private static final String[] BUILTIN_TAGLIBS = {"org.apache.taglibs.standard", "com.sun.faces.taglib.jsf_core", "com.sun.faces.ext.taglib", "com.sun.faces.taglib.html_basic",}; /** * Dotname for AsyncListener, which can be injected dynamically. */ private static final DotName ASYNC_LISTENER_INTERFACE = DotName.createSimple(AsyncListener.class.getName()); @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; } final Map<String, ComponentDescription> componentByClass = new HashMap<String, ComponentDescription>(); final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final EEApplicationClasses applicationClassesDescription = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); final CompositeIndex compositeIndex = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX); if (moduleDescription == null) { return; //not an EE deployment } for (ComponentDescription component : moduleDescription.getComponentDescriptions()) { componentByClass.put(component.getComponentClassName(), component); } final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); final TldsMetaData tldsMetaData = deploymentUnit.getAttachment(TldsMetaData.ATTACHMENT_KEY); final Set<String> classes = getAllComponentClasses(deploymentUnit, compositeIndex, warMetaData, tldsMetaData); for (String clazz : classes) { if (clazz == null || clazz.trim().isEmpty()) { continue; } ComponentDescription description = componentByClass.get(clazz); if (description != null) { //for now just make sure it has a single view //this will generally be a managed bean, but it could also be an Jakarta Enterprise Beans //TODO: make sure the component is a managed bean if (!(description.getViews().size() == 1)) { throw UndertowLogger.ROOT_LOGGER.wrongComponentType(clazz); } } else { //we do not make the standard tags into components, as there is no need if (compositeIndex.getClassByName(DotName.createSimple(clazz)) == null) { boolean found = false; for (String pack : BUILTIN_TAGLIBS) { if (clazz.startsWith(pack)) { found = true; break; } } if(found) { continue; } } description = new WebComponentDescription(clazz, clazz, moduleDescription, deploymentUnit.getServiceName(), applicationClassesDescription); moduleDescription.addComponent(description); deploymentUnit.addToAttachmentList(WebComponentDescription.WEB_COMPONENTS, description.getStartServiceName()); } } } /** * Gets all classes that are eligible for injection etc * * @param metaData * @return */ private Set<String> getAllComponentClasses(DeploymentUnit deploymentUnit, CompositeIndex index, WarMetaData metaData, TldsMetaData tldsMetaData) { final Set<String> classes = new HashSet<String>(); getAllComponentClasses(metaData.getMergedJBossWebMetaData(), classes); if (tldsMetaData == null) return classes; if (tldsMetaData.getSharedTlds(deploymentUnit) != null) for (TldMetaData tldMetaData : tldsMetaData.getSharedTlds(deploymentUnit)) { getAllComponentClasses(tldMetaData, classes); } if (tldsMetaData.getTlds() != null) for (Map.Entry<String, TldMetaData> tldMetaData : tldsMetaData.getTlds().entrySet()) { getAllComponentClasses(tldMetaData.getValue(), classes); } getAllAsyncListenerClasses(index, classes); return classes; } private void getAllComponentClasses(JBossWebMetaData metaData, Set<String> classes) { if (metaData.getServlets() != null) for (ServletMetaData servlet : metaData.getServlets()) { if (servlet.getServletClass() != null) { classes.add(servlet.getServletClass()); } } if (metaData.getFilters() != null) for (FilterMetaData filter : metaData.getFilters()) { classes.add(filter.getFilterClass()); } if (metaData.getListeners() != null) for (ListenerMetaData listener : metaData.getListeners()) { classes.add(listener.getListenerClass()); } } private void getAllComponentClasses(TldMetaData metaData, Set<String> classes) { if (metaData.getValidator() != null) { classes.add(metaData.getValidator().getValidatorClass()); } if (metaData.getListeners() != null) for (ListenerMetaData listener : metaData.getListeners()) { classes.add(listener.getListenerClass()); } if (metaData.getTags() != null) for (TagMetaData tag : metaData.getTags()) { classes.add(tag.getTagClass()); } } private void getAllAsyncListenerClasses(CompositeIndex index, Set<String> classes) { if (index != null) { Set<ClassInfo> classInfos = index.getAllKnownImplementors(ASYNC_LISTENER_INTERFACE); for (ClassInfo classInfo : classInfos) { if(!Modifier.isAbstract(classInfo.flags()) && !Modifier.isInterface(classInfo.flags())) { classes.add(classInfo.name().toString()); } } } } }
9,673
46.421569
182
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.io.File; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import java.util.function.Supplier; import io.undertow.server.HttpHandler; import io.undertow.servlet.api.Deployment; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import jakarta.servlet.ServletException; import org.jboss.as.web.common.StartupContext; import org.jboss.as.web.common.WebInjectionContainer; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.extension.undertow.Host; import org.wildfly.extension.undertow.ServletContainerService; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class UndertowDeploymentService implements Service<UndertowDeploymentService> { private final Consumer<UndertowDeploymentService> serviceConsumer; private final Supplier<ServletContainerService> container; private final Supplier<ExecutorService> serverExecutor; private final Supplier<Host> host; private final Supplier<DeploymentInfo> deploymentInfo; private final WebInjectionContainer webInjectionContainer; private final boolean autostart; private volatile DeploymentManager deploymentManager; UndertowDeploymentService( final Consumer<UndertowDeploymentService> serviceConsumer, final Supplier<ServletContainerService> container, final Supplier<ExecutorService> serverExecutor, final Supplier<Host> host, final Supplier<DeploymentInfo> deploymentInfo, final WebInjectionContainer webInjectionContainer, final boolean autostart) { this.serviceConsumer = serviceConsumer; this.container = container; this.serverExecutor = serverExecutor; this.host = host; this.deploymentInfo = deploymentInfo; this.webInjectionContainer = webInjectionContainer; this.autostart = autostart; } @Override public void start(final StartContext startContext) throws StartException { if (autostart) { // The start can trigger the web app context initialization which involves blocking tasks like // servlet context initialization, startup servlet initialization lifecycles and such. Hence this needs to be done asynchronously // to prevent the MSC threads from blocking startContext.asynchronous(); serverExecutor.get().submit(new Runnable() { @Override public void run() { try { startContext(); startContext.complete(); } catch (Throwable e) { startContext.failed(new StartException(e)); } } }); } } public void startContext() throws ServletException { final ClassLoader old = Thread.currentThread().getContextClassLoader(); DeploymentInfo deploymentInfo = this.deploymentInfo.get(); Thread.currentThread().setContextClassLoader(deploymentInfo.getClassLoader()); try { StartupContext.setInjectionContainer(webInjectionContainer); try { deploymentManager = container.get().getServletContainer().addDeployment(deploymentInfo); deploymentManager.deploy(); HttpHandler handler = deploymentManager.start(); Deployment deployment = deploymentManager.getDeployment(); host.get().registerDeployment(deployment, handler); } catch (Throwable e ) { deploymentManager.undeploy(); container.get().getServletContainer().removeDeployment(deploymentInfo); throw e; } finally { StartupContext.setInjectionContainer(null); } } finally { Thread.currentThread().setContextClassLoader(old); serviceConsumer.accept(this); } } @Override public void stop(final StopContext stopContext) { // The service stop can trigger the web app context destruction which involves blocking tasks like servlet context destruction, startup servlet // destruction lifecycles and such. Hence this needs to be done asynchronously to prevent the MSC threads from blocking stopContext.asynchronous(); serverExecutor.get().submit(new Runnable() { @Override public void run() { try { stopContext(); } finally { stopContext.complete(); } } }); } public void stopContext() { serviceConsumer.accept(null); final ClassLoader old = Thread.currentThread().getContextClassLoader(); DeploymentInfo deploymentInfo = this.deploymentInfo.get(); Thread.currentThread().setContextClassLoader(deploymentInfo.getClassLoader()); try { if (deploymentManager != null) { Deployment deployment = deploymentManager.getDeployment(); try { host.get().unregisterDeployment(deployment); deploymentManager.stop(); } catch (ServletException e) { throw new RuntimeException(e); } deploymentManager.undeploy(); container.get().getServletContainer().removeDeployment(deploymentInfo); } recursiveDelete(deploymentInfo.getTempDir()); } finally { Thread.currentThread().setContextClassLoader(old); } } @Override public UndertowDeploymentService getValue() throws IllegalStateException, IllegalArgumentException { return this; } public DeploymentInfo getDeploymentInfo() { return deploymentInfo.get(); } public Deployment getDeployment(){ if(this.deploymentManager != null) { return deploymentManager.getDeployment(); } else { return null; } } private static void recursiveDelete(File file) { if(file == null) { return; } File[] files = file.listFiles(); if (files != null){ for(File f : files) { recursiveDelete(f); } } if(!file.delete()) { UndertowLogger.ROOT_LOGGER.couldNotDeleteTempFile(file); } } }
7,760
38.8
151
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/ServletResource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.io.IoCallback; import io.undertow.io.Sender; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.resource.RangeAwareResource; import io.undertow.server.handlers.resource.Resource; import io.undertow.util.ETag; import io.undertow.util.MimeMappings; import java.io.File; import java.net.URL; import java.nio.file.Path; import java.util.Date; import java.util.List; /** * * Resource implementation that wraps an underlying resource, and overrides the list() method to take overlays into account. * * @author Stuart Douglas */ public class ServletResource implements Resource, RangeAwareResource { private final ServletResourceManager resourceManager; private final Resource underlying; public ServletResource(ServletResourceManager resourceManager, Resource underlying) { this.resourceManager = resourceManager; this.underlying = underlying; } @Override public String getPath() { return underlying.getPath(); } @Override public Date getLastModified() { return underlying.getLastModified(); } @Override public String getLastModifiedString() { return underlying.getLastModifiedString(); } @Override public ETag getETag() { return underlying.getETag(); } @Override public String getName() { return underlying.getName(); } @Override public boolean isDirectory() { return underlying.isDirectory(); } @Override public List<Resource> list() { return resourceManager.list(getPath()); } @Override public String getContentType(MimeMappings mimeMappings) { return underlying.getContentType(mimeMappings); } @Override public void serve(Sender sender, HttpServerExchange exchange, IoCallback completionCallback) { underlying.serve(sender, exchange, completionCallback); } @Override public Long getContentLength() { return underlying.getContentLength(); } @Override public String getCacheKey() { return underlying.getCacheKey(); } @Override public File getFile() { return underlying.getFile(); } @Override public File getResourceManagerRoot() { return underlying.getResourceManagerRoot(); } @Override public URL getUrl() { return underlying.getUrl(); } public Path getResourceManagerRootPath() { return getResourceManagerRoot().toPath(); } public Path getFilePath() { if(getFile() == null) { return null; } return getFile().toPath(); } @Override public void serveRange(Sender sender, HttpServerExchange exchange, long start, long end, IoCallback completionCallback) { ((RangeAwareResource) underlying).serveRange(sender, exchange, start, end, completionCallback); } @Override public boolean isRangeSupported() { if(underlying instanceof RangeAwareResource) { return ((RangeAwareResource) underlying).isRangeSupported(); } return false; } }
4,214
27.288591
125
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/JspConfigDescriptorImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagLibraryInfo; import jakarta.servlet.descriptor.JspConfigDescriptor; import jakarta.servlet.descriptor.JspPropertyGroupDescriptor; import jakarta.servlet.descriptor.TaglibDescriptor; import java.util.ArrayList; import java.util.Collection; /** * @author Stuart Douglas */ public class JspConfigDescriptorImpl implements JspConfigDescriptor { private final Collection<TaglibDescriptor> taglibs; private final Collection<JspPropertyGroupDescriptor> jspPropertyGroups; public JspConfigDescriptorImpl(Collection<TagLibraryInfo> taglibs, Collection<JspPropertyGroup> jspPropertyGroups) { this.taglibs = new ArrayList<TaglibDescriptor>(); for(TagLibraryInfo t : taglibs) { this.taglibs.add(new TaglibDescriptorImpl(t)); } this.jspPropertyGroups = new ArrayList<JspPropertyGroupDescriptor>(); for(JspPropertyGroup p : jspPropertyGroups) { this.jspPropertyGroups.add(new JspPropertyGroupDescriptorImpl(p)); } } @Override public Collection<TaglibDescriptor> getTaglibs() { return new ArrayList<TaglibDescriptor>(taglibs); } @Override public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() { return new ArrayList<JspPropertyGroupDescriptor>(jspPropertyGroups); } }
2,465
38.142857
120
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/VirtualFileResource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.UndertowLogger; import io.undertow.io.IoCallback; import io.undertow.io.Sender; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.resource.Resource; import io.undertow.util.DateUtils; import io.undertow.util.ETag; import io.undertow.util.MimeMappings; import org.jboss.vfs.VirtualFile; import org.xnio.FileAccess; import org.xnio.IoUtils; import org.xnio.Pooled; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author Stuart Douglas */ public class VirtualFileResource implements Resource { private final File resourceManagerRoot; private final VirtualFile file; private final String path; public VirtualFileResource(File resourceManagerRoot, final VirtualFile file, String path) { this.resourceManagerRoot = resourceManagerRoot; this.file = file; this.path = path; } @Override public String getPath() { return path; } @Override public Date getLastModified() { return new Date(file.getLastModified()); } @Override public String getLastModifiedString() { final Date lastModified = getLastModified(); if (lastModified == null) { return null; } return DateUtils.toDateString(lastModified); } @Override public ETag getETag() { return null; } @Override public String getName() { return file.getName(); } @Override public boolean isDirectory() { return file.isDirectory(); } @Override public List<Resource> list() { final List<Resource> resources = new ArrayList<Resource>(); for (VirtualFile child : file.getChildren()) { resources.add(new VirtualFileResource(resourceManagerRoot, child, path)); } return resources; } @Override public String getContentType(final MimeMappings mimeMappings) { final String fileName = file.getName(); int index = fileName.lastIndexOf('.'); if (index != -1 && index != fileName.length() - 1) { return mimeMappings.getMimeType(fileName.substring(index + 1)); } return null; } @Override public void serve(final Sender sender, final HttpServerExchange exchange, final IoCallback callback) { abstract class BaseFileTask implements Runnable { protected volatile FileChannel fileChannel; protected boolean openFile() { try { fileChannel = exchange.getConnection().getWorker().getXnio().openFile(file.getPhysicalFile(), FileAccess.READ_ONLY); } catch (FileNotFoundException e) { exchange.setResponseCode(404); callback.onException(exchange, sender, e); return false; } catch (IOException e) { exchange.setResponseCode(500); callback.onException(exchange, sender, e); return false; } return true; } } class ServerTask extends BaseFileTask implements IoCallback { private Pooled<ByteBuffer> pooled; @Override public void run() { if (fileChannel == null) { if (!openFile()) { return; } pooled = exchange.getConnection().getBufferPool().allocate(); } if (pooled != null) { ByteBuffer buffer = pooled.getResource(); try { buffer.clear(); int res = fileChannel.read(buffer); if (res == -1) { //we are done pooled.free(); IoUtils.safeClose(fileChannel); callback.onComplete(exchange, sender); return; } buffer.flip(); sender.send(buffer, this); } catch (IOException e) { onException(exchange, sender, e); } } } @Override public void onComplete(final HttpServerExchange exchange, final Sender sender) { if (exchange.isInIoThread()) { exchange.dispatch(this); } else { run(); } } @Override public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) { UndertowLogger.REQUEST_IO_LOGGER.ioException(exception); if (pooled != null) { pooled.free(); pooled = null; } IoUtils.safeClose(fileChannel); if (!exchange.isResponseStarted()) { exchange.setResponseCode(500); } callback.onException(exchange, sender, exception); } } class TransferTask extends BaseFileTask { @Override public void run() { if (!openFile()) { return; } sender.transferFrom(fileChannel, new IoCallback() { @Override public void onComplete(HttpServerExchange exchange, Sender sender) { try { IoUtils.safeClose(fileChannel); } finally { callback.onComplete(exchange, sender); } } @Override public void onException(HttpServerExchange exchange, Sender sender, IOException exception) { try { IoUtils.safeClose(fileChannel); } finally { callback.onException(exchange, sender, exception); } } }); } } BaseFileTask task = new TransferTask(); if (exchange.isInIoThread()) { exchange.dispatch(task); } else { task.run(); } } @Override public Long getContentLength() { return file.getSize(); } @Override public String getCacheKey() { return file.toString(); } @Override public File getFile() { try { return file.getPhysicalFile(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public File getResourceManagerRoot() { return resourceManagerRoot; } @Override public URL getUrl() { try { return file.toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public Path getResourceManagerRootPath() { return getResourceManagerRoot().toPath(); } public Path getFilePath() { if(getFile() == null) { return null; } return getFile().toPath(); } }
8,676
30.32491
136
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/WarDeploymentInitializingProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.Locale; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; /** * Processor that marks a war deployment. * * @author John Bailey * @author [email protected] */ public class WarDeploymentInitializingProcessor implements DeploymentUnitProcessor { public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); String deploymentName = deploymentUnit.getName().toLowerCase(Locale.ENGLISH); if (deploymentName.endsWith(".war")) { DeploymentTypeMarker.setType(DeploymentType.WAR, deploymentUnit); } } }
2,069
40.4
108
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/TldsMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.List; import java.util.Map; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.web.common.SharedTldsMetaDataBuilder; import org.jboss.metadata.web.spec.TldMetaData; /** * @author Remy Maucherat */ public class TldsMetaData { public static final AttachmentKey<TldsMetaData> ATTACHMENT_KEY = AttachmentKey.create(TldsMetaData.class); /** * Shared TLDs. */ private SharedTldsMetaDataBuilder sharedTlds; /** * Webapp TLDs. */ private Map<String, TldMetaData> tlds; public List<TldMetaData> getSharedTlds(DeploymentUnit deploymentUnit) { return sharedTlds.getSharedTlds(deploymentUnit); } public void setSharedTlds(SharedTldsMetaDataBuilder sharedTlds) { this.sharedTlds = sharedTlds; } public Map<String, TldMetaData> getTlds() { return tlds; } public void setTlds(Map<String, TldMetaData> tlds) { this.tlds = tlds; } }
2,101
30.373134
110
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDependencyProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoader; /** * Module dependencies processor. * * @author Emanuel Muckenhuber * @author Stan Silvert */ public class UndertowDependencyProcessor implements DeploymentUnitProcessor { private static final String JSTL = "jakarta.servlet.jstl.api"; private static final String UNDERTOW_CORE = "io.undertow.core"; private static final String UNDERTOW_SERVLET = "io.undertow.servlet"; private static final String UNDERTOW_JSP = "io.undertow.jsp"; private static final String UNDERTOW_WEBSOCKET = "io.undertow.websocket"; private static final String SERVLET_API = "jakarta.servlet.api"; private static final String JSP_API = "jakarta.servlet.jsp.api"; private static final String WEBSOCKET_API = "jakarta.websocket.api"; static { Module module = Module.forClass(UndertowDependencyProcessor.class); if (module != null) { //When testing the subsystems we are running in a non-modular environment //so module will be null. Having a null entry kills ModularURLStreamHandlerFactory Module.registerURLStreamHandlerFactoryModule(module); } } @Override public void deploy(DeploymentPhaseContext phaseContext) { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); //add the api classes for every deployment moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, SERVLET_API, false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, JSP_API, false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, WEBSOCKET_API, false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, JSTL, false, false, false, false)); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, UNDERTOW_CORE, false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, UNDERTOW_SERVLET, false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, UNDERTOW_JSP, false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, UNDERTOW_WEBSOCKET, false, false, true, false)); } }
4,297
48.402299
131
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/RewriteCorrectingHandlerWrappers.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.servlet.handlers.ServletPathMatch; import io.undertow.servlet.handlers.ServletRequestContext; import io.undertow.util.AttachmentKey; /** * Handler that works around issues with rewrites() and undertow-handlers.conf. * <p> * Because the rewrite happens after the initial dispatch this handler detects if * the path has been rewritten and updates the servlet target. * * This is a bit of a hack, it needs a lot more thinking about a clean way to handle * this */ class RewriteCorrectingHandlerWrappers { private static final AttachmentKey<String> OLD_RELATIVE_PATH = AttachmentKey.create(String.class); static class PreWrapper implements HandlerWrapper { @Override public HttpHandler wrap(final HttpHandler handler) { return new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.putAttachment(OLD_RELATIVE_PATH, exchange.getRelativePath()); handler.handleRequest(exchange); } }; } } static class PostWrapper implements HandlerWrapper { @Override public HttpHandler wrap(final HttpHandler handler) { return new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { String old = exchange.getAttachment(OLD_RELATIVE_PATH); if(!old.equals(exchange.getRelativePath())) { ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); ServletPathMatch info = src.getDeployment().getServletPaths().getServletHandlerByPath(exchange.getRelativePath()); src.setCurrentServlet(info.getServletChain()); src.setServletPathMatch(info); } handler.handleRequest(exchange); } }; } } }
3,260
41.350649
138
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowJSPInstanceManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.lang.reflect.InvocationTargetException; import javax.naming.NamingException; import org.apache.jasper.runtime.HttpJspBase; import org.apache.tomcat.InstanceManager; import org.jboss.as.web.common.WebInjectionContainer; /** * * InstanceManager is evil and needs to go away * * * We don't use web injection container for instances of org.apache.jasper.runtime.HttpJspBase, as it causes problems * with Jakarta Server Pages hot reload. Because a new Jakarta Server Pages class has the same name the generated ID is exactly the same. * * * @author Stuart Douglas */ public class UndertowJSPInstanceManager implements InstanceManager { private final WebInjectionContainer webInjectionContainer; public UndertowJSPInstanceManager(final WebInjectionContainer webInjectionContainer) { this.webInjectionContainer = webInjectionContainer; } @Override public Object newInstance(final String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { return webInjectionContainer.newInstance(className); } @Override public Object newInstance(final String fqcn, final ClassLoader classLoader) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { return newInstance(classLoader.loadClass(fqcn)); } @Override public Object newInstance(final Class<?> c) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException { if(HttpJspBase.class.isAssignableFrom(c)) { return c.newInstance(); } return webInjectionContainer.newInstance(c); } @Override public void newInstance(final Object o) throws IllegalAccessException, InvocationTargetException, NamingException { if(o instanceof HttpJspBase) { return; } webInjectionContainer.newInstance(o); } @Override public void destroyInstance(final Object o) throws IllegalAccessException, InvocationTargetException { if(o instanceof HttpJspBase) { return; } webInjectionContainer.destroyInstance(o); } }
3,321
37.627907
203
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowMetricsCollector.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.HashMap; import java.util.Map; import io.undertow.server.handlers.MetricsHandler; import io.undertow.servlet.api.MetricsCollector; /** * @author Tomaz Cerar (c) 2014 Red Hat Inc. */ public class UndertowMetricsCollector implements MetricsCollector { private final Map<String, MetricsHandler> metrics = new HashMap<>(); @Override public void registerMetric(String name, MetricsHandler handler) { metrics.put(name, handler); } public MetricsHandler.MetricResult getMetrics(String name) { if (metrics.containsKey(name)) { return metrics.get(name).getMetrics(); } return null; } }
1,744
34.612245
72
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/WebFragmentParsingDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.ee.structure.SpecDescriptorPropertyReplacement; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.parser.servlet.WebFragmentMetaDataParser; import org.jboss.metadata.parser.util.NoopXMLResolver; import org.jboss.metadata.web.spec.WebFragmentMetaData; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author Remy Maucherat */ public class WebFragmentParsingDeploymentProcessor implements DeploymentUnitProcessor { private static final String WEB_FRAGMENT_XML = "META-INF/web-fragment.xml"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); assert warMetaData != null; Map<String, WebFragmentMetaData> webFragments = warMetaData.getWebFragmentsMetaData(); if (webFragments == null) { webFragments = new HashMap<String, WebFragmentMetaData>(); warMetaData.setWebFragmentsMetaData(webFragments); } List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS); for (ResourceRoot resourceRoot : resourceRoots) { if (resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { VirtualFile webFragment = resourceRoot.getRoot().getChild(WEB_FRAGMENT_XML); if (webFragment.exists() && webFragment.isFile()) { InputStream is = null; try { is = webFragment.openStream(); final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setXMLResolver(NoopXMLResolver.create()); XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is); WebFragmentMetaData webFragmentMetaData = WebFragmentMetaDataParser.parse(xmlReader, SpecDescriptorPropertyReplacement.propertyReplacer(deploymentUnit)); webFragments.put(resourceRoot.getRootName(), webFragmentMetaData); /*Log message to inform that distributable is not set in web-fragment.xml while it is set in web.xml*/ if (warMetaData.getWebMetaData() != null && warMetaData.getWebMetaData().getDistributable()!= null && webFragmentMetaData.getDistributable() == null) UndertowLogger.ROOT_LOGGER.distributableDisabledInFragmentXml(deploymentUnit.getName(),resourceRoot.getRootName()); } catch (XMLStreamException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(webFragment.toString(), e.getLocation().getLineNumber(), e.getLocation().getColumnNumber())); } catch (IOException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(webFragment.toString()), e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } } } } } } }
5,505
50.457944
213
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowHandlersDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.server.handlers.builder.PredicatedHandler; import io.undertow.server.handlers.builder.PredicatedHandlersParser; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.web.jboss.HttpHandlerMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.undertow.logging.UndertowLogger; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; /** * DUP that handles undertow-handlers.conf, and handlers definded in jboss-web.xml * * @author Stuart Douglas */ public class UndertowHandlersDeploymentProcessor implements DeploymentUnitProcessor { private static final String WEB_INF = "WEB-INF/undertow-handlers.conf"; private static final String META_INF = "META-INF/undertow-handlers.conf"; public static final AttachmentKey<List<PredicatedHandler>> PREDICATED_HANDLERS = AttachmentKey.create(List.class); @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if (module == null) { return; } handleInfoFile(deploymentUnit, module); handleJbossWebXml(deploymentUnit, module); } private void handleJbossWebXml(DeploymentUnit deploymentUnit, Module module) throws DeploymentUnitProcessingException { WarMetaData warMetadata = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetadata == null) { return; } JBossWebMetaData merged = warMetadata.getMergedJBossWebMetaData(); if (merged == null) { return; } List<HttpHandlerMetaData> handlers = merged.getHandlers(); if (handlers == null) { return; } for (HttpHandlerMetaData hander : handlers) { try { ClassLoader cl = module.getClassLoader(); if (hander.getModule() != null) { Module handlerModule = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER).loadModule(ModuleIdentifier.fromString(hander.getModule())); cl = handlerModule.getClassLoader(); } Class<?> handlerClass = cl.loadClass(hander.getHandlerClass()); Map<String, String> params = new HashMap<>(); if(hander.getParams() != null) { for(ParamValueMetaData param : hander.getParams()) { params.put(param.getParamName(), param.getParamValue()); } } deploymentUnit.addToAttachmentList(UndertowAttachments.UNDERTOW_OUTER_HANDLER_CHAIN_WRAPPERS, new ConfiguredHandlerWrapper(handlerClass, params)); } catch (Exception e) { throw UndertowLogger.ROOT_LOGGER.failedToConfigureHandlerClass(hander.getHandlerClass(), e); } } } private void handleInfoFile(DeploymentUnit deploymentUnit, Module module) { final List<PredicatedHandler> handlerWrappers = new ArrayList<>(); ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); VirtualFile config = root.getRoot().getChild(WEB_INF); try { if (config.exists()) { handlerWrappers.addAll(PredicatedHandlersParser.parse(config.openStream(), module.getClassLoader())); } Enumeration<URL> paths = module.getClassLoader().getResources(META_INF); while (paths.hasMoreElements()) { URL path = paths.nextElement(); handlerWrappers.addAll(PredicatedHandlersParser.parse(path.openStream(), module.getClassLoader())); } } catch (IOException e) { throw new RuntimeException(e); } if (!handlerWrappers.isEmpty()) { deploymentUnit.putAttachment(PREDICATED_HANDLERS, handlerWrappers); } } finally { Thread.currentThread().setContextClassLoader(oldCl); } } }
6,075
43.676471
167
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/ImmediateSessionManagerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.server.session.SessionManager; import io.undertow.servlet.api.Deployment; import io.undertow.servlet.api.SessionManagerFactory; /** * @author Stuart Douglas */ public class ImmediateSessionManagerFactory implements SessionManagerFactory{ private final SessionManager sessionManager; public ImmediateSessionManagerFactory(SessionManager sessionManager) { this.sessionManager = sessionManager; } @Override public SessionManager createSessionManager(Deployment deployment) { return sessionManager; } }
1,640
35.466667
77
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/DeploymentRootExplodedMountProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.Locale; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.MountExplodedMarker; /** * Processor that marks a deployment as exploded. * * @author [email protected] * @since 05-Oct-2011 */ public class DeploymentRootExplodedMountProcessor implements DeploymentUnitProcessor { private static final String WAR_EXTENSION = ".war"; public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit depUnit = phaseContext.getDeploymentUnit(); String depName = depUnit.getName().toLowerCase(Locale.ENGLISH); if (depName.endsWith(WAR_EXTENSION)) { MountExplodedMarker.setMountExploded(depUnit); } } }
2,051
39.235294
108
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SharedSessionManagerDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.time.Duration; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; import java.util.function.Function; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.common.WarMetaData; import org.jboss.as.web.session.SharedSessionManagerConfig; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.metadata.web.spec.SessionConfigMetaData; import org.wildfly.clustering.web.container.SessionManagementProvider; import org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration; import org.wildfly.extension.undertow.ServletContainerService; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.session.NonDistributableSessionManagementProvider; import org.wildfly.extension.undertow.session.SessionManagementProviderFactory; import io.undertow.server.session.InMemorySessionManager; import io.undertow.servlet.api.SessionManagerFactory; /** * @author Stuart Douglas */ public class SharedSessionManagerDeploymentProcessor implements DeploymentUnitProcessor, Function<SessionManagerFactoryConfiguration, SessionManagerFactory> { private final String defaultServerName; private final SessionManagementProviderFactory sessionManagementProviderFactory; private final SessionManagementProvider nonDistributableSessionManagementProvider; public SharedSessionManagerDeploymentProcessor(String defaultServerName) { this.defaultServerName = defaultServerName; Iterator<SessionManagementProviderFactory> factories = ServiceLoader.load(SessionManagementProviderFactory.class, SessionManagementProviderFactory.class.getClassLoader()).iterator(); this.sessionManagementProviderFactory = factories.hasNext() ? factories.next() : null; this.nonDistributableSessionManagementProvider = new NonDistributableSessionManagementProvider(this); } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); SharedSessionManagerConfig sharedConfig = deploymentUnit.getAttachment(SharedSessionManagerConfig.ATTACHMENT_KEY); if (sharedConfig == null) return; String deploymentName = (deploymentUnit.getParent() == null) ? deploymentUnit.getName() : String.join(".", deploymentUnit.getParent().getName(), deploymentUnit.getName()); WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); String serverName = Optional.ofNullable(warMetaData).map(metaData -> metaData.getMergedJBossWebMetaData().getServerInstanceName()) .orElse(Optional.ofNullable(DefaultDeploymentMappingProvider.instance().getMapping(deploymentName)).map(Map.Entry::getKey).orElse(this.defaultServerName)); SessionConfigMetaData sessionConfig = sharedConfig.getSessionConfig(); ServletContainerService servletContainer = deploymentUnit.getAttachment(UndertowAttachments.SERVLET_CONTAINER_SERVICE); Integer defaultSessionTimeout = ((sessionConfig != null) && sessionConfig.getSessionTimeoutSet()) ? sessionConfig.getSessionTimeout() : (servletContainer != null) ? servletContainer.getDefaultSessionTimeout() : Integer.valueOf(30); CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); ServiceTarget target = phaseContext.getServiceTarget(); ServiceName deploymentServiceName = deploymentUnit.getServiceName(); ServiceName managerServiceName = deploymentServiceName.append(SharedSessionManagerConfig.SHARED_SESSION_MANAGER_SERVICE_NAME); ServiceName affinityServiceName = deploymentServiceName.append(SharedSessionManagerConfig.SHARED_SESSION_AFFINITY_SERVICE_NAME); SessionManagementProvider provider = this.getDistributableWebDeploymentProvider(deploymentUnit, sharedConfig); SessionManagerFactoryConfiguration configuration = new SessionManagerFactoryConfiguration() { @Override public String getServerName() { return serverName; } @Override public String getDeploymentName() { return deploymentName; } @Override public Integer getMaxActiveSessions() { return sharedConfig.getMaxActiveSessions(); } @Override public DeploymentUnit getDeploymentUnit() { return deploymentUnit; } @Override public Duration getDefaultSessionTimeout() { return Duration.ofMinutes(defaultSessionTimeout); } }; for (CapabilityServiceConfigurator configurator : provider.getSessionManagerFactoryServiceConfigurators(managerServiceName, configuration)) { configurator.configure(support).build(target).install(); } for (CapabilityServiceConfigurator configurator : provider.getSessionAffinityServiceConfigurators(affinityServiceName, configuration)) { configurator.configure(support).build(target).install(); } } @SuppressWarnings("deprecation") private SessionManagementProvider getDistributableWebDeploymentProvider(DeploymentUnit unit, SharedSessionManagerConfig config) { if (config.isDistributable()) { if (this.sessionManagementProviderFactory != null) { return this.sessionManagementProviderFactory.createSessionManagementProvider(unit, config.getReplicationConfig()); } // Fallback to non-distributable session manager if server does not support clustering UndertowLogger.ROOT_LOGGER.clusteringNotSupported(); } return this.nonDistributableSessionManagementProvider; } @Override public SessionManagerFactory apply(SessionManagerFactoryConfiguration configuration) { String deploymentName = configuration.getDeploymentName(); Integer maxActiveSessions = configuration.getMaxActiveSessions(); InMemorySessionManager manager = (maxActiveSessions != null) ? new InMemorySessionManager(deploymentName, maxActiveSessions.intValue()) : new InMemorySessionManager(deploymentName); manager.setDefaultSessionTimeout((int) configuration.getDefaultSessionTimeout().getSeconds()); return new ImmediateSessionManagerFactory(manager); } }
8,003
53.821918
239
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/DefaultSecurityDomainProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; public class DefaultSecurityDomainProcessor implements DeploymentUnitProcessor { private String defaultSecurityDomain; public DefaultSecurityDomainProcessor(String securityDomain) { defaultSecurityDomain = securityDomain; } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { phaseContext.getDeploymentUnit().putAttachment(UndertowAttachments.DEFAULT_SECURITY_DOMAIN, defaultSecurityDomain); } @Override public void undeploy(DeploymentUnit context) { context.removeAttachment(UndertowAttachments.DEFAULT_SECURITY_DOMAIN); } }
1,975
41.042553
123
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import static org.jboss.as.ee.component.Attachments.STARTUP_COUNTDOWN; import static org.jboss.as.server.security.SecurityMetaData.ATTACHMENT_KEY; import static org.jboss.as.server.security.VirtualDomainMarkerUtility.isVirtualDomainRequired; import static org.jboss.as.web.common.VirtualHttpServerMechanismFactoryMarkerUtility.isVirtualMechanismFactoryRequired; import static org.wildfly.extension.undertow.Capabilities.REF_LEGACY_SECURITY; import static org.wildfly.extension.undertow.logging.UndertowLogger.ROOT_LOGGER; import java.net.MalformedURLException; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import jakarta.security.jacc.PolicyConfiguration; import io.undertow.servlet.api.SessionConfigWrapper; import org.apache.jasper.Constants; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.TagAttributeInfo; import org.apache.jasper.deploy.TagFileInfo; import org.apache.jasper.deploy.TagInfo; import org.apache.jasper.deploy.TagLibraryInfo; import org.apache.jasper.deploy.TagLibraryValidatorInfo; import org.apache.jasper.deploy.TagVariableInfo; import org.jboss.annotation.javaee.Icon; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.ee.component.ComponentRegistry; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.deployers.StartupCountdown; import org.jboss.as.ee.security.JaccService; import org.jboss.as.server.ServerEnvironment; import org.jboss.as.server.ServerEnvironmentService; import org.jboss.as.server.Services; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentResourceSupport; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.ExplodedDeploymentMarker; import org.jboss.as.server.deployment.SetupAction; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.server.security.AdvancedSecurityMetaData; import org.jboss.as.server.security.SecurityMetaData; import org.jboss.as.server.suspend.SuspendController; import org.jboss.as.web.common.CachingWebInjectionContainer; import org.jboss.as.web.common.ExpressionFactoryWrapper; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.as.web.common.SimpleWebInjectionContainer; import org.jboss.as.web.common.WarMetaData; import org.jboss.as.web.common.WebComponentDescription; import org.jboss.as.web.common.WebInjectionContainer; import org.jboss.as.web.session.SharedSessionManagerConfig; import org.jboss.dmr.ModelNode; import org.jboss.metadata.javaee.jboss.RunAsIdentityMetaData; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.AttributeMetaData; import org.jboss.metadata.web.spec.FunctionMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.SessionConfigMetaData; import org.jboss.metadata.web.spec.TagFileMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.VariableMetaData; import org.jboss.modules.Module; import org.jboss.msc.service.DuplicateServiceException; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.vfs.VirtualFile; import org.wildfly.clustering.web.container.SessionManagementProvider; import org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration; import org.wildfly.common.function.Functions; import org.wildfly.extension.io.IOServices; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.requestcontroller.ControlPointService; import org.wildfly.extension.requestcontroller.RequestControllerActivationMarker; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.CookieConfig; import org.wildfly.extension.undertow.DeploymentDefinition; import org.wildfly.extension.undertow.Host; import org.wildfly.extension.undertow.ServletContainerService; import org.wildfly.extension.undertow.UndertowExtension; import org.wildfly.extension.undertow.UndertowService; import org.wildfly.extension.undertow.ApplicationSecurityDomainDefinition.Registration; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.security.jacc.WarJACCDeployer; import org.wildfly.extension.undertow.session.NonDistributableSessionManagementProvider; import org.wildfly.extension.undertow.session.SessionManagementProviderFactory; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.http.HttpServerAuthenticationMechanismFactory; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.SessionManagerFactory; import io.undertow.servlet.core.InMemorySessionManagerFactory; /** * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class UndertowDeploymentProcessor implements DeploymentUnitProcessor, Function<SessionManagerFactoryConfiguration, SessionManagerFactory> { public static final String OLD_URI_PREFIX = "http://java.sun.com"; public static final String NEW_URI_PREFIX = "http://xmlns.jcp.org"; private static final String LEGACY_JACC_CAPABILITY_NAME = "org.wildfly.legacy-security.jacc"; private static final String ELYTRON_JACC_CAPABILITY_NAME = "org.wildfly.security.jacc-policy"; private final String defaultServer; private final String defaultHost; private final String defaultContainer; private final Predicate<String> mappedSecurityDomain; /** default module mappings, where we have key as name of default deployment, for value we have Map.Entry which has key as server-name where deployment is bound to, value is host name where deployment is bound to. */ private final DefaultDeploymentMappingProvider defaultModuleMappingProvider; private final SessionManagementProviderFactory sessionManagementProviderFactory; private final SessionManagementProvider nonDistributableSessionManagementProvider; public UndertowDeploymentProcessor(String defaultHost, final String defaultContainer, String defaultServer, Predicate<String> mappedSecurityDomain) { this.defaultHost = defaultHost; this.defaultModuleMappingProvider = DefaultDeploymentMappingProvider.instance(); if (defaultHost == null) { throw UndertowLogger.ROOT_LOGGER.nullDefaultHost(); } this.defaultContainer = defaultContainer; this.defaultServer = defaultServer; this.mappedSecurityDomain = mappedSecurityDomain; Iterator<SessionManagementProviderFactory> factories = ServiceLoader.load(SessionManagementProviderFactory.class, SessionManagementProviderFactory.class.getClassLoader()).iterator(); this.sessionManagementProviderFactory = factories.hasNext() ? factories.next() : null; this.nonDistributableSessionManagementProvider = new NonDistributableSessionManagementProvider(this); } @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); DeploymentUnit parentDeploymentUnit = deploymentUnit.getParent(); //install the control point for the top level deployment no matter what if (RequestControllerActivationMarker.isRequestControllerEnabled(deploymentUnit) && parentDeploymentUnit == null) { ControlPointService.install(phaseContext.getServiceTarget(), deploymentUnit.getName(), UndertowExtension.SUBSYSTEM_NAME); } final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData == null) { return; } String deploymentName = (parentDeploymentUnit != null) ? String.join(".", List.of(parentDeploymentUnit.getName(), deploymentUnit.getName())) : deploymentUnit.getName(); final Map.Entry<String,String> serverHost = defaultModuleMappingProvider.getMapping(deploymentName); String defaultHostForDeployment; String defaultServerForDeployment; if (serverHost != null) { defaultServerForDeployment = serverHost.getKey(); defaultHostForDeployment = serverHost.getValue(); } else { defaultServerForDeployment = this.defaultServer; defaultHostForDeployment = this.defaultHost; } String serverInstanceName = warMetaData.getMergedJBossWebMetaData().getServerInstanceName() == null ? defaultServerForDeployment : warMetaData.getMergedJBossWebMetaData().getServerInstanceName(); String hostName = hostNameOfDeployment(warMetaData, defaultHostForDeployment); // flag if the app is the default web module for the server/host boolean isDefaultWebModule = serverHost != null && serverInstanceName.equals(defaultServerForDeployment) && hostName.equals(defaultHostForDeployment); processDeployment(warMetaData, deploymentUnit, phaseContext.getServiceTarget(), deploymentName, hostName, serverInstanceName, isDefaultWebModule); } private String hostNameOfDeployment(final WarMetaData metaData, String defaultHost) { Collection<String> hostNames = null; if (metaData.getMergedJBossWebMetaData() != null) { hostNames = metaData.getMergedJBossWebMetaData().getVirtualHosts(); } if (hostNames == null || hostNames.isEmpty()) { hostNames = Collections.singleton(defaultHost); } String hostName = hostNames.iterator().next(); if (hostName == null) { throw UndertowLogger.ROOT_LOGGER.nullHostName(); } return hostName; } private void processDeployment(final WarMetaData warMetaData, final DeploymentUnit deploymentUnit, final ServiceTarget serviceTarget, final String deploymentName, final String hostName, final String serverInstanceName, final boolean isDefaultWebModule) throws DeploymentUnitProcessingException { ResourceRoot deploymentResourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); final VirtualFile deploymentRoot = deploymentResourceRoot.getRoot(); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if (module == null) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failedToResolveModule(deploymentUnit)); } final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData(); final List<SetupAction> setupActions = deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS); CapabilityServiceSupport capabilitySupport = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); ScisMetaData scisMetaData = deploymentUnit.getAttachment(ScisMetaData.ATTACHMENT_KEY); final Set<ServiceName> dependentComponents = new HashSet<>(); // see AS7-2077 // basically we want to ignore components that have failed for whatever reason // if they are important they will be picked up when the web deployment actually starts final List<ServiceName> components = deploymentUnit.getAttachmentList(WebComponentDescription.WEB_COMPONENTS); final Set<ServiceName> failed = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.FAILED_COMPONENTS); for (final ServiceName component : components) { if (!failed.contains(component)) { dependentComponents.add(component); } } String servletContainerName = Optional.ofNullable(metaData.getServletContainerName()).orElse(this.defaultContainer); final boolean componentRegistryExists = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.COMPONENT_REGISTRY) != null; final ComponentRegistry componentRegistry = componentRegistryExists ? deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.COMPONENT_REGISTRY) : new ComponentRegistry(null); final ClassLoader loader = module.getClassLoader(); final WebInjectionContainer injectionContainer = (metaData.getDistributable() == null) ? new CachingWebInjectionContainer(loader, componentRegistry) : new SimpleWebInjectionContainer(loader, componentRegistry); DeploymentUnit parentDeploymentUnit = deploymentUnit.getParent(); String jaccContextId = metaData.getJaccContextID(); if (jaccContextId == null) { jaccContextId = deploymentUnit.getName(); } if (parentDeploymentUnit != null) { jaccContextId = parentDeploymentUnit.getName() + "!" + jaccContextId; } String pathName = pathNameOfDeployment(deploymentUnit, metaData, isDefaultWebModule); final Set<ServiceName> additionalDependencies = new HashSet<>(); for (final SetupAction setupAction : setupActions) { Set<ServiceName> dependencies = setupAction.dependencies(); if (dependencies != null) { additionalDependencies.addAll(dependencies); } } if(!deploymentResourceRoot.isUsePhysicalCodeSource()) { try { deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(Constants.CODE_SOURCE_ATTRIBUTE_NAME, deploymentRoot.toURL())); } catch (MalformedURLException e) { throw new DeploymentUnitProcessingException(e); } } deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(Constants.PERMISSION_COLLECTION_ATTRIBUTE_NAME, deploymentUnit.getAttachment(Attachments.MODULE_PERMISSIONS))); additionalDependencies.addAll(warMetaData.getAdditionalDependencies()); final ServiceName hostServiceName = UndertowService.virtualHostName(serverInstanceName, hostName); final ServiceName legacyDeploymentServiceName = UndertowService.deploymentServiceName(serverInstanceName, hostName, pathName); final ServiceName deploymentServiceName = UndertowService.deploymentServiceName(deploymentUnit.getServiceName()); StartupCountdown countDown = deploymentUnit.getAttachment(STARTUP_COUNTDOWN); if (countDown != null) { deploymentUnit.addToAttachmentList(UndertowAttachments.UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS, handler->new ComponentStartupCountdownHandler(handler, countDown)); } String securityDomainName = deploymentUnit.getAttachment(UndertowAttachments.RESOLVED_SECURITY_DOMAIN); TldsMetaData tldsMetaData = deploymentUnit.getAttachment(TldsMetaData.ATTACHMENT_KEY); final ServiceName deploymentInfoServiceName = deploymentServiceName.append(UndertowDeploymentInfoService.SERVICE_NAME); final ServiceName legacyDeploymentInfoServiceName = legacyDeploymentServiceName.append(UndertowDeploymentInfoService.SERVICE_NAME); final ServiceBuilder<?> builder = serviceTarget.addService(deploymentInfoServiceName); final Consumer<DeploymentInfo> deploymentInfo = builder.provides(deploymentInfoServiceName, legacyDeploymentInfoServiceName); final Supplier<UndertowService> undertowService = builder.requires(UndertowService.UNDERTOW); final Supplier<ServletContainerService> servletContainerService = builder.requires(UndertowService.SERVLET_CONTAINER.append(servletContainerName)); final Supplier<ComponentRegistry> componentRegistryDependency = componentRegistryExists ? builder.requires(ComponentRegistry.serviceName(deploymentUnit)) : Functions.constantSupplier(componentRegistry); final Supplier<Host> host = builder.requires(hostServiceName); final Supplier<SuspendController> suspendController = builder.requires(capabilitySupport.getCapabilityServiceName(Capabilities.REF_SUSPEND_CONTROLLER)); final Supplier<ServerEnvironment> serverEnvironment = builder.requires(ServerEnvironmentService.SERVICE_NAME); Supplier<SecurityDomain> securityDomain = null; Supplier<HttpServerAuthenticationMechanismFactory> mechanismFactorySupplier = null; Supplier<BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration>> applySecurityFunction = null; for (final ServiceName additionalDependency : additionalDependencies) { builder.requires(additionalDependency); } final SecurityMetaData securityMetaData = deploymentUnit.getAttachment(ATTACHMENT_KEY); if (isVirtualDomainRequired(deploymentUnit) || isVirtualMechanismFactoryRequired(deploymentUnit)) { securityDomain = builder.requires(securityMetaData.getSecurityDomain()); } else if(securityDomainName != null) { if (mappedSecurityDomain.test(securityDomainName)) { applySecurityFunction = builder.requires(capabilitySupport.getCapabilityServiceName(Capabilities.CAPABILITY_APPLICATION_SECURITY_DOMAIN, securityDomainName)); } else { throw ROOT_LOGGER.deploymentConfiguredForLegacySecurity(); } } if (isVirtualMechanismFactoryRequired(deploymentUnit)) { if (securityMetaData instanceof AdvancedSecurityMetaData) { mechanismFactorySupplier = builder.requires(((AdvancedSecurityMetaData) securityMetaData).getHttpServerAuthenticationMechanismFactory()); } } Supplier<ControlPoint> controlPoint = RequestControllerActivationMarker.isRequestControllerEnabled(deploymentUnit) ? builder.requires(ControlPointService.serviceName(Optional.ofNullable(parentDeploymentUnit).orElse(deploymentUnit).getName(), UndertowExtension.SUBSYSTEM_NAME)) : null; SharedSessionManagerConfig sharedSessionManagerConfig = parentDeploymentUnit != null ? parentDeploymentUnit.getAttachment(SharedSessionManagerConfig.ATTACHMENT_KEY) : null; ServiceName sessionManagerFactoryServiceName = (sharedSessionManagerConfig != null) ? parentDeploymentUnit.getServiceName().append(SharedSessionManagerConfig.SHARED_SESSION_MANAGER_SERVICE_NAME) : deploymentServiceName.append("session"); ServiceName sessionConfigWrapperFactoryServiceName = (sharedSessionManagerConfig != null) ? parentDeploymentUnit.getServiceName().append(SharedSessionManagerConfig.SHARED_SESSION_AFFINITY_SERVICE_NAME) : deploymentServiceName.append("affinity"); ServletContainerService servletContainer = deploymentUnit.getAttachment(UndertowAttachments.SERVLET_CONTAINER_SERVICE); Supplier<SessionManagerFactory> sessionManagerFactory = (servletContainer != null) ? builder.requires(sessionManagerFactoryServiceName) : null; Supplier<Function<CookieConfig, SessionConfigWrapper>> sessionConfigWrapperFactory = (servletContainer != null) ? builder.requires(sessionConfigWrapperFactoryServiceName) : null; if ((servletContainer != null) && (sharedSessionManagerConfig == null)) { Integer maxActiveSessions = (metaData.getMaxActiveSessions() != null) ? metaData.getMaxActiveSessions() : servletContainer.getMaxSessions(); SessionConfigMetaData sessionConfig = metaData.getSessionConfig(); int defaultSessionTimeout = ((sessionConfig != null) && sessionConfig.getSessionTimeoutSet()) ? sessionConfig.getSessionTimeout() : servletContainer.getDefaultSessionTimeout(); SessionManagementProvider provider = this.getDistributableWebDeploymentProvider(deploymentUnit, metaData); SessionManagerFactoryConfiguration configuration = new SessionManagerFactoryConfiguration() { @Override public String getServerName() { return serverInstanceName; } @Override public String getDeploymentName() { return deploymentName; } @Override public DeploymentUnit getDeploymentUnit() { return deploymentUnit; } @Override public Integer getMaxActiveSessions() { return maxActiveSessions; } @Override public Duration getDefaultSessionTimeout() { return Duration.ofMinutes(defaultSessionTimeout); } }; for (CapabilityServiceConfigurator configurator : provider.getSessionManagerFactoryServiceConfigurators(sessionManagerFactoryServiceName, configuration)) { configurator.configure(capabilitySupport).build(serviceTarget).install(); } for (CapabilityServiceConfigurator configurator : provider.getSessionAffinityServiceConfigurators(sessionConfigWrapperFactoryServiceName, configuration)) { configurator.configure(capabilitySupport).build(serviceTarget).install(); } } UndertowDeploymentInfoService undertowDeploymentInfoService = UndertowDeploymentInfoService.builder() .setAttributes(deploymentUnit.getAttachmentList(ServletContextAttribute.ATTACHMENT_KEY)) .setContextPath(pathName) .setDeploymentName(deploymentName) //todo: is this deployment name concept really applicable? .setDeploymentRoot(deploymentRoot) .setMergedMetaData(warMetaData.getMergedJBossWebMetaData()) .setModule(module) .setScisMetaData(scisMetaData) .setJaccContextId(jaccContextId) .setSecurityDomain(securityDomainName) .setTldInfo(createTldsInfo(tldsMetaData, tldsMetaData == null ? null : tldsMetaData.getSharedTlds(deploymentUnit))) .setSetupActions(setupActions) .setSharedSessionManagerConfig(sharedSessionManagerConfig) .setOverlays(warMetaData.getOverlays()) .setExpressionFactoryWrappers(deploymentUnit.getAttachmentList(ExpressionFactoryWrapper.ATTACHMENT_KEY)) .setPredicatedHandlers(deploymentUnit.getAttachment(UndertowHandlersDeploymentProcessor.PREDICATED_HANDLERS)) .setInitialHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS)) .setInnerHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_INNER_HANDLER_CHAIN_WRAPPERS)) .setOuterHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_OUTER_HANDLER_CHAIN_WRAPPERS)) .setThreadSetupActions(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_THREAD_SETUP_ACTIONS)) .setServletExtensions(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_SERVLET_EXTENSIONS)) .setExplodedDeployment(ExplodedDeploymentMarker.isExplodedDeployment(deploymentUnit)) .setWebSocketDeploymentInfo(deploymentUnit.getAttachment(UndertowAttachments.WEB_SOCKET_DEPLOYMENT_INFO)) .setTempDir(warMetaData.getTempDir()) .setExternalResources(deploymentUnit.getAttachmentList(UndertowAttachments.EXTERNAL_RESOURCES)) .setAllowSuspendedRequests(deploymentUnit.getAttachmentList(UndertowAttachments.ALLOW_REQUEST_WHEN_SUSPENDED)) .createUndertowDeploymentInfoService(deploymentInfo, undertowService, sessionManagerFactory, sessionConfigWrapperFactory, servletContainerService, componentRegistryDependency, host, controlPoint, suspendController, serverEnvironment, securityDomain, mechanismFactorySupplier, applySecurityFunction); builder.setInstance(undertowDeploymentInfoService); final Set<String> seenExecutors = new HashSet<String>(); if (metaData.getExecutorName() != null) { final Supplier<Executor> executor = builder.requires(IOServices.WORKER.append(metaData.getExecutorName())); undertowDeploymentInfoService.addInjectedExecutor(metaData.getExecutorName(), executor); seenExecutors.add(metaData.getExecutorName()); } if (metaData.getServlets() != null) { for (JBossServletMetaData servlet : metaData.getServlets()) { if (servlet.getExecutorName() != null && !seenExecutors.contains(servlet.getExecutorName())) { final Supplier<Executor> executor = builder.requires(IOServices.WORKER.append(servlet.getExecutorName())); undertowDeploymentInfoService.addInjectedExecutor(servlet.getExecutorName(), executor); seenExecutors.add(servlet.getExecutorName()); } } } try { builder.install(); } catch (DuplicateServiceException e) { throw UndertowLogger.ROOT_LOGGER.duplicateHostContextDeployments(deploymentInfoServiceName, e.getMessage()); } final ServiceBuilder<?> udsBuilder = serviceTarget.addService(deploymentServiceName); final Consumer<UndertowDeploymentService> sConsumer = udsBuilder.provides(deploymentServiceName, legacyDeploymentServiceName); final Supplier<ServletContainerService> cSupplier = udsBuilder.requires(UndertowService.SERVLET_CONTAINER.append(defaultContainer)); final Supplier<ExecutorService> seSupplier = Services.requireServerExecutor(udsBuilder); final Supplier<Host> hSupplier = udsBuilder.requires(hostServiceName); final Supplier<DeploymentInfo> diSupplier = udsBuilder.requires(deploymentInfoServiceName); for (final ServiceName webDependency : deploymentUnit.getAttachmentList(Attachments.WEB_DEPENDENCIES)) { udsBuilder.requires(webDependency); } for (final ServiceName dependentComponent : dependentComponents) { udsBuilder.requires(dependentComponent); } udsBuilder.setInstance(new UndertowDeploymentService(sConsumer, cSupplier, seSupplier, hSupplier, diSupplier, injectionContainer, true)); udsBuilder.install(); deploymentUnit.addToAttachmentList(Attachments.DEPLOYMENT_COMPLETE_SERVICES, deploymentServiceName); // adding Jakarta Authorization service final boolean elytronJacc = capabilitySupport.hasCapability(ELYTRON_JACC_CAPABILITY_NAME); final boolean legacyJacc = !elytronJacc && capabilitySupport.hasCapability(REF_LEGACY_SECURITY); if(legacyJacc || elytronJacc) { WarJACCDeployer deployer = new WarJACCDeployer(); JaccService<WarMetaData> jaccService = deployer.deploy(deploymentUnit, jaccContextId); if (jaccService != null) { final ServiceName jaccServiceName = deploymentUnit.getServiceName().append(JaccService.SERVICE_NAME); ServiceBuilder<?> jaccBuilder = serviceTarget.addService(jaccServiceName, jaccService); if (parentDeploymentUnit != null) { // add dependency to parent policy jaccBuilder.addDependency(parentDeploymentUnit.getServiceName().append(JaccService.SERVICE_NAME), PolicyConfiguration.class, jaccService.getParentPolicyInjector()); } jaccBuilder.requires(capabilitySupport.getCapabilityServiceName(elytronJacc ? ELYTRON_JACC_CAPABILITY_NAME : LEGACY_JACC_CAPABILITY_NAME)); // add dependency to web deployment service jaccBuilder.requires(deploymentServiceName); jaccBuilder.setInitialMode(Mode.PASSIVE).install(); } } // Process the web related mgmt information final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT); final ModelNode node = deploymentResourceSupport.getDeploymentSubsystemModel(UndertowExtension.SUBSYSTEM_NAME); node.get(DeploymentDefinition.CONTEXT_ROOT.getName()).set("".equals(pathName) ? "/" : pathName); node.get(DeploymentDefinition.VIRTUAL_HOST.getName()).set(hostName); node.get(DeploymentDefinition.SERVER.getName()).set(serverInstanceName); processManagement(deploymentUnit, metaData); } @Override public SessionManagerFactory apply(SessionManagerFactoryConfiguration configuration) { Integer maxActiveSessions = configuration.getMaxActiveSessions(); return (maxActiveSessions != null) ? new InMemorySessionManagerFactory(maxActiveSessions.intValue()) : new InMemorySessionManagerFactory(); } private SessionManagementProvider getDistributableWebDeploymentProvider(DeploymentUnit unit, JBossWebMetaData metaData) { if (metaData.getDistributable() != null) { if (this.sessionManagementProviderFactory != null) { return this.sessionManagementProviderFactory.createSessionManagementProvider(unit, metaData.getReplicationConfig()); } // Fallback to local session manager if server does not support clustering UndertowLogger.ROOT_LOGGER.clusteringNotSupported(); } return this.nonDistributableSessionManagementProvider; } static String pathNameOfDeployment(final DeploymentUnit deploymentUnit, final JBossWebMetaData metaData, final boolean isDefaultWebModule) { String pathName; if (isDefaultWebModule) { pathName = "/"; } else if (metaData.getContextRoot() == null) { final EEModuleDescription description = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); if (description != null) { // if there is an EEModuleDescription we need to take into account that the module name may have been overridden pathName = "/" + description.getModuleName(); } else { pathName = "/" + deploymentUnit.getName().substring(0, deploymentUnit.getName().length() - 4); } } else { pathName = metaData.getContextRoot(); if (pathName.length() > 0 && pathName.charAt(0) != '/') { pathName = "/" + pathName; } } return pathName; } //todo move to UndertowDeploymentService and use all registered servlets from Deployment instead of just one found by metadata void processManagement(final DeploymentUnit unit, JBossWebMetaData metaData) { final DeploymentResourceSupport deploymentResourceSupport = unit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT); for (final JBossServletMetaData servlet : metaData.getServlets()) { try { final String name = servlet.getName(); final ModelNode node = deploymentResourceSupport.getDeploymentSubModel(UndertowExtension.SUBSYSTEM_NAME, PathElement.pathElement("servlet", name)); node.get("servlet-class").set(servlet.getServletClass()); node.get("servlet-name").set(servlet.getServletName()); } catch (Exception e) { // Should a failure in creating the mgmt view also make to the deployment to fail? continue; } } } @Override public void undeploy(final DeploymentUnit deploymentUnit) { deploymentUnit.removeAttachment(ServletContextAttribute.ATTACHMENT_KEY); } private static HashMap<String, TagLibraryInfo> createTldsInfo(final TldsMetaData tldsMetaData, List<TldMetaData> sharedTlds) { final HashMap<String, TagLibraryInfo> ret = new HashMap<>(); if (tldsMetaData != null) { if (tldsMetaData.getTlds() != null) { for (Map.Entry<String, TldMetaData> tld : tldsMetaData.getTlds().entrySet()) { createTldInfo(tld.getKey(), tld.getValue(), ret); } } if (sharedTlds != null) { for (TldMetaData metaData : sharedTlds) { createTldInfo(null, metaData, ret); } } } //we also register them under the new namespaces for (Map.Entry<String, TagLibraryInfo> entry : new HashSet<>(ret.entrySet())) { if (entry.getKey() != null && entry.getKey().startsWith(OLD_URI_PREFIX)) { String newUri = entry.getKey().replace(OLD_URI_PREFIX, NEW_URI_PREFIX); ret.put(newUri, entry.getValue()); } } return ret; } private static TagLibraryInfo createTldInfo(final String location, final TldMetaData tldMetaData, final HashMap<String, TagLibraryInfo> ret) { String relativeLocation = location; String jarPath = null; if (relativeLocation != null && relativeLocation.startsWith("/WEB-INF/lib/")) { int pos = relativeLocation.indexOf('/', "/WEB-INF/lib/".length()); if (pos > 0) { jarPath = relativeLocation.substring(pos); if (jarPath.startsWith("/")) { jarPath = jarPath.substring(1); } relativeLocation = relativeLocation.substring(0, pos); } } TagLibraryInfo tagLibraryInfo = new TagLibraryInfo(); if(tldMetaData.getListeners() != null) { for (ListenerMetaData l : tldMetaData.getListeners()) { tagLibraryInfo.addListener(l.getListenerClass()); } } tagLibraryInfo.setTlibversion(tldMetaData.getTlibVersion()); if (tldMetaData.getJspVersion() == null) { tagLibraryInfo.setJspversion(tldMetaData.getVersion()); } else { tagLibraryInfo.setJspversion(tldMetaData.getJspVersion()); } tagLibraryInfo.setShortname(tldMetaData.getShortName()); tagLibraryInfo.setUri(tldMetaData.getUri()); if (tldMetaData.getDescriptionGroup() != null) { tagLibraryInfo.setInfo(tldMetaData.getDescriptionGroup().getDescription()); } // Validator if (tldMetaData.getValidator() != null) { TagLibraryValidatorInfo tagLibraryValidatorInfo = new TagLibraryValidatorInfo(); tagLibraryValidatorInfo.setValidatorClass(tldMetaData.getValidator().getValidatorClass()); if (tldMetaData.getValidator().getInitParams() != null) { for (ParamValueMetaData paramValueMetaData : tldMetaData.getValidator().getInitParams()) { tagLibraryValidatorInfo.addInitParam(paramValueMetaData.getParamName(), paramValueMetaData.getParamValue()); } } tagLibraryInfo.setValidator(tagLibraryValidatorInfo); } // Tag if (tldMetaData.getTags() != null) { for (TagMetaData tagMetaData : tldMetaData.getTags()) { TagInfo tagInfo = new TagInfo(); tagInfo.setTagName(tagMetaData.getName()); tagInfo.setTagClassName(tagMetaData.getTagClass()); tagInfo.setTagExtraInfo(tagMetaData.getTeiClass()); if (tagMetaData.getBodyContent() != null) { tagInfo.setBodyContent(tagMetaData.getBodyContent().toString()); } tagInfo.setDynamicAttributes(tagMetaData.getDynamicAttributes()); // Description group if (tagMetaData.getDescriptionGroup() != null) { DescriptionGroupMetaData descriptionGroup = tagMetaData.getDescriptionGroup(); if (descriptionGroup.getIcons() != null && descriptionGroup.getIcons().value() != null && (descriptionGroup.getIcons().value().length > 0)) { Icon icon = descriptionGroup.getIcons().value()[0]; tagInfo.setLargeIcon(icon.largeIcon()); tagInfo.setSmallIcon(icon.smallIcon()); } tagInfo.setInfoString(descriptionGroup.getDescription()); tagInfo.setDisplayName(descriptionGroup.getDisplayName()); } // Variable if (tagMetaData.getVariables() != null) { for (VariableMetaData variableMetaData : tagMetaData.getVariables()) { TagVariableInfo tagVariableInfo = new TagVariableInfo(); tagVariableInfo.setNameGiven(variableMetaData.getNameGiven()); tagVariableInfo.setNameFromAttribute(variableMetaData.getNameFromAttribute()); tagVariableInfo.setClassName(variableMetaData.getVariableClass()); tagVariableInfo.setDeclare(variableMetaData.getDeclare()); if (variableMetaData.getScope() != null) { tagVariableInfo.setScope(variableMetaData.getScope().toString()); } tagInfo.addTagVariableInfo(tagVariableInfo); } } // Attribute if (tagMetaData.getAttributes() != null) { for (AttributeMetaData attributeMetaData : tagMetaData.getAttributes()) { TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(); tagAttributeInfo.setName(attributeMetaData.getName()); tagAttributeInfo.setType(attributeMetaData.getType()); tagAttributeInfo.setReqTime(attributeMetaData.getRtexprvalue()); tagAttributeInfo.setRequired(attributeMetaData.getRequired()); tagAttributeInfo.setFragment(attributeMetaData.getFragment()); if (attributeMetaData.getDeferredValue() != null) { tagAttributeInfo.setDeferredValue("true"); tagAttributeInfo.setExpectedTypeName(attributeMetaData.getDeferredValue().getType()); } else { tagAttributeInfo.setDeferredValue("false"); } if (attributeMetaData.getDeferredMethod() != null) { tagAttributeInfo.setDeferredMethod("true"); tagAttributeInfo.setMethodSignature(attributeMetaData.getDeferredMethod().getMethodSignature()); } else { tagAttributeInfo.setDeferredMethod("false"); } tagInfo.addTagAttributeInfo(tagAttributeInfo); } } tagLibraryInfo.addTagInfo(tagInfo); } } // Tag files if (tldMetaData.getTagFiles() != null) { for (TagFileMetaData tagFileMetaData : tldMetaData.getTagFiles()) { TagFileInfo tagFileInfo = new TagFileInfo(); tagFileInfo.setName(tagFileMetaData.getName()); tagFileInfo.setPath(tagFileMetaData.getPath()); tagLibraryInfo.addTagFileInfo(tagFileInfo); } } // Function if (tldMetaData.getFunctions() != null) { for (FunctionMetaData functionMetaData : tldMetaData.getFunctions()) { FunctionInfo functionInfo = new FunctionInfo(); functionInfo.setName(functionMetaData.getName()); functionInfo.setFunctionClass(functionMetaData.getFunctionClass()); functionInfo.setFunctionSignature(functionMetaData.getFunctionSignature()); tagLibraryInfo.addFunctionInfo(functionInfo); } } if (jarPath == null && relativeLocation == null) { if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } } else if (jarPath == null) { tagLibraryInfo.setLocation(""); tagLibraryInfo.setPath(relativeLocation); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } ret.put(relativeLocation, tagLibraryInfo); } else { tagLibraryInfo.setLocation(relativeLocation); tagLibraryInfo.setPath(jarPath); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } if (jarPath.equals("META-INF/taglib.tld")) { ret.put(relativeLocation, tagLibraryInfo); } } return tagLibraryInfo; } }
42,936
57.898491
292
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/AuthMethodParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.servlet.api.AuthMethodConfig; import io.undertow.util.QueryParameterUtils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Map; /** * @author Stuart Douglas */ public class AuthMethodParser { public static final String UTF_8 = "UTF-8"; public static List<AuthMethodConfig> parse(final String methods, final Map<String, String> replacements) { try { if (methods == null || methods.isEmpty()) { return Collections.emptyList(); } final List<AuthMethodConfig> ret = new ArrayList<AuthMethodConfig>(); String[] parts = methods.split(","); for (String part : parts) { if (part.isEmpty()) { continue; } int index = part.indexOf('?'); if (index == -1) { ret.add(createAuthMethodConfig(part, replacements)); } else { final String name = part.substring(0, index); Map<String, Deque<String>> props = QueryParameterUtils.parseQueryString(part.substring(index + 1), UTF_8); final AuthMethodConfig authMethodConfig = createAuthMethodConfig(name, replacements); for (Map.Entry<String, Deque<String>> entry : props.entrySet()) { Deque<String> val = entry.getValue(); if (val.isEmpty()) { authMethodConfig.getProperties().put(entry.getKey(), ""); } else { authMethodConfig.getProperties().put(entry.getKey(), val.getFirst()); } } ret.add(authMethodConfig); } } return ret; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private static AuthMethodConfig createAuthMethodConfig(String part, Map<String, String> replacements) throws UnsupportedEncodingException { String name = URLDecoder.decode(part, UTF_8); if (replacements.containsKey(name)) { return new AuthMethodConfig(replacements.get(name)); } return new AuthMethodConfig(name); } private AuthMethodParser() { } }
3,550
38.455556
143
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/DelegatingResourceManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.server.handlers.resource.Resource; import io.undertow.server.handlers.resource.ResourceChangeListener; import io.undertow.server.handlers.resource.ResourceManager; import org.xnio.IoUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author Stuart Douglas */ public class DelegatingResourceManager implements ResourceManager { private final List<ResourceManager> delegates; public DelegatingResourceManager(List<ResourceManager> delegates) { this.delegates = new ArrayList<>(delegates); } @Override public Resource getResource(String path) throws IOException { for(ResourceManager d : delegates) { Resource res = d.getResource(path); if(res != null) { return res; } } return null; } @Override public boolean isResourceChangeListenerSupported() { return true; } @Override public void registerResourceChangeListener(ResourceChangeListener listener) { for(ResourceManager del : delegates) { if(del.isResourceChangeListenerSupported()) { del.registerResourceChangeListener(listener); } } } @Override public void removeResourceChangeListener(ResourceChangeListener listener) { for(ResourceManager del : delegates) { if(del.isResourceChangeListenerSupported()) { del.removeResourceChangeListener(listener); } } } @Override public void close() throws IOException { for(ResourceManager del : delegates) { IoUtils.safeClose(del); } } }
2,778
31.313953
81
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/WarStructureDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.io.Closeable; import java.io.File; import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.undertow.util.FileUtils; import org.jboss.as.controller.services.path.PathManager; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.MountedDeploymentOverlay; import org.jboss.as.server.deployment.PrivateSubDeploymentMarker; import org.jboss.as.server.deployment.module.FilterSpecification; import org.jboss.as.server.deployment.module.ModuleRootMarker; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.as.server.deployment.module.MountHandle; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.server.deployment.module.TempFileProviderService; import org.jboss.as.web.common.SharedTldsMetaDataBuilder; import org.jboss.as.web.common.WarMetaData; import org.jboss.modules.filter.PathFilters; import org.jboss.modules.security.ImmediatePermissionFactory; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; import org.jboss.vfs.VisitorAttributes; import org.jboss.vfs.util.SuffixMatchFilter; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * Create and mount classpath entries in the .war deployment. * * @author Emanuel Muckenhuber * @author [email protected] */ public class WarStructureDeploymentProcessor implements DeploymentUnitProcessor { private static final String TEMP_DIR = "jboss.server.temp.dir"; public static final String WEB_INF_LIB = "WEB-INF/lib"; public static final String WEB_INF_CLASSES = "WEB-INF/classes"; public static final String META_INF = "META-INF"; private static final String WEB_INF_EXTERNAL_MOUNTS = "WEB-INF/undertow-external-mounts.conf"; public static final VirtualFileFilter DEFAULT_WEB_INF_LIB_FILTER = new SuffixMatchFilter(".jar", VisitorAttributes.DEFAULT); private final SharedTldsMetaDataBuilder sharedTldsMetaData; public WarStructureDeploymentProcessor(final SharedTldsMetaDataBuilder sharedTldsMetaData) { this.sharedTldsMetaData = sharedTldsMetaData; } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } final ResourceRoot deploymentResourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); final VirtualFile deploymentRoot = deploymentResourceRoot.getRoot(); if (deploymentRoot == null) { return; } // set the child first behaviour final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); if (moduleSpecification == null) { return; } moduleSpecification.setPrivateModule(true); // other sub deployments should not have access to classes in the war module PrivateSubDeploymentMarker.mark(deploymentUnit); // we do not want to index the resource root, only WEB-INF/classes and WEB-INF/lib deploymentResourceRoot.putAttachment(Attachments.INDEX_RESOURCE_ROOT, false); // Make sure the root does not end up in the module, only META-INF deploymentResourceRoot.getExportFilters().add(new FilterSpecification(PathFilters.getMetaInfFilter(), true)); deploymentResourceRoot.getExportFilters().add(new FilterSpecification(PathFilters.getMetaInfSubdirectoriesFilter(), true)); deploymentResourceRoot.getExportFilters().add(new FilterSpecification(PathFilters.acceptAll(), false)); ModuleRootMarker.mark(deploymentResourceRoot, true); // TODO: This needs to be ported to add additional resource roots the standard way final MountHandle mountHandle = deploymentResourceRoot.getMountHandle(); try { // add standard resource roots, this should eventually replace ClassPathEntry final List<ResourceRoot> resourceRoots = createResourceRoots(deploymentRoot, deploymentUnit); for (ResourceRoot root : resourceRoots) { deploymentUnit.addToAttachmentList(Attachments.RESOURCE_ROOTS, root); } } catch (Exception e) { throw new DeploymentUnitProcessingException(e); } // Add the war metadata final WarMetaData warMetaData = new WarMetaData(); deploymentUnit.putAttachment(WarMetaData.ATTACHMENT_KEY, warMetaData); String deploymentName; if(deploymentUnit.getParent() == null) { deploymentName = deploymentUnit.getName(); } else { deploymentName = deploymentUnit.getParent().getName() + "." + deploymentUnit.getName(); } PathManager pathManager = deploymentUnit.getAttachment(Attachments.PATH_MANAGER); File tempDir = new File(pathManager.getPathEntry(TEMP_DIR).resolvePath(), deploymentName); tempDir.mkdirs(); warMetaData.setTempDir(tempDir); moduleSpecification.addPermissionFactory(new ImmediatePermissionFactory(new FilePermission(tempDir.getAbsolutePath() + File.separatorChar + "-", "read,write,delete"))); // Add the shared TLDs metadata final TldsMetaData tldsMetaData = new TldsMetaData(); tldsMetaData.setSharedTlds(sharedTldsMetaData); deploymentUnit.putAttachment(TldsMetaData.ATTACHMENT_KEY, tldsMetaData); processExternalMounts(deploymentUnit, deploymentRoot); } private void processExternalMounts(DeploymentUnit deploymentUnit, VirtualFile deploymentRoot) throws DeploymentUnitProcessingException { VirtualFile mounts = deploymentRoot.getChild(WEB_INF_EXTERNAL_MOUNTS); if(!mounts.exists()) { return; } try (InputStream data = mounts.openStream()) { String contents = FileUtils.readFile(data); String[] lines = contents.split("\n"); for(String line : lines) { String trimmed = line; int commentIndex = trimmed.indexOf("#"); if(commentIndex > -1) { trimmed = trimmed.substring(0, commentIndex); } trimmed = trimmed.trim(); if(trimmed.isEmpty()) { continue; } File path = new File(trimmed); if(path.exists()) { deploymentUnit.addToAttachmentList(UndertowAttachments.EXTERNAL_RESOURCES, path); } else { throw UndertowLogger.ROOT_LOGGER.couldNotFindExternalPath(path); } } } catch (IOException e) { throw new RuntimeException(e); } } /** * Create the resource roots for a .war deployment * * * @param deploymentRoot the deployment root * @return the resource roots * @throws java.io.IOException for any error */ private List<ResourceRoot> createResourceRoots(final VirtualFile deploymentRoot, final DeploymentUnit deploymentUnit) throws IOException, DeploymentUnitProcessingException { final List<ResourceRoot> entries = new ArrayList<ResourceRoot>(); // WEB-INF classes final VirtualFile webinfClasses = deploymentRoot.getChild(WEB_INF_CLASSES); if (webinfClasses.exists()) { final ResourceRoot webInfClassesRoot = new ResourceRoot(webinfClasses.getName(), webinfClasses, null); ModuleRootMarker.mark(webInfClassesRoot); entries.add(webInfClassesRoot); } // WEB-INF lib Map<String, MountedDeploymentOverlay> overlays = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_OVERLAY_LOCATIONS); final VirtualFile webinfLib = deploymentRoot.getChild(WEB_INF_LIB); if (webinfLib.exists()) { final List<VirtualFile> archives = webinfLib.getChildren(DEFAULT_WEB_INF_LIB_FILTER); for (final VirtualFile archive : archives) { try { String relativeName = archive.getPathNameRelativeTo(deploymentRoot); MountedDeploymentOverlay overlay = overlays.get(relativeName); Closeable closable = null; if(overlay != null) { overlay.remountAsZip(false); } else if (archive.isFile()) { closable = VFS.mountZip(archive, archive, TempFileProviderService.provider()); } else { closable = null; } final ResourceRoot webInfArchiveRoot = new ResourceRoot(archive.getName(), archive, MountHandle.create(closable)); ModuleRootMarker.mark(webInfArchiveRoot); entries.add(webInfArchiveRoot); } catch (IOException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToProcessWebInfLib(archive), e); } } } return entries; } }
10,787
45.300429
177
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/ScisMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.Map; import java.util.Set; import jakarta.servlet.ServletContainerInitializer; import org.jboss.as.server.deployment.AttachmentKey; /** * @author Remy Maucherat */ public class ScisMetaData { public static final AttachmentKey<ScisMetaData> ATTACHMENT_KEY = AttachmentKey.create(ScisMetaData.class); /** * SCIs. */ private Set<ServletContainerInitializer> scis; /** * Handles types. */ private Map<ServletContainerInitializer, Set<Class<?>>> handlesTypes; public Set<ServletContainerInitializer> getScis() { return scis; } public void setScis(Set<ServletContainerInitializer> scis) { this.scis = scis; } public Map<ServletContainerInitializer, Set<Class<?>>> getHandlesTypes() { return handlesTypes; } public void setHandlesTypes(Map<ServletContainerInitializer, Set<Class<?>>> handlesTypes) { this.handlesTypes = handlesTypes; } }
2,041
29.939394
110
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/JspApplicationContextWrapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.List; import jakarta.el.ELContextListener; import jakarta.el.ELResolver; import jakarta.el.ExpressionFactory; import jakarta.servlet.ServletContext; import jakarta.servlet.jsp.JspContext; import org.apache.jasper.el.ELContextImpl; import org.apache.jasper.runtime.JspApplicationContextImpl; import org.jboss.as.web.common.ExpressionFactoryWrapper; /** * @author pmuir */ public class JspApplicationContextWrapper extends JspApplicationContextImpl { private final JspApplicationContextImpl delegate; private final List<ExpressionFactoryWrapper> wrapperList; private final ServletContext servletContext; private volatile ExpressionFactory factory; protected JspApplicationContextWrapper(JspApplicationContextImpl delegate, List<ExpressionFactoryWrapper> wrapperList, ServletContext servletContext) { this.delegate = delegate; this.wrapperList = wrapperList; this.servletContext = servletContext; } @Override public void addELContextListener(ELContextListener listener) { delegate.addELContextListener(listener); } @Override public void addELResolver(ELResolver resolver) throws IllegalStateException { delegate.addELResolver(resolver); } @Override public ELContextImpl createELContext(JspContext arg0) { // Before providing any ELContext, ensure we allow any ExpressionFactoryWrappers to execute getExpressionFactory(); return delegate.createELContext(arg0); } @Override public ExpressionFactory getExpressionFactory() { if (factory == null) { synchronized (this) { if (factory == null) { ExpressionFactory tmpfactory = delegate.getExpressionFactory(); for (ExpressionFactoryWrapper wrapper : wrapperList) { tmpfactory = wrapper.wrap(tmpfactory, servletContext); } factory = tmpfactory; } } } return factory; } @Override public boolean equals(Object obj) { return this == obj || delegate.equals(obj); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.toString(); } }
3,422
32.558824
155
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/GateHandlerWrapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.SameThreadExecutor; import java.util.ArrayList; import java.util.List; /** * A handler that will prevent requests from progressing until the gate is opened. * * This will either queue or reject the requests, based on the configured behaviour * * @author Stuart Douglas */ public class GateHandlerWrapper implements HandlerWrapper { private final List<Holder> held = new ArrayList<>(); private volatile boolean open = false; /** * If this is >0 then requests when the gate is closed will be rejected with this value * * Otherwise they will be queued */ private final int statusCode; public GateHandlerWrapper(int statusCode) { this.statusCode = statusCode; } public synchronized void open() { open = true; for(Holder holder : held) { holder.exchange.dispatch(holder.next); } held.clear(); } @Override public HttpHandler wrap(HttpHandler handler) { return new GateHandler(handler); } private final class GateHandler implements HttpHandler { private final HttpHandler next; private GateHandler(HttpHandler next) { this.next = next; } @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if(open) { next.handleRequest(exchange); return; } if(statusCode > 0) { exchange.setStatusCode(statusCode); return; } synchronized (GateHandlerWrapper.this) { if(open) { next.handleRequest(exchange); } else { exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() { @Override public void run() { synchronized (GateHandlerWrapper.this) { if(open) { exchange.dispatch(next); } else { held.add(new Holder(next, exchange)); } } } }); } } } } private static final class Holder { final HttpHandler next; final HttpServerExchange exchange; private Holder(HttpHandler next, HttpServerExchange exchange) { this.next = next; this.exchange = exchange; } } }
3,813
30.783333
91
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/ServletContainerInitializerDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import jakarta.servlet.ServletContainerInitializer; import jakarta.servlet.annotation.HandlesTypes; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.as.server.moduleservice.ServiceModuleLoader; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.jboss.as.web.common.WarMetaData; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.FieldInfo; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.MethodParameterInfo; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoadException; import org.jboss.vfs.VirtualFile; /** * SCI deployment processor. * * @author Emanuel Muckenhuber * @author Remy Maucherat * @author Ales Justin */ public class ServletContainerInitializerDeploymentProcessor implements DeploymentUnitProcessor { /** * Process SCIs. */ public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ServiceModuleLoader loader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); assert warMetaData != null; final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if (module == null) { throw UndertowLogger.ROOT_LOGGER.failedToResolveModule(deploymentUnit); } final ClassLoader classLoader = module.getClassLoader(); ScisMetaData scisMetaData = deploymentUnit.getAttachment(ScisMetaData.ATTACHMENT_KEY); if (scisMetaData == null) { scisMetaData = new ScisMetaData(); deploymentUnit.putAttachment(ScisMetaData.ATTACHMENT_KEY, scisMetaData); } Set<ServletContainerInitializer> scis = scisMetaData.getScis(); Set<Class<? extends ServletContainerInitializer>> sciClasses = new HashSet<>(); if (scis == null) { scis = new LinkedHashSet<>(); scisMetaData.setScis(scis); } Map<ServletContainerInitializer, Set<Class<?>>> handlesTypes = scisMetaData.getHandlesTypes(); if (handlesTypes == null) { handlesTypes = new HashMap<ServletContainerInitializer, Set<Class<?>>>(); scisMetaData.setHandlesTypes(handlesTypes); } // Find the SCIs from shared modules for (ModuleDependency dependency : moduleSpecification.getAllDependencies()) { // Should not include SCI if services is not included if (!dependency.isImportServices()) { continue; } try { Module depModule = loader.loadModule(dependency.getIdentifier()); ServiceLoader<ServletContainerInitializer> serviceLoader = depModule.loadService(ServletContainerInitializer.class); for (ServletContainerInitializer service : serviceLoader) { if(sciClasses.add(service.getClass())) { scis.add(service); } } } catch (ModuleLoadException e) { if (!dependency.isOptional()) { throw UndertowLogger.ROOT_LOGGER.errorLoadingSCIFromModule(dependency.getIdentifier().toString(), e); } } } // Find local ServletContainerInitializer services List<String> order = warMetaData.getOrder(); Map<String, VirtualFile> localScis = warMetaData.getScis(); if (order != null && localScis != null) { for (String jar : order) { VirtualFile sci = localScis.get(jar); if (sci != null) { scis.addAll(loadSci(classLoader, sci, jar, true, sciClasses)); } } } //SCI's deployed in the war itself if(localScis != null) { VirtualFile warDeployedScis = localScis.get("classes"); if(warDeployedScis != null) { scis.addAll(loadSci(classLoader, warDeployedScis, deploymentUnit.getName(), true, sciClasses)); } } // Process HandlesTypes for ServletContainerInitializer Map<Class<?>, Set<ServletContainerInitializer>> typesMap = new HashMap<Class<?>, Set<ServletContainerInitializer>>(); for (ServletContainerInitializer service : scis) { try { if (service.getClass().isAnnotationPresent(HandlesTypes.class)) { HandlesTypes handlesTypesAnnotation = service.getClass().getAnnotation(HandlesTypes.class); Class<?>[] typesArray = handlesTypesAnnotation.value(); if (typesArray != null) { for (Class<?> type : typesArray) { Set<ServletContainerInitializer> servicesSet = typesMap.get(type); if (servicesSet == null) { servicesSet = new HashSet<ServletContainerInitializer>(); typesMap.put(type, servicesSet); } servicesSet.add(service); handlesTypes.put(service, new HashSet<Class<?>>()); } } } } catch (ArrayStoreException e) { // https://bugs.openjdk.java.net/browse/JDK-7183985 // Class.findAnnotation() has a bug under JDK < 11 which throws ArrayStoreException throw UndertowLogger.ROOT_LOGGER.missingClassInAnnotation(HandlesTypes.class.getSimpleName(), service.getClass().getName()); } } Class<?>[] typesArray = typesMap.keySet().toArray(new Class<?>[0]); final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); if (index == null) { throw UndertowLogger.ROOT_LOGGER.unableToResolveAnnotationIndex(deploymentUnit); } final CompositeIndex parent; if(deploymentUnit.getParent() != null) { parent = deploymentUnit.getParent().getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); } else { parent = null; } //WFLY-4205, look in the parent as well as the war CompositeIndex parentIndex = deploymentUnit.getParent() == null ? null : deploymentUnit.getParent().getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); // Find classes which extend, implement, or are annotated by HandlesTypes for (Class<?> type : typesArray) { DotName className = DotName.createSimple(type.getName()); Set<ClassInfo> classInfos = new HashSet<>(); classInfos.addAll(processHandlesType(className, type, index, parent)); if(parentIndex != null) { classInfos.addAll(processHandlesType(className, type, parentIndex, parent)); } Set<Class<?>> classes = loadClassInfoSet(classInfos, classLoader); Set<ServletContainerInitializer> sciSet = typesMap.get(type); for (ServletContainerInitializer sci : sciSet) { handlesTypes.get(sci).addAll(classes); } } } public void undeploy(final DeploymentUnit context) { context.removeAttachment(ScisMetaData.ATTACHMENT_KEY); } private List<ServletContainerInitializer> loadSci(ClassLoader classLoader, VirtualFile sci, String jar, boolean error, Set<Class<? extends ServletContainerInitializer>> sciClasses) throws DeploymentUnitProcessingException { final List<ServletContainerInitializer> scis = new ArrayList<ServletContainerInitializer>(); InputStream is = null; try { // Get the ServletContainerInitializer class name is = sci.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); String servletContainerInitializerClassName = reader.readLine(); while (servletContainerInitializerClassName != null) { try { int pos = servletContainerInitializerClassName.indexOf('#'); if (pos >= 0) { servletContainerInitializerClassName = servletContainerInitializerClassName.substring(0, pos); } servletContainerInitializerClassName = servletContainerInitializerClassName.trim(); if (!servletContainerInitializerClassName.isEmpty()) { // Instantiate the ServletContainerInitializer ServletContainerInitializer service = (ServletContainerInitializer) classLoader.loadClass(servletContainerInitializerClassName).newInstance(); if (service != null && sciClasses.add(service.getClass())) { scis.add(service); } } servletContainerInitializerClassName = reader.readLine(); } catch (Exception e) { if (error) { throw UndertowLogger.ROOT_LOGGER.errorProcessingSCI(jar, e); } else { UndertowLogger.ROOT_LOGGER.skippedSCI(jar, e); } } } } catch (Exception e) { if (error) { throw UndertowLogger.ROOT_LOGGER.errorProcessingSCI(jar, e); } else { UndertowLogger.ROOT_LOGGER.skippedSCI(jar, e); } } finally { try { if (is != null) is.close(); } catch (IOException e) { // Ignore } } return scis; } private Set<ClassInfo> processHandlesType(DotName typeName, Class<?> type, CompositeIndex index, CompositeIndex parent) throws DeploymentUnitProcessingException { Set<ClassInfo> classes = new HashSet<ClassInfo>(); if (type.isAnnotation()) { List<AnnotationInstance> instances = index.getAnnotations(typeName); for (AnnotationInstance instance : instances) { AnnotationTarget annotationTarget = instance.target(); if (annotationTarget instanceof ClassInfo) { classes.add((ClassInfo) annotationTarget); } else if (annotationTarget instanceof FieldInfo) { classes.add(((FieldInfo) annotationTarget).declaringClass()); } else if (annotationTarget instanceof MethodInfo) { classes.add(((MethodInfo) annotationTarget).declaringClass()); } else if (annotationTarget instanceof MethodParameterInfo) { classes.add(((MethodParameterInfo) annotationTarget).method().declaringClass()); } } } else { classes.addAll(index.getAllKnownSubclasses(typeName)); classes.addAll(index.getAllKnownImplementors(typeName)); if(parent != null) { Set<ClassInfo> parentImplementors = new HashSet<>(); parentImplementors.addAll(parent.getAllKnownImplementors(typeName)); parentImplementors.addAll(parent.getAllKnownSubclasses(typeName)); for(ClassInfo pc: parentImplementors) { classes.addAll(index.getAllKnownSubclasses(pc.name())); classes.addAll(index.getAllKnownImplementors(pc.name())); } } } return classes; } private Set<Class<?>> loadClassInfoSet(Set<ClassInfo> classInfos, ClassLoader classLoader) throws DeploymentUnitProcessingException { Set<Class<?>> classes = new HashSet<Class<?>>(); for (ClassInfo classInfo : classInfos) { Class<?> type; try { type = classLoader.loadClass(classInfo.name().toString()); classes.add(type); } catch (Exception e) { UndertowLogger.ROOT_LOGGER.cannotLoadDesignatedHandleTypes(classInfo, e); } } return classes; } }
14,643
47.330033
227
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/EarContextRootProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import org.jboss.as.ee.structure.Attachments; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.ear.spec.EarMetaData; import org.jboss.metadata.ear.spec.ModuleMetaData; import org.jboss.metadata.ear.spec.ModulesMetaData; import org.jboss.metadata.ear.spec.WebModuleMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import static org.jboss.metadata.ear.spec.ModuleMetaData.ModuleType.Web; /** * Deployment unit processor responsible for detecting web deployments and determining if they have a parent EAR file and * if so applying the EAR defined context root to web metadata. * * @author John Bailey */ public class EarContextRootProcessor implements DeploymentUnitProcessor { public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if(warMetaData == null) { return; // Nothing we can do without WarMetaData } final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT); if(deploymentRoot == null) { return; // We don't have a root to work with } final DeploymentUnit parent = deploymentUnit.getParent(); if(parent == null || !DeploymentTypeMarker.isType(DeploymentType.EAR, parent)) { return; // Only care if this war is nested in an EAR } final EarMetaData earMetaData = parent.getAttachment(Attachments.EAR_METADATA); if(earMetaData == null) { return; // Nothing to see here } final ModulesMetaData modulesMetaData = earMetaData.getModules(); if(modulesMetaData != null) for(ModuleMetaData moduleMetaData : modulesMetaData) { if(Web.equals(moduleMetaData.getType()) && moduleMetaData.getFileName().equals(deploymentRoot.getRootName())) { String contextRoot = WebModuleMetaData.class.cast(moduleMetaData.getValue()).getContextRoot(); if(contextRoot == null && (warMetaData.getJBossWebMetaData() == null || warMetaData.getJBossWebMetaData().getContextRoot() == null)) { contextRoot = "/" + parent.getName().substring(0, parent.getName().length() - 4) + "/" + deploymentUnit.getName().substring(0, deploymentUnit.getName().length() - 4); } if(contextRoot != null) { JBossWebMetaData jBossWebMetaData = warMetaData.getJBossWebMetaData(); if(jBossWebMetaData == null) { jBossWebMetaData = new JBossWebMetaData(); warMetaData.setJBossWebMetaData(jBossWebMetaData); } jBossWebMetaData.setContextRoot(contextRoot); } return; } } } }
4,539
47.297872
150
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/WarMetaDataProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.jboss.as.ee.component.DeploymentDescriptorEnvironment; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.metadata.MetadataCompleteMarker; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.ear.spec.EarMetaData; import org.jboss.metadata.javaee.spec.EmptyMetaData; import org.jboss.metadata.javaee.spec.SecurityRolesMetaData; import org.jboss.metadata.merge.javaee.spec.SecurityRolesMetaDataMerger; import org.jboss.metadata.merge.web.jboss.JBossWebMetaDataMerger; import org.jboss.metadata.merge.web.spec.WebCommonMetaDataMerger; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.AbsoluteOrderingMetaData; import org.jboss.metadata.web.spec.OrderingElementMetaData; import org.jboss.metadata.web.spec.WebCommonMetaData; import org.jboss.metadata.web.spec.WebFragmentMetaData; import org.jboss.metadata.web.spec.WebMetaData; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * Merge all metadata into a main JBossWebMetaData. * * @author Remy Maucherat * @author [email protected] */ public class WarMetaDataProcessor implements DeploymentUnitProcessor { static final String VERSION = "4.0"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); assert warMetaData != null; boolean isComplete = false; WebMetaData specMetaData = warMetaData.getWebMetaData(); if (specMetaData != null) { isComplete = specMetaData.isMetadataComplete(); } // Find all fragments that have been processed by deployers, and place // them in a map keyed by location LinkedList<String> order = new LinkedList<String>(); List<WebOrdering> orderings = new ArrayList<WebOrdering>(); HashSet<String> jarsSet = new HashSet<String>(); Set<VirtualFile> overlays = new HashSet<VirtualFile>(); Map<String, VirtualFile> scis = new HashMap<String, VirtualFile>(); boolean fragmentFound = false; Map<String, WebFragmentMetaData> webFragments = warMetaData.getWebFragmentsMetaData(); List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS); for (ResourceRoot resourceRoot : resourceRoots) { if (resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { jarsSet.add(resourceRoot.getRootName()); // Find overlays VirtualFile overlay = resourceRoot.getRoot().getChild("META-INF/resources"); if (overlay.exists()) { overlays.add(overlay); } } //we load SCI's directly from the war not just from jars //not required by spec but other containers do it //see WFLY-9081 // Find ServletContainerInitializer services VirtualFile sci = resourceRoot.getRoot().getChild("META-INF/services/jakarta.servlet.ServletContainerInitializer"); if (sci.exists()) { scis.put(resourceRoot.getRootName(), sci); } } if (!isComplete) { HashSet<String> jarsWithoutFragmentsSet = new HashSet<String>(); jarsWithoutFragmentsSet.addAll(jarsSet); for (Map.Entry<String, WebFragmentMetaData> entry : webFragments.entrySet()) { fragmentFound = true; String jarName = entry.getKey(); WebFragmentMetaData fragmentMetaData = entry.getValue(); webFragments.put(jarName, fragmentMetaData); WebOrdering webOrdering = new WebOrdering(); webOrdering.setName(fragmentMetaData.getName()); webOrdering.setJar(jarName); jarsWithoutFragmentsSet.remove(jarName); if (fragmentMetaData.getOrdering() != null) { if (fragmentMetaData.getOrdering().getAfter() != null) { for (OrderingElementMetaData orderingElementMetaData : fragmentMetaData.getOrdering().getAfter() .getOrdering()) { if (orderingElementMetaData.isOthers()) { webOrdering.setAfterOthers(true); } else { webOrdering.addAfter(orderingElementMetaData.getName()); } } } if (fragmentMetaData.getOrdering().getBefore() != null) { for (OrderingElementMetaData orderingElementMetaData : fragmentMetaData.getOrdering().getBefore() .getOrdering()) { if (orderingElementMetaData.isOthers()) { webOrdering.setBeforeOthers(true); } else { webOrdering.addBefore(orderingElementMetaData.getName()); } } } } orderings.add(webOrdering); } // If there is no fragment, still consider it for ordering as a // fragment specifying no name and no order for (String jarName : jarsWithoutFragmentsSet) { WebOrdering ordering = new WebOrdering(); ordering.setJar(jarName); orderings.add(ordering); } } if (!fragmentFound) { // Drop the order as there is no fragment in the webapp orderings.clear(); } // Generate web fragments parsing order AbsoluteOrderingMetaData absoluteOrderingMetaData = null; if (!isComplete && specMetaData != null) { absoluteOrderingMetaData = specMetaData.getAbsoluteOrdering(); } if (absoluteOrderingMetaData != null) { // Absolute ordering from web.xml, any relative fragment ordering is ignored int otherPos = -1; int i = 0; for (OrderingElementMetaData orderingElementMetaData : absoluteOrderingMetaData.getOrdering()) { if (orderingElementMetaData.isOthers()) { if (otherPos >= 0) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidMultipleOthers()); } otherPos = i; } else { boolean found = false; for (WebOrdering ordering : orderings) { if (orderingElementMetaData.getName().equals(ordering.getName())) { order.add(ordering.getJar()); jarsSet.remove(ordering.getJar()); found = true; break; } } if (!found) { UndertowLogger.ROOT_LOGGER.invalidAbsoluteOrdering(orderingElementMetaData.getName()); } else { i++; } } } if (otherPos >= 0) { order.addAll(otherPos, jarsSet); jarsSet.clear(); } } else if (!orderings.isEmpty()) { // Resolve relative ordering try { resolveOrder(orderings, order); } catch (IllegalStateException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidRelativeOrdering(), e); } jarsSet.clear(); } else { // No order specified order.addAll(jarsSet); jarsSet.clear(); warMetaData.setNoOrder(true); } if (UndertowLogger.ROOT_LOGGER.isDebugEnabled()) { StringBuilder builder = new StringBuilder(); builder.append("Resolved order: [ "); for (String jar : order) { builder.append(jar).append(' '); } builder.append(']'); UndertowLogger.ROOT_LOGGER.debug(builder.toString()); } warMetaData.setOrder(order); warMetaData.setOverlays(overlays); warMetaData.setScis(scis); Map<String, WebMetaData> annotationsMetaData = warMetaData.getAnnotationsMetaData(); // The fragments and corresponding annotations will need to be merged in order // For each JAR in the order: // - Merge the annotation metadata into the fragment meta data (unless the fragment exists and is meta data complete) // - Merge the fragment metadata into merged fragment meta data WebCommonMetaData mergedFragmentMetaData = new WebCommonMetaData(); if (specMetaData == null) { // If there is no web.xml, it has to be considered to be the latest version specMetaData = new WebMetaData(); specMetaData.setVersion(VERSION); } // Augment with meta data from annotations in /WEB-INF/classes WebMetaData annotatedMetaData = annotationsMetaData.get("classes"); if (annotatedMetaData != null) { if (isComplete) { // Discard @WebFilter, @WebListener and @WebServlet annotatedMetaData.setFilters(null); annotatedMetaData.setFilterMappings(null); annotatedMetaData.setListeners(null); annotatedMetaData.setServlets(null); annotatedMetaData.setServletMappings(null); } WebCommonMetaDataMerger.augment(specMetaData, annotatedMetaData, null, true); } // Augment with meta data from fragments and annotations from the corresponding JAR for (String jar : order) { WebFragmentMetaData webFragmentMetaData = webFragments.get(jar); if (webFragmentMetaData == null || isComplete) { webFragmentMetaData = new WebFragmentMetaData(); // Add non overriding default distributable flag webFragmentMetaData.setDistributable(new EmptyMetaData()); } WebMetaData jarAnnotatedMetaData = annotationsMetaData.get(jar); if ((isComplete || webFragmentMetaData.isMetadataComplete()) && jarAnnotatedMetaData != null) { // Discard @WebFilter, @WebListener and @WebServlet jarAnnotatedMetaData.setFilters(null); jarAnnotatedMetaData.setFilterMappings(null); jarAnnotatedMetaData.setListeners(null); jarAnnotatedMetaData.setServlets(null); jarAnnotatedMetaData.setServletMappings(null); } if (jarAnnotatedMetaData != null) { // Merge annotations corresponding to the JAR WebCommonMetaDataMerger.augment(webFragmentMetaData, jarAnnotatedMetaData, null, true); } // Merge fragment meta data according to the conflict rules try { WebCommonMetaDataMerger.augment(mergedFragmentMetaData, webFragmentMetaData, specMetaData, false); } catch (Exception e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebFragment(jar), e); } } // Augment with meta data from annotations from JARs excluded from the order for (String jar : jarsSet) { WebFragmentMetaData webFragmentMetaData = new WebFragmentMetaData(); // Add non overriding default distributable flag webFragmentMetaData.setDistributable(new EmptyMetaData()); WebMetaData jarAnnotatedMetaData = annotationsMetaData.get(jar); if (jarAnnotatedMetaData != null) { // Discard @WebFilter, @WebListener and @WebServlet jarAnnotatedMetaData.setFilters(null); jarAnnotatedMetaData.setFilterMappings(null); jarAnnotatedMetaData.setListeners(null); jarAnnotatedMetaData.setServlets(null); jarAnnotatedMetaData.setServletMappings(null); } if (jarAnnotatedMetaData != null) { // Merge annotations corresponding to the JAR WebCommonMetaDataMerger.augment(webFragmentMetaData, jarAnnotatedMetaData, null, true); } // Merge fragment meta data according to the conflict rules try { WebCommonMetaDataMerger.augment(mergedFragmentMetaData, webFragmentMetaData, specMetaData, false); } catch (Exception e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebFragment(jar), e); } } WebCommonMetaDataMerger.augment(specMetaData, mergedFragmentMetaData, null, true); List<WebMetaData> additional = warMetaData.getAdditionalModuleAnnotationsMetadata(); if (additional != null && !isComplete) { //augument with annotations from additional modules for (WebMetaData annotations : additional) { // Merge annotations corresponding to the JAR WebCommonMetaDataMerger.augment(specMetaData, annotations, null, true); } } // Override with meta data (JBossWebMetaData) Create a merged view JBossWebMetaData mergedMetaData = new JBossWebMetaData(); JBossWebMetaData metaData = warMetaData.getJBossWebMetaData(); JBossWebMetaDataMerger.merge(mergedMetaData, metaData, specMetaData); // FIXME: Incorporate any ear level overrides warMetaData.setMergedJBossWebMetaData(mergedMetaData); if (mergedMetaData.isMetadataComplete()) { MetadataCompleteMarker.setMetadataComplete(deploymentUnit, true); } //now attach any JNDI binding related information to the deployment if (mergedMetaData.getJndiEnvironmentRefsGroup() != null) { final DeploymentDescriptorEnvironment bindings = new DeploymentDescriptorEnvironment("java:module/env/", mergedMetaData.getJndiEnvironmentRefsGroup()); deploymentUnit.putAttachment(org.jboss.as.ee.component.Attachments.MODULE_DEPLOYMENT_DESCRIPTOR_ENVIRONMENT, bindings); } //override module name if applicable if (mergedMetaData.getModuleName() != null && !mergedMetaData.getModuleName().isEmpty()) { final EEModuleDescription description = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); description.setModuleName(mergedMetaData.getModuleName()); } //WFLY-3102 Jakarta Enterprise Beans in WAR should inherit WAR's security domain if(mergedMetaData.getSecurityDomain() != null) { final EEModuleDescription description = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); description.setDefaultSecurityDomain(mergedMetaData.getSecurityDomain()); } //merge security roles from the ear DeploymentUnit parent = deploymentUnit.getParent(); if (parent != null) { final EarMetaData earMetaData = parent.getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA); if (earMetaData != null) { SecurityRolesMetaData earSecurityRolesMetaData = earMetaData.getSecurityRoles(); if(earSecurityRolesMetaData != null) { if(mergedMetaData.getSecurityRoles() == null) { mergedMetaData.setSecurityRoles(new SecurityRolesMetaData()); } SecurityRolesMetaDataMerger.merge(mergedMetaData.getSecurityRoles(), mergedMetaData.getSecurityRoles(), earSecurityRolesMetaData); } } } } /** * Utility class to associate the logical name with the JAR name, needed * during the order resolving. */ protected static class WebOrdering implements Serializable { private static final long serialVersionUID = 5603203103871892211L; protected String jar = null; protected String name = null; protected List<String> after = new ArrayList<String>(); protected List<String> before = new ArrayList<String>(); protected boolean afterOthers = false; protected boolean beforeOthers = false; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getAfter() { return after; } public void addAfter(String name) { after.add(name); } public List<String> getBefore() { return before; } public void addBefore(String name) { before.add(name); } public String getJar() { return jar; } public void setJar(String jar) { this.jar = jar; } public boolean isAfterOthers() { return afterOthers; } public void setAfterOthers(boolean afterOthers) { this.afterOthers = afterOthers; } public boolean isBeforeOthers() { return beforeOthers; } public void setBeforeOthers(boolean beforeOthers) { this.beforeOthers = beforeOthers; } } protected static class Ordering { protected WebOrdering ordering; protected Set<Ordering> after = new HashSet<Ordering>(); protected Set<Ordering> before = new HashSet<Ordering>(); protected boolean afterOthers = false; protected boolean beforeOthers = false; public boolean addAfter(Ordering ordering) { return after.add(ordering); } public boolean addBefore(Ordering ordering) { return before.add(ordering); } public void validate() { isBefore(new Ordering()); isAfter(new Ordering()); } /** * Check (recursively) if a fragment is before the specified fragment. * * @param ordering * @return */ public boolean isBefore(Ordering ordering) { return isBeforeInternal(ordering, new HashSet<Ordering>()); } protected boolean isBeforeInternal(Ordering ordering, Set<Ordering> checked) { checked.add(this); if (before.contains(ordering)) { return true; } Iterator<Ordering> beforeIterator = before.iterator(); while (beforeIterator.hasNext()) { Ordering check = beforeIterator.next(); if (checked.contains(check)) { throw new IllegalStateException(UndertowLogger.ROOT_LOGGER.invalidRelativeOrdering(this.ordering.getJar())); } if (check.isBeforeInternal(ordering, checked)) { return true; } } return false; } /** * Check (recursively) if a fragment is after the specified fragment. * * @param ordering * @return */ public boolean isAfter(Ordering ordering) { return isAfterInternal(ordering, new HashSet<Ordering>()); } protected boolean isAfterInternal(Ordering ordering, Set<Ordering> checked) { checked.add(this); if (after.contains(ordering)) { return true; } Iterator<Ordering> afterIterator = after.iterator(); while (afterIterator.hasNext()) { Ordering check = afterIterator.next(); if (checked.contains(check)) { throw new IllegalStateException(UndertowLogger.ROOT_LOGGER.invalidRelativeOrdering(this.ordering.getJar())); } if (check.isAfterInternal(ordering, checked)) { return true; } } return false; } /** * Check is a fragment marked as before others is after a fragment that * is not. * * @return true if a fragment marked as before others is after a * fragment that is not */ public boolean isLastBeforeOthers() { if (!beforeOthers) { throw new IllegalStateException(); } Iterator<Ordering> beforeIterator = before.iterator(); while (beforeIterator.hasNext()) { Ordering check = beforeIterator.next(); if (!check.beforeOthers) { return true; } else if (check.isLastBeforeOthers()) { return true; } } return false; } /** * Check is a fragment marked as after others is before a fragment that * is not. * * @return true if a fragment marked as after others is before a * fragment that is not */ public boolean isFirstAfterOthers() { if (!afterOthers) { throw new IllegalStateException(); } Iterator<Ordering> afterIterator = after.iterator(); while (afterIterator.hasNext()) { Ordering check = afterIterator.next(); if (!check.afterOthers) { return true; } else if (check.isFirstAfterOthers()) { return true; } } return false; } } /** * Generate the Jar processing order. * * @param webOrderings The list of orderings, as parsed from the fragments * @param order The generated order list */ protected static void resolveOrder(List<WebOrdering> webOrderings, List<String> order) { List<Ordering> work = new ArrayList<Ordering>(); // Populate the work Ordering list Iterator<WebOrdering> webOrderingsIterator = webOrderings.iterator(); while (webOrderingsIterator.hasNext()) { WebOrdering webOrdering = webOrderingsIterator.next(); Ordering ordering = new Ordering(); ordering.ordering = webOrdering; ordering.afterOthers = webOrdering.isAfterOthers(); ordering.beforeOthers = webOrdering.isBeforeOthers(); if (ordering.afterOthers && ordering.beforeOthers) { // Cannot be both after and before others throw new IllegalStateException(UndertowLogger.ROOT_LOGGER.invalidRelativeOrderingBeforeAndAfter(webOrdering.getJar())); } work.add(ordering); } // Create double linked relationships between the orderings, // and resolve names Iterator<Ordering> workIterator = work.iterator(); while (workIterator.hasNext()) { Ordering ordering = workIterator.next(); WebOrdering webOrdering = ordering.ordering; Iterator<String> after = webOrdering.getAfter().iterator(); while (after.hasNext()) { String name = after.next(); Iterator<Ordering> workIterator2 = work.iterator(); boolean found = false; while (workIterator2.hasNext()) { Ordering ordering2 = workIterator2.next(); if (name.equals(ordering2.ordering.getName())) { if (found) { // Duplicate name throw new IllegalStateException(UndertowLogger.ROOT_LOGGER.invalidRelativeOrderingDuplicateName(webOrdering.getJar())); } ordering.addAfter(ordering2); ordering2.addBefore(ordering); found = true; } } if (!found) { // Unknown name UndertowLogger.ROOT_LOGGER.invalidRelativeOrderingUnknownName(webOrdering.getJar()); } } Iterator<String> before = webOrdering.getBefore().iterator(); while (before.hasNext()) { String name = before.next(); Iterator<Ordering> workIterator2 = work.iterator(); boolean found = false; while (workIterator2.hasNext()) { Ordering ordering2 = workIterator2.next(); if (name.equals(ordering2.ordering.getName())) { if (found) { // Duplicate name throw new IllegalStateException(UndertowLogger.ROOT_LOGGER.invalidRelativeOrderingDuplicateName(webOrdering.getJar())); } ordering.addBefore(ordering2); ordering2.addAfter(ordering); found = true; } } if (!found) { // Unknown name UndertowLogger.ROOT_LOGGER.invalidRelativeOrderingUnknownName(webOrdering.getJar()); } } } // Validate ordering workIterator = work.iterator(); while (workIterator.hasNext()) { workIterator.next().validate(); } // Create three ordered lists that will then be merged List<Ordering> tempOrder = new ArrayList<Ordering>(); // Create the ordered list of fragments which are before others workIterator = work.iterator(); while (workIterator.hasNext()) { Ordering ordering = workIterator.next(); if (ordering.beforeOthers) { // Insert at the first possible position int insertAfter = -1; boolean last = ordering.isLastBeforeOthers(); int lastBeforeOthers = -1; for (int i = 0; i < tempOrder.size(); i++) { if (ordering.isAfter(tempOrder.get(i))) { insertAfter = i; } if (tempOrder.get(i).beforeOthers) { lastBeforeOthers = i; } } int pos = insertAfter; if (last && lastBeforeOthers > insertAfter) { pos = lastBeforeOthers; } tempOrder.add(pos + 1, ordering); } else if (ordering.afterOthers) { // Insert at the last possible element int insertBefore = tempOrder.size(); boolean first = ordering.isFirstAfterOthers(); int firstAfterOthers = tempOrder.size(); for (int i = tempOrder.size() - 1; i >= 0; i--) { if (ordering.isBefore(tempOrder.get(i))) { insertBefore = i; } if (tempOrder.get(i).afterOthers) { firstAfterOthers = i; } } int pos = insertBefore; if (first && firstAfterOthers < insertBefore) { pos = firstAfterOthers; } tempOrder.add(pos, ordering); } else { // Insert according to other already inserted elements int insertAfter = -1; int insertBefore = tempOrder.size(); for (int i = 0; i < tempOrder.size(); i++) { if (ordering.isAfter(tempOrder.get(i)) || tempOrder.get(i).beforeOthers) { insertAfter = i; } if (ordering.isBefore(tempOrder.get(i)) || tempOrder.get(i).afterOthers) { insertBefore = i; } } if (insertAfter > insertBefore) { // Conflicting order (probably caught earlier) throw new IllegalStateException(UndertowLogger.ROOT_LOGGER.invalidRelativeOrderingConflict(ordering.ordering.getJar())); } // Insert somewhere in the range tempOrder.add(insertAfter + 1, ordering); } } // Create the final ordered list Iterator<Ordering> tempOrderIterator = tempOrder.iterator(); while (tempOrderIterator.hasNext()) { Ordering ordering = tempOrderIterator.next(); order.add(ordering.ordering.getJar()); } } }
31,035
42.346369
163
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/JspPropertyGroupDescriptorImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import org.apache.jasper.deploy.JspPropertyGroup; import jakarta.servlet.descriptor.JspPropertyGroupDescriptor; import java.util.Collection; /** * @author Stuart Douglas */ public class JspPropertyGroupDescriptorImpl implements JspPropertyGroupDescriptor { private final JspPropertyGroup propertyGroup; public JspPropertyGroupDescriptorImpl(JspPropertyGroup propertyGroup) { this.propertyGroup = propertyGroup; } @Override public Collection<String> getUrlPatterns() { return propertyGroup.getUrlPatterns(); } @Override public String getElIgnored() { return propertyGroup.getElIgnored(); } @Override public String getPageEncoding() { return propertyGroup.getPageEncoding(); } @Override public String getScriptingInvalid() { return propertyGroup.getScriptingInvalid(); } @Override public String getIsXml() { return propertyGroup.getIsXml(); } @Override public Collection<String> getIncludePreludes() { return propertyGroup.getIncludePreludes(); } @Override public Collection<String> getIncludeCodas() { return propertyGroup.getIncludeCodas(); } @Override public String getDeferredSyntaxAllowedAsLiteral() { return propertyGroup.getDeferredSyntaxAllowedAsLiteral(); } @Override public String getTrimDirectiveWhitespaces() { return propertyGroup.getTrimDirectiveWhitespaces(); } @Override public String getDefaultContentType() { return propertyGroup.getDefaultContentType(); } @Override public String getBuffer() { return propertyGroup.getBuffer(); } @Override public String getErrorOnUndeclaredNamespace() { return propertyGroup.getErrorOnUndeclaredNamespace(); } @Override public String getErrorOnELNotFound() { return propertyGroup.getErrorOnELNotFound(); } }
3,034
27.632075
83
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/GlobalRequestControllerHandler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.List; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.requestcontroller.RunResult; import io.undertow.predicate.Predicate; import io.undertow.server.ExchangeCompletionListener; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.servlet.handlers.ServletRequestContext; /** * Undertow handler that hooks into the global request controller. * * @author Stuart Douglas */ public class GlobalRequestControllerHandler implements HttpHandler { public static final String ORG_WILDFLY_SUSPENDED = "org.wildfly.suspended"; private final HttpHandler next; private final ControlPoint entryPoint; private final List<Predicate> allowSuspendedRequests; private final ExchangeCompletionListener listener = new ExchangeCompletionListener() { @Override public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) { entryPoint.requestComplete(); nextListener.proceed(); } }; public GlobalRequestControllerHandler(HttpHandler next, ControlPoint entryPoint, List<Predicate> allowSuspendedRequests) { this.next = next; this.entryPoint = entryPoint; this.allowSuspendedRequests = allowSuspendedRequests; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { RunResult result = entryPoint.beginRequest(); try { if(result == RunResult.RUN) { next.handleRequest(exchange); } else { boolean allowed = false; for(Predicate allow : allowSuspendedRequests) { if(allow.resolve(exchange)) { allowed = true; ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); if(src != null) { src.getServletRequest().setAttribute(ORG_WILDFLY_SUSPENDED, "true"); } next.handleRequest(exchange); break; } } if (!allowed) { exchange.setStatusCode(503); exchange.endExchange(); } } } finally { if(result == RunResult.RUN && (exchange.isComplete() || !exchange.isDispatched())) { entryPoint.requestComplete(); } else if(result == RunResult.RUN) { exchange.addExchangeCompleteListener(listener); } } } public static HandlerWrapper wrapper(final ControlPoint entryPoint, List<Predicate> allowSuspendedRequests) { return handler -> new GlobalRequestControllerHandler(handler, entryPoint, allowSuspendedRequests); } public HttpHandler getNext() { return next; } }
4,080
38.240385
126
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/JBossWebParsingDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.io.IOException; import java.io.InputStream; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.ee.structure.JBossDescriptorPropertyReplacement; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.parser.jbossweb.JBossWebMetaDataParser; import org.jboss.metadata.parser.util.NoopXMLResolver; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.jboss.ValveMetaData; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author Jean-Frederic Clere */ public class JBossWebParsingDeploymentProcessor implements DeploymentUnitProcessor { private static final String JBOSS_WEB_XML = "WEB-INF/jboss-web.xml"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } final VirtualFile deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot(); final VirtualFile jbossWebXml = deploymentRoot.getChild(JBOSS_WEB_XML); WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); assert warMetaData != null; if (jbossWebXml.exists()) { InputStream is = null; try { is = jbossWebXml.openStream(); final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setXMLResolver(NoopXMLResolver.create()); XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is); final JBossWebMetaData jBossWebMetaData = JBossWebMetaDataParser.parse(xmlReader, JBossDescriptorPropertyReplacement.propertyReplacer(deploymentUnit)); warMetaData.setJBossWebMetaData(jBossWebMetaData); // if the jboss-web.xml has a distinct-name configured, then attach the value to this // deployment unit if(jBossWebMetaData.getValves() != null) { for(ValveMetaData valve : jBossWebMetaData.getValves()) { UndertowLogger.ROOT_LOGGER.unsupportedValveFeature(valve.getValveClass()); } } if (jBossWebMetaData.getDistinctName() != null) { deploymentUnit.putAttachment(org.jboss.as.ee.structure.Attachments.DISTINCT_NAME, jBossWebMetaData.getDistinctName()); } } catch (XMLStreamException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(jbossWebXml.toString(), e.getLocation().getLineNumber(), e.getLocation().getColumnNumber()), e); } catch (IOException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(jbossWebXml.toString()), e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } } } else { //jboss web embedded inside jboss-all.xml final JBossWebMetaData jbMeta = deploymentUnit.getAttachment(WebJBossAllParser.ATTACHMENT_KEY); if(jbMeta != null) { warMetaData.setJBossWebMetaData(jbMeta); } } } }
5,185
47.018519
208
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityDomainResolvingProcessor.java
/* * Copyright 2020 Red Hat, Inc. * * 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.wildfly.extension.undertow.deployment; import static org.jboss.as.server.security.SecurityMetaData.ATTACHMENT_KEY; import static org.wildfly.extension.undertow.Capabilities.REF_LEGACY_SECURITY; import static org.wildfly.extension.undertow.deployment.UndertowAttachments.RESOLVED_SECURITY_DOMAIN; import java.util.function.Predicate; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.security.SecurityMetaData; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.ear.jboss.JBossAppMetaData; import org.jboss.metadata.ear.spec.EarMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Constants; /** * A {@code DeploymentUnitProcessor} to resolve the security domain name for the deployment. * * @author <a href="mailto:[email protected]">Darran Lofthouse</a> */ public class SecurityDomainResolvingProcessor implements DeploymentUnitProcessor { private static final String JAAS_CONTEXT_ROOT = "java:jboss/jaas/"; private static final String JASPI_CONTEXT_ROOT = "java:jboss/jbsx/"; private static final String LEGACY_JAAS_CONTEXT_ROOT = "java:/jaas/"; private final String defaultSecurityDomain; private final Predicate<String> mappedSecurityDomain; public SecurityDomainResolvingProcessor(final String defaultSecurityDomain, final Predicate<String> mappedSecurityDomain) { this.defaultSecurityDomain = defaultSecurityDomain; this.mappedSecurityDomain = mappedSecurityDomain; } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData == null) { return; } final SecurityMetaData securityMetaData = deploymentUnit.getAttachment(ATTACHMENT_KEY); if (securityMetaData != null && securityMetaData.getSecurityDomain() != null) { return; // The SecurityDomain is already defined. } final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData(); String securityDomain = metaData.getSecurityDomain(); if (securityDomain == null) { securityDomain = getJBossAppSecurityDomain(deploymentUnit); } securityDomain = securityDomain == null ? defaultSecurityDomain : unprefixSecurityDomain(securityDomain); if (securityDomain != null) { if (mappedSecurityDomain.test(securityDomain)) { ServiceName securityDomainName = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT) .getCapabilityServiceName( Capabilities.CAPABILITY_APPLICATION_SECURITY_DOMAIN, securityDomain).append(Constants.SECURITY_DOMAIN); if (securityMetaData != null) { securityMetaData.setSecurityDomain(securityDomainName); } deploymentUnit.putAttachment(RESOLVED_SECURITY_DOMAIN, securityDomain); } else if (legacySecurityInstalled(deploymentUnit)) { deploymentUnit.putAttachment(RESOLVED_SECURITY_DOMAIN, securityDomain); } } } private static boolean legacySecurityInstalled(final DeploymentUnit deploymentUnit) { final CapabilityServiceSupport capabilities = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); return capabilities.hasCapability(REF_LEGACY_SECURITY); } @Override public void undeploy(DeploymentUnit deploymentUnit) { deploymentUnit.removeAttachment(RESOLVED_SECURITY_DOMAIN); } /** * Try to obtain the security domain configured in jboss-app.xml at the ear level if available */ private static String getJBossAppSecurityDomain(final DeploymentUnit deploymentUnit) { String securityDomain = null; DeploymentUnit parent = deploymentUnit.getParent(); if (parent != null) { final EarMetaData jbossAppMetaData = parent.getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA); if (jbossAppMetaData instanceof JBossAppMetaData) { securityDomain = ((JBossAppMetaData) jbossAppMetaData).getSecurityDomain(); } } return securityDomain != null ? securityDomain.trim() : null; } public static String unprefixSecurityDomain(String securityDomain) { String result = null; if (securityDomain != null) { if (securityDomain.startsWith(JAAS_CONTEXT_ROOT)) result = securityDomain.substring(JAAS_CONTEXT_ROOT.length()); else if (securityDomain.startsWith(JASPI_CONTEXT_ROOT)) result = securityDomain.substring(JASPI_CONTEXT_ROOT.length()); else if (securityDomain.startsWith(LEGACY_JAAS_CONTEXT_ROOT)) result = securityDomain.substring(LEGACY_JAAS_CONTEXT_ROOT.length()); else result = securityDomain; } return result; } }
6,252
43.664286
127
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowServletContainerDependencyProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.wildfly.extension.undertow.UndertowService; /** * @author Stuart Douglas */ public class UndertowServletContainerDependencyProcessor implements DeploymentUnitProcessor { private final String defaultServletContainer; public UndertowServletContainerDependencyProcessor(String defaultContainer) { this.defaultServletContainer = defaultContainer; } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData != null) { String servletContainerName = defaultServletContainer; final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData(); if(metaData != null && metaData.getServletContainerName() != null) { servletContainerName = metaData.getServletContainerName(); } phaseContext.addDeploymentDependency(UndertowService.SERVLET_CONTAINER.append(servletContainerName), UndertowAttachments.SERVLET_CONTAINER_SERVICE); } } }
2,635
44.448276
160
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/ComponentStartupCountdownHandler.java
/* * Copyright 2018 Red Hat, Inc, and 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.wildfly.extension.undertow.deployment; import io.undertow.server.Connectors; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.ResponseCodeHandler; import org.jboss.as.ee.component.deployers.StartupCountdown; import java.util.concurrent.atomic.AtomicBoolean; /** * Queue up requests until all startup components are initialized successfully. If any of the components failed to * startup, all queued up and any subsequent requests are terminated with a 500 error code. * * Based on {@code io.undertow.server.handlers.RequestLimitingHandler} * * @author [email protected] */ public class ComponentStartupCountdownHandler implements HttpHandler { private final HttpHandler wrappedHandler; private final AtomicBoolean started = new AtomicBoolean(false); private final HttpHandler startupFailedHandler = ResponseCodeHandler.HANDLE_500; public ComponentStartupCountdownHandler(final HttpHandler handler, StartupCountdown countdown) { this.wrappedHandler = handler; countdown.addCallback(()->started.set(true)); } @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (started.get()) { wrappedHandler.handleRequest(exchange); } else { Connectors.executeRootHandler(startupFailedHandler, exchange); } } }
2,056
35.087719
114
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/WarAnnotationDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import jakarta.annotation.security.DeclareRoles; import jakarta.annotation.security.RunAs; import jakarta.servlet.annotation.MultipartConfig; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.annotation.WebListener; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import org.jboss.annotation.javaee.Descriptions; import org.jboss.annotation.javaee.DisplayNames; import org.jboss.annotation.javaee.Icons; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.AnnotationIndexUtils; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.web.common.WarMetaData; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.Index; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.DescriptionImpl; import org.jboss.metadata.javaee.spec.DescriptionsImpl; import org.jboss.metadata.javaee.spec.DisplayNameImpl; import org.jboss.metadata.javaee.spec.DisplayNamesImpl; import org.jboss.metadata.javaee.spec.IconImpl; import org.jboss.metadata.javaee.spec.IconsImpl; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.RunAsMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleMetaData; import org.jboss.metadata.javaee.spec.SecurityRolesMetaData; import org.jboss.metadata.web.spec.AnnotationMetaData; import org.jboss.metadata.web.spec.AnnotationsMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FiltersMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.ServletMetaData; import org.jboss.metadata.web.spec.ServletSecurityMetaData; import org.jboss.metadata.web.spec.ServletsMetaData; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.WebMetaData; import org.jboss.modules.ModuleIdentifier; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * Web annotation deployment processor. * * @author Emanuel Muckenhuber * @author Remy Maucherat */ public class WarAnnotationDeploymentProcessor implements DeploymentUnitProcessor { private static final DotName webFilter = DotName.createSimple(WebFilter.class.getName()); private static final DotName webListener = DotName.createSimple(WebListener.class.getName()); private static final DotName webServlet = DotName.createSimple(WebServlet.class.getName()); private static final DotName runAs = DotName.createSimple(RunAs.class.getName()); private static final DotName declareRoles = DotName.createSimple(DeclareRoles.class.getName()); private static final DotName multipartConfig = DotName.createSimple(MultipartConfig.class.getName()); private static final DotName servletSecurity = DotName.createSimple(ServletSecurity.class.getName()); private static final DotName servletDotName = DotName.createSimple(HttpServlet.class.getName()); // This list defines some annotations that won't get processed if they are added to a servlet according to Servlet Specification // but sometimes users may misuse them, users will get a warning log in such scenarios. // https://issues.redhat.com/browse/WFLY-14307 private static final List<DotName> badAnnotationsInServlet = new ArrayList<>(); static { badAnnotationsInServlet.add(DotName.createSimple("org.jboss.ejb3.annotation.RunAsPrincipal")); } /** * Process web annotations. */ public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); assert warMetaData != null; Map<String, WebMetaData> annotationsMetaData = warMetaData.getAnnotationsMetaData(); if (annotationsMetaData == null) { annotationsMetaData = new HashMap<String, WebMetaData>(); warMetaData.setAnnotationsMetaData(annotationsMetaData); } Map<ResourceRoot, Index> indexes = AnnotationIndexUtils.getAnnotationIndexes(deploymentUnit); // Process lib/*.jar for (final Entry<ResourceRoot, Index> entry : indexes.entrySet()) { final Index jarIndex = entry.getValue(); annotationsMetaData.put(entry.getKey().getRootName(), processAnnotations(jarIndex)); } Map<ModuleIdentifier, CompositeIndex> additionalModelAnnotations = deploymentUnit.getAttachment(Attachments.ADDITIONAL_ANNOTATION_INDEXES_BY_MODULE); if (additionalModelAnnotations != null) { final List<WebMetaData> additional = new ArrayList<WebMetaData>(); for (Entry<ModuleIdentifier, CompositeIndex> entry : additionalModelAnnotations.entrySet()) { for(Index index : entry.getValue().getIndexes()) { additional.add(processAnnotations(index)); } } warMetaData.setAdditionalModuleAnnotationsMetadata(additional); } } /** * Process a single index. * * @param index the annotation index * * @throws DeploymentUnitProcessingException */ protected WebMetaData processAnnotations(Index index) throws DeploymentUnitProcessingException { WebMetaData metaData = new WebMetaData(); // @WebServlet final List<AnnotationInstance> webServletAnnotations = index.getAnnotations(webServlet); if (webServletAnnotations != null && !webServletAnnotations.isEmpty()) { ServletsMetaData servlets = new ServletsMetaData(); List<ServletMappingMetaData> servletMappings = new ArrayList<ServletMappingMetaData>(); for (final AnnotationInstance annotation : webServletAnnotations) { ServletMetaData servlet = new ServletMetaData(); AnnotationTarget target = annotation.target(); if (!(target instanceof ClassInfo)) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebServletAnnotation(target)); } ClassInfo classInfo = ClassInfo.class.cast(target); servlet.setServletClass(classInfo.toString()); AnnotationValue nameValue = annotation.value("name"); if (nameValue == null || nameValue.asString().isEmpty()) { servlet.setName(classInfo.toString()); } else { servlet.setName(nameValue.asString()); } AnnotationValue loadOnStartup = annotation.value("loadOnStartup"); if (loadOnStartup != null && loadOnStartup.asInt() >= 0) { servlet.setLoadOnStartupInt(loadOnStartup.asInt()); } AnnotationValue asyncSupported = annotation.value("asyncSupported"); if (asyncSupported != null) { servlet.setAsyncSupported(asyncSupported.asBoolean()); } AnnotationValue initParamsValue = annotation.value("initParams"); if (initParamsValue != null) { AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray(); if (initParamsAnnotations != null && initParamsAnnotations.length > 0) { List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>(); for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) { ParamValueMetaData initParam = new ParamValueMetaData(); AnnotationValue initParamName = initParamsAnnotation.value("name"); AnnotationValue initParamValue = initParamsAnnotation.value(); if (initParamName == null || initParamValue == null) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebInitParamAnnotation(target)); } AnnotationValue initParamDescription = initParamsAnnotation.value("description"); initParam.setParamName(initParamName.asString()); initParam.setParamValue(initParamValue.asString()); if (initParamDescription != null) { Descriptions descriptions = getDescription(initParamDescription.asString()); if (descriptions != null) { initParam.setDescriptions(descriptions); } } initParams.add(initParam); } servlet.setInitParam(initParams); } } AnnotationValue descriptionValue = annotation.value("description"); AnnotationValue displayNameValue = annotation.value("displayName"); AnnotationValue smallIconValue = annotation.value("smallIcon"); AnnotationValue largeIconValue = annotation.value("largeIcon"); DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString()); if (descriptionGroup != null) { servlet.setDescriptionGroup(descriptionGroup); } ServletMappingMetaData servletMapping = new ServletMappingMetaData(); servletMapping.setServletName(servlet.getName()); List<String> urlPatterns = new ArrayList<String>(); AnnotationValue urlPatternsValue = annotation.value("urlPatterns"); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } urlPatternsValue = annotation.value(); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } if (!urlPatterns.isEmpty()) { servletMapping.setUrlPatterns(urlPatterns); servletMappings.add(servletMapping); } servlets.add(servlet); } metaData.setServlets(servlets); metaData.setServletMappings(servletMappings); } // @WebFilter final List<AnnotationInstance> webFilterAnnotations = index.getAnnotations(webFilter); if (webFilterAnnotations != null && !webFilterAnnotations.isEmpty()) { FiltersMetaData filters = new FiltersMetaData(); List<FilterMappingMetaData> filterMappings = new ArrayList<FilterMappingMetaData>(); for (final AnnotationInstance annotation : webFilterAnnotations) { FilterMetaData filter = new FilterMetaData(); AnnotationTarget target = annotation.target(); if (!(target instanceof ClassInfo)) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebFilterAnnotation(target)); } ClassInfo classInfo = ClassInfo.class.cast(target); filter.setFilterClass(classInfo.toString()); AnnotationValue nameValue = annotation.value("filterName"); if (nameValue == null || nameValue.asString().isEmpty()) { filter.setName(classInfo.toString()); } else { filter.setName(nameValue.asString()); } AnnotationValue asyncSupported = annotation.value("asyncSupported"); if (asyncSupported != null) { filter.setAsyncSupported(asyncSupported.asBoolean()); } AnnotationValue initParamsValue = annotation.value("initParams"); if (initParamsValue != null) { AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray(); if (initParamsAnnotations != null && initParamsAnnotations.length > 0) { List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>(); for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) { ParamValueMetaData initParam = new ParamValueMetaData(); AnnotationValue initParamName = initParamsAnnotation.value("name"); AnnotationValue initParamValue = initParamsAnnotation.value(); if (initParamName == null || initParamValue == null) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebInitParamAnnotation(target)); } AnnotationValue initParamDescription = initParamsAnnotation.value("description"); initParam.setParamName(initParamName.asString()); initParam.setParamValue(initParamValue.asString()); if (initParamDescription != null) { Descriptions descriptions = getDescription(initParamDescription.asString()); if (descriptions != null) { initParam.setDescriptions(descriptions); } } initParams.add(initParam); } filter.setInitParam(initParams); } } AnnotationValue descriptionValue = annotation.value("description"); AnnotationValue displayNameValue = annotation.value("displayName"); AnnotationValue smallIconValue = annotation.value("smallIcon"); AnnotationValue largeIconValue = annotation.value("largeIcon"); DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString()); if (descriptionGroup != null) { filter.setDescriptionGroup(descriptionGroup); } filters.add(filter); FilterMappingMetaData filterMapping = new FilterMappingMetaData(); filterMapping.setFilterName(filter.getName()); List<String> urlPatterns = new ArrayList<String>(); List<String> servletNames = new ArrayList<String>(); List<DispatcherType> dispatchers = new ArrayList<DispatcherType>(); AnnotationValue urlPatternsValue = annotation.value("urlPatterns"); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } urlPatternsValue = annotation.value(); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } if (!urlPatterns.isEmpty()) { filterMapping.setUrlPatterns(urlPatterns); } AnnotationValue servletNamesValue = annotation.value("servletNames"); if (servletNamesValue != null) { for (String servletName : servletNamesValue.asStringArray()) { servletNames.add(servletName); } } if (!servletNames.isEmpty()) { filterMapping.setServletNames(servletNames); } AnnotationValue dispatcherTypesValue = annotation.value("dispatcherTypes"); if (dispatcherTypesValue != null) { for (String dispatcherValue : dispatcherTypesValue.asEnumArray()) { dispatchers.add(DispatcherType.valueOf(dispatcherValue)); } } if (!dispatchers.isEmpty()) { filterMapping.setDispatchers(dispatchers); } if (!urlPatterns.isEmpty() || !servletNames.isEmpty()) { filterMappings.add(filterMapping); } } metaData.setFilters(filters); metaData.setFilterMappings(filterMappings); } // @WebListener final List<AnnotationInstance> webListenerAnnotations = index.getAnnotations(webListener); if (webListenerAnnotations != null && !webListenerAnnotations.isEmpty()) { List<ListenerMetaData> listeners = new ArrayList<ListenerMetaData>(); for (final AnnotationInstance annotation : webListenerAnnotations) { ListenerMetaData listener = new ListenerMetaData(); AnnotationTarget target = annotation.target(); if (!(target instanceof ClassInfo)) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebListenerAnnotation(target)); } ClassInfo classInfo = ClassInfo.class.cast(target); listener.setListenerClass(classInfo.toString()); AnnotationValue descriptionValue = annotation.value(); if (descriptionValue != null) { DescriptionGroupMetaData descriptionGroup = getDescriptionGroup(descriptionValue.asString()); if (descriptionGroup != null) { listener.setDescriptionGroup(descriptionGroup); } } listeners.add(listener); } metaData.setListeners(listeners); } // @RunAs final List<AnnotationInstance> runAsAnnotations = index.getAnnotations(runAs); if (runAsAnnotations != null && !runAsAnnotations.isEmpty()) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : runAsAnnotations) { AnnotationTarget target = annotation.target(); if (!(target instanceof ClassInfo)) { continue; } ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } if (annotation.value() == null) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidRunAsAnnotation(target)); } RunAsMetaData runAs = new RunAsMetaData(); runAs.setRoleName(annotation.value().asString()); annotationMD.setRunAs(runAs); } } // @DeclareRoles final List<AnnotationInstance> declareRolesAnnotations = index.getAnnotations(declareRoles); if (declareRolesAnnotations != null && !declareRolesAnnotations.isEmpty()) { SecurityRolesMetaData securityRoles = metaData.getSecurityRoles(); if (securityRoles == null) { securityRoles = new SecurityRolesMetaData(); metaData.setSecurityRoles(securityRoles); } for (final AnnotationInstance annotation : declareRolesAnnotations) { if (annotation.value() == null) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidDeclareRolesAnnotation(annotation.target())); } for (String role : annotation.value().asStringArray()) { SecurityRoleMetaData sr = new SecurityRoleMetaData(); sr.setRoleName(role); securityRoles.add(sr); } } } // @MultipartConfig final List<AnnotationInstance> multipartConfigAnnotations = index.getAnnotations(multipartConfig); if (multipartConfigAnnotations != null && !multipartConfigAnnotations.isEmpty()) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : multipartConfigAnnotations) { AnnotationTarget target = annotation.target(); if (!(target instanceof ClassInfo)) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidMultipartConfigAnnotation(target)); } ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } MultipartConfigMetaData multipartConfig = new MultipartConfigMetaData(); AnnotationValue locationValue = annotation.value("location"); if (locationValue != null && locationValue.asString().length() > 0) { multipartConfig.setLocation(locationValue.asString()); } AnnotationValue maxFileSizeValue = annotation.value("maxFileSize"); if (maxFileSizeValue != null && maxFileSizeValue.asLong() != -1L) { multipartConfig.setMaxFileSize(maxFileSizeValue.asLong()); } AnnotationValue maxRequestSizeValue = annotation.value("maxRequestSize"); if (maxRequestSizeValue != null && maxRequestSizeValue.asLong() != -1L) { multipartConfig.setMaxRequestSize(maxRequestSizeValue.asLong()); } AnnotationValue fileSizeThresholdValue = annotation.value("fileSizeThreshold"); if (fileSizeThresholdValue != null && fileSizeThresholdValue.asInt() != 0) { multipartConfig.setFileSizeThreshold(fileSizeThresholdValue.asInt()); } annotationMD.setMultipartConfig(multipartConfig); } } // @ServletSecurity final List<AnnotationInstance> servletSecurityAnnotations = index.getAnnotations(servletSecurity); if (servletSecurityAnnotations != null && !servletSecurityAnnotations.isEmpty()) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : servletSecurityAnnotations) { AnnotationTarget target = annotation.target(); if (!(target instanceof ClassInfo)) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidServletSecurityAnnotation(target)); } ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } ServletSecurityMetaData servletSecurity = new ServletSecurityMetaData(); AnnotationValue httpConstraintValue = annotation.value(); List<String> rolesAllowed = new ArrayList<String>(); if (httpConstraintValue != null) { AnnotationInstance httpConstraint = httpConstraintValue.asNested(); AnnotationValue httpConstraintERSValue = httpConstraint.value(); if (httpConstraintERSValue != null) { servletSecurity.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpConstraintERSValue.asEnum())); } AnnotationValue httpConstraintTGValue = httpConstraint.value("transportGuarantee"); if (httpConstraintTGValue != null) { servletSecurity.setTransportGuarantee(TransportGuaranteeType.valueOf(httpConstraintTGValue.asEnum())); } AnnotationValue rolesAllowedValue = httpConstraint.value("rolesAllowed"); if (rolesAllowedValue != null) { for (String role : rolesAllowedValue.asStringArray()) { rolesAllowed.add(role); } } } servletSecurity.setRolesAllowed(rolesAllowed); AnnotationValue httpMethodConstraintsValue = annotation.value("httpMethodConstraints"); if (httpMethodConstraintsValue != null) { AnnotationInstance[] httpMethodConstraints = httpMethodConstraintsValue.asNestedArray(); if (httpMethodConstraints.length > 0) { List<HttpMethodConstraintMetaData> methodConstraints = new ArrayList<HttpMethodConstraintMetaData>(); for (AnnotationInstance httpMethodConstraint : httpMethodConstraints) { HttpMethodConstraintMetaData methodConstraint = new HttpMethodConstraintMetaData(); AnnotationValue httpMethodConstraintValue = httpMethodConstraint.value(); if (httpMethodConstraintValue != null) { methodConstraint.setMethod(httpMethodConstraintValue.asString()); } AnnotationValue httpMethodConstraintERSValue = httpMethodConstraint.value("emptyRoleSemantic"); if (httpMethodConstraintERSValue != null) { methodConstraint.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpMethodConstraintERSValue.asEnum())); } AnnotationValue httpMethodConstraintTGValue = httpMethodConstraint.value("transportGuarantee"); if (httpMethodConstraintTGValue != null) { methodConstraint.setTransportGuarantee(TransportGuaranteeType.valueOf(httpMethodConstraintTGValue.asEnum())); } AnnotationValue rolesAllowedValue = httpMethodConstraint.value("rolesAllowed"); rolesAllowed = new ArrayList<String>(); if (rolesAllowedValue != null) { for (String role : rolesAllowedValue.asStringArray()) { rolesAllowed.add(role); } } methodConstraint.setRolesAllowed(rolesAllowed); methodConstraints.add(methodConstraint); } servletSecurity.setHttpMethodConstraints(methodConstraints); } } annotationMD.setServletSecurity(servletSecurity); } } // bad annotations for (DotName badAnnotation: badAnnotationsInServlet) { final List<AnnotationInstance> badAnnotationInstance = index.getAnnotations(badAnnotation); if (badAnnotationInstance != null && !badAnnotationInstance.isEmpty()) { Collection<ClassInfo> servlets = index.getAllKnownSubclasses(servletDotName); for (AnnotationInstance annotation: badAnnotationInstance) { AnnotationTarget target = annotation.target(); if (target instanceof ClassInfo) { ClassInfo classInfo = (ClassInfo) target; if (servlets.contains(classInfo)) { UndertowLogger.ROOT_LOGGER.badAnnotationOnServlet(badAnnotation.toString(), classInfo.toString()); } } } } } return metaData; } protected Descriptions getDescription(String description) { DescriptionsImpl descriptions = null; if (description.length() > 0) { DescriptionImpl di = new DescriptionImpl(); di.setDescription(description); descriptions = new DescriptionsImpl(); descriptions.add(di); } return descriptions; } protected DisplayNames getDisplayName(String displayName) { DisplayNamesImpl displayNames = null; if (displayName.length() > 0) { DisplayNameImpl dn = new DisplayNameImpl(); dn.setDisplayName(displayName); displayNames = new DisplayNamesImpl(); displayNames.add(dn); } return displayNames; } protected Icons getIcons(String smallIcon, String largeIcon) { IconsImpl icons = null; if (smallIcon.length() > 0 || largeIcon.length() > 0) { IconImpl i = new IconImpl(); i.setSmallIcon(smallIcon); i.setLargeIcon(largeIcon); icons = new IconsImpl(); icons.add(i); } return icons; } protected DescriptionGroupMetaData getDescriptionGroup(String description) { DescriptionGroupMetaData dg = null; if (description.length() > 0) { dg = new DescriptionGroupMetaData(); Descriptions descriptions = getDescription(description); dg.setDescriptions(descriptions); } return dg; } protected DescriptionGroupMetaData getDescriptionGroup(String description, String displayName, String smallIcon, String largeIcon) { DescriptionGroupMetaData dg = null; if (description.length() > 0 || displayName.length() > 0 || smallIcon.length() > 0 || largeIcon.length() > 0) { dg = new DescriptionGroupMetaData(); Descriptions descriptions = getDescription(description); if (descriptions != null) dg.setDescriptions(descriptions); DisplayNames displayNames = getDisplayName(displayName); if (displayNames != null) dg.setDisplayNames(displayNames); Icons icons = getIcons(smallIcon, largeIcon); if (icons != null) dg.setIcons(icons); } return dg; } }
34,603
54.3664
157
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ModClusterServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import static org.wildfly.extension.undertow.logging.UndertowLogger.ROOT_LOGGER; import java.io.IOException; import java.net.InetAddress; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import javax.net.ssl.SSLContext; import io.undertow.UndertowOptions; import io.undertow.client.UndertowClient; import io.undertow.protocols.ssl.UndertowXnioSsl; import io.undertow.server.handlers.proxy.RouteParsingStrategy; import io.undertow.server.handlers.proxy.mod_cluster.MCMPConfig; import io.undertow.server.handlers.proxy.mod_cluster.ModCluster; import org.jboss.as.clustering.controller.CommonUnaryRequirement; import org.jboss.as.clustering.controller.ResourceServiceConfigurator; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.registry.Resource; import org.jboss.as.network.SocketBinding; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.CompositeDependency; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.extension.io.IOServices; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.xnio.OptionMap; import org.xnio.Options; import org.xnio.XnioWorker; import org.xnio.ssl.XnioSsl; /** * Configures a service that provides both {@link ModCluster} and {@link MCMPConfig}. * @author Paul Ferraro */ public class ModClusterServiceConfigurator extends ModClusterServiceNameProvider implements ResourceServiceConfigurator, Supplier<Map.Entry<ModCluster, MCMPConfig>>, Consumer<Map.Entry<ModCluster, MCMPConfig>> { private static final Map<PathElement, RouteParsingStrategy> ROUTE_PARSING_STRATEGIES = Map.of( NoAffinityResourceDefinition.PATH, RouteParsingStrategy.NONE, SingleAffinityResourceDefinition.PATH, RouteParsingStrategy.SINGLE, RankedAffinityResourceDefinition.PATH, RouteParsingStrategy.RANKED); private volatile SupplierDependency<XnioWorker> worker; private volatile SupplierDependency<SocketBinding> managementBinding; private volatile SupplierDependency<SocketBinding> advertiseBinding; private volatile SupplierDependency<SSLContext> sslContext; private volatile OptionMap clientOptions; private volatile RouteParsingStrategy routeParsingStrategy; private volatile String routeDelimiter; private volatile long healthCheckInterval; private volatile int maxRequestTime; private volatile long brokenNodeTimeout; private volatile int advertiseFrequency; private volatile String advertisePath; private volatile String advertiseProtocol; private volatile String securityKey; private volatile int maxConnections; private volatile int cachedConnections; private volatile int connectionIdleTimeout; private volatile int requestQueueSize; private volatile boolean useAlias; private volatile int maxRetries; private volatile FailoverStrategy failoverStrategy; ModClusterServiceConfigurator(PathAddress address) { super(address); } ServiceName getConfigServiceName() { return this.getServiceName().append("config"); } @Override public ServiceConfigurator configure(OperationContext context, ModelNode model) throws OperationFailedException { if (ModClusterDefinition.SECURITY_REALM.resolveModelAttribute(context, model).isDefined()) { ROOT_LOGGER.runtimeSecurityRealmUnsupported(); } String sslContext = ModClusterDefinition.SSL_CONTEXT.resolveModelAttribute(context, model).asStringOrNull(); this.sslContext = (sslContext != null) ? new ServiceSupplierDependency<>(CommonUnaryRequirement.SSL_CONTEXT.getServiceName(context, sslContext)) : null; OptionMap.Builder builder = OptionMap.builder(); Integer packetSize = ModClusterDefinition.MAX_AJP_PACKET_SIZE.resolveModelAttribute(context, model).asIntOrNull(); if (packetSize != null) { builder.set(UndertowOptions.MAX_AJP_PACKET_SIZE, packetSize); } builder.set(UndertowOptions.ENABLE_HTTP2, ModClusterDefinition.ENABLE_HTTP2.resolveModelAttribute(context, model).asBoolean()); ModClusterDefinition.HTTP2_ENABLE_PUSH.resolveOption(context, model, builder); ModClusterDefinition.HTTP2_HEADER_TABLE_SIZE.resolveOption(context, model, builder); ModClusterDefinition.HTTP2_INITIAL_WINDOW_SIZE.resolveOption(context, model, builder); ModClusterDefinition.HTTP2_MAX_CONCURRENT_STREAMS.resolveOption(context, model, builder); ModClusterDefinition.HTTP2_MAX_FRAME_SIZE.resolveOption(context, model, builder); ModClusterDefinition.HTTP2_MAX_HEADER_LIST_SIZE.resolveOption(context, model, builder); this.clientOptions = builder.getMap(); Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); Set<Resource.ResourceEntry> children = resource.getChildren(AffinityResourceDefinition.WILDCARD_PATH.getKey()); if (children.size() != 1) { throw new IllegalStateException(); } Resource.ResourceEntry entry = children.iterator().next(); this.routeParsingStrategy = ROUTE_PARSING_STRATEGIES.get(entry.getPathElement()); this.routeDelimiter = (this.routeParsingStrategy == RouteParsingStrategy.RANKED) ? RankedAffinityResourceDefinition.Attribute.DELIMITER.resolveModelAttribute(context, entry.getModel()).asString() : null; String managementBinding = ModClusterDefinition.MANAGEMENT_SOCKET_BINDING.resolveModelAttribute(context, model).asString(); this.managementBinding = new ServiceSupplierDependency<>(CommonUnaryRequirement.SOCKET_BINDING.getServiceName(context, managementBinding)); String advertiseBinding = ModClusterDefinition.ADVERTISE_SOCKET_BINDING.resolveModelAttribute(context, model).asStringOrNull(); this.advertiseBinding = (advertiseBinding != null) ? new ServiceSupplierDependency<>(CommonUnaryRequirement.SOCKET_BINDING.getServiceName(context, advertiseBinding)) : null; String worker = ModClusterDefinition.WORKER.resolveModelAttribute(context, model).asString(); this.worker = new ServiceSupplierDependency<>(context.getCapabilityServiceName(IOServices.IO_WORKER_CAPABILITY_NAME, XnioWorker.class, worker)); this.healthCheckInterval = ModClusterDefinition.HEALTH_CHECK_INTERVAL.resolveModelAttribute(context, model).asInt(); this.maxRequestTime = ModClusterDefinition.MAX_REQUEST_TIME.resolveModelAttribute(context, model).asInt(); this.brokenNodeTimeout = ModClusterDefinition.BROKEN_NODE_TIMEOUT.resolveModelAttribute(context, model).asLong(); this.advertiseFrequency = ModClusterDefinition.ADVERTISE_FREQUENCY.resolveModelAttribute(context, model).asInt(); this.advertisePath = ModClusterDefinition.ADVERTISE_PATH.resolveModelAttribute(context, model).asString(); this.advertiseProtocol = ModClusterDefinition.ADVERTISE_PROTOCOL.resolveModelAttribute(context, model).asString(); this.securityKey = ModClusterDefinition.SECURITY_KEY.resolveModelAttribute(context, model).asStringOrNull(); this.maxConnections = ModClusterDefinition.CONNECTIONS_PER_THREAD.resolveModelAttribute(context, model).asInt(); this.cachedConnections = ModClusterDefinition.CACHED_CONNECTIONS_PER_THREAD.resolveModelAttribute(context, model).asInt(); this.connectionIdleTimeout = ModClusterDefinition.CONNECTION_IDLE_TIMEOUT.resolveModelAttribute(context, model).asInt(); this.requestQueueSize = ModClusterDefinition.REQUEST_QUEUE_SIZE.resolveModelAttribute(context, model).asInt(); this.useAlias = ModClusterDefinition.USE_ALIAS.resolveModelAttribute(context, model).asBoolean(); this.maxRetries = ModClusterDefinition.MAX_RETRIES.resolveModelAttribute(context, model).asInt(); this.failoverStrategy = Enum.valueOf(FailoverStrategy.class, ModClusterDefinition.FAILOVER_STRATEGY.resolveModelAttribute(context, model).asString()); return this; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceName name = this.getServiceName(); ServiceBuilder<?> builder = target.addService(name); Consumer<ModCluster> service = new CompositeDependency(this.worker, this.managementBinding, this.advertiseBinding, this.sslContext).register(builder).provides(name); Consumer<MCMPConfig> config = builder.provides(this.getConfigServiceName()); Consumer<Map.Entry<ModCluster, MCMPConfig>> consumer = new Consumer<>() { @Override public void accept(Map.Entry<ModCluster, MCMPConfig> entry) { service.accept(entry.getKey()); config.accept(entry.getValue()); } }; return builder.setInstance(new FunctionalService<>(consumer, Function.identity(), this, this)); } @Override public void accept(Map.Entry<ModCluster, MCMPConfig> entry) { entry.getKey().stop(); } @Override public Map.Entry<ModCluster, MCMPConfig> get() { SSLContext sslContext = this.sslContext != null ? this.sslContext.get() : null; XnioWorker worker = this.worker.get(); XnioSsl xnioSsl = (sslContext != null) ? new UndertowXnioSsl(worker.getXnio(), OptionMap.builder().set(Options.USE_DIRECT_BUFFERS, true).getMap(), sslContext) : null; //TODO: SSL support for the client ModCluster.Builder serviceBuilder = ModCluster.builder(worker, UndertowClient.getInstance(), xnioSsl) .setMaxRetries(this.maxRetries) .setClientOptions(this.clientOptions) .setHealthCheckInterval(this.healthCheckInterval) .setMaxRequestTime(this.maxRequestTime) .setCacheConnections(this.cachedConnections) .setQueueNewRequests(this.requestQueueSize > 0) .setRequestQueueSize(this.requestQueueSize) .setRemoveBrokenNodes(this.brokenNodeTimeout) .setTtl(this.connectionIdleTimeout) .setMaxConnections(this.maxConnections) .setUseAlias(this.useAlias) .setRouteParsingStrategy(this.routeParsingStrategy) .setRankedAffinityDelimiter(this.routeDelimiter) ; if (this.failoverStrategy == FailoverStrategy.DETERMINISTIC) { serviceBuilder.setDeterministicFailover(true); } ModCluster service = serviceBuilder.build(); MCMPConfig.Builder configBuilder = MCMPConfig.builder(); if (this.advertiseBinding != null) { SocketBinding advertiseBinding = this.advertiseBinding.get(); InetAddress multicastAddress = advertiseBinding.getMulticastAddress(); if (multicastAddress == null) { throw UndertowLogger.ROOT_LOGGER.advertiseSocketBindingRequiresMulticastAddress(); } if (this.advertiseFrequency > 0) { configBuilder.enableAdvertise() .setAdvertiseAddress(advertiseBinding.getSocketAddress().getAddress().getHostAddress()) .setAdvertiseGroup(multicastAddress.getHostAddress()) .setAdvertisePort(advertiseBinding.getMulticastPort()) .setAdvertiseFrequency(this.advertiseFrequency) .setPath(this.advertisePath) .setProtocol(this.advertiseProtocol) .setSecurityKey(this.securityKey); } } SocketBinding managementBinding = this.managementBinding.get(); configBuilder.setManagementHost(managementBinding.getSocketAddress().getHostString()); configBuilder.setManagementPort(managementBinding.getSocketAddress().getPort()); MCMPConfig config = configBuilder.build(); if (this.advertiseBinding != null && this.advertiseFrequency > 0) { try { service.advertise(config); } catch (IOException e) { throw new RuntimeException(e); } } service.start(); return Map.entry(service, config); } }
13,755
53.15748
211
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/FilterDefinitions.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.Collections; import java.util.List; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyRemoveStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.registry.AliasEntry; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. */ public class FilterDefinitions extends PersistentResourceDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.CONFIGURATION, Constants.FILTER); public FilterDefinitions() { super(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getValue()), new ModelOnlyAddStepHandler(), ModelOnlyRemoveStepHandler.INSTANCE ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptySet(); } @Override public List<? extends PersistentResourceDefinition> getChildren() { return List.of( new RequestLimitHandlerDefinition(), new ResponseHeaderFilterDefinition(), new GzipFilterDefinition(), new ErrorPageDefinition(), new CustomFilterDefinition(), new ModClusterDefinition(), new ExpressionFilterDefinition(), new RewriteFilterDefinition()); } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { super.registerChildren(resourceRegistration); PathElement targetPe = RequestLimitHandlerDefinition.PATH_ELEMENT; AliasEntry aliasEntry = new AliasEntry(resourceRegistration.getSubModel(PathAddress.pathAddress(targetPe))) { @Override public PathAddress convertToTargetAddress(PathAddress aliasAddress, AliasContext aliasContext) { PathElement pe = aliasAddress.getLastElement(); return aliasAddress.getParent().append(PathElement.pathElement(targetPe.getKey(), pe.getValue())); } }; resourceRegistration.registerAlias(PathElement.pathElement("connection-limit"), aliasEntry); } }
3,595
40.333333
118
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ExpressionFilterDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.List; import io.undertow.Handlers; import io.undertow.server.HandlerWrapper; import io.undertow.server.handlers.builder.PredicatedHandler; import io.undertow.server.handlers.builder.PredicatedHandlersParser; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author Tomaz Cerar (c) 2014 Red Hat Inc. */ public class ExpressionFilterDefinition extends SimpleFilterDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement("expression-filter"); public static final AttributeDefinition EXPRESSION = new SimpleAttributeDefinitionBuilder("expression", ModelType.STRING) .setRequired(true) .setAllowExpression(true) .setRestartAllServices() .build(); public static final AttributeDefinition MODULE = new SimpleAttributeDefinitionBuilder("module", ModelType.STRING) .setRequired(false) .setAllowExpression(true) .setRestartAllServices() .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(EXPRESSION, MODULE); ExpressionFilterDefinition() { super(PATH_ELEMENT, ExpressionFilterDefinition::createHandlerWrapper); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) throws OperationFailedException { String expression = EXPRESSION.resolveModelAttribute(context, model).asString(); String moduleName = MODULE.resolveModelAttribute(context, model).asStringOrNull(); ClassLoader loader = ExpressionFilterDefinition.class.getClassLoader(); if (moduleName != null) { try { ModuleLoader moduleLoader = Module.getBootModuleLoader(); Module filterModule = moduleLoader.loadModule(ModuleIdentifier.fromString(moduleName)); loader = filterModule.getClassLoader(); } catch (ModuleLoadException e) { throw UndertowLogger.ROOT_LOGGER.couldNotLoadHandlerFromModule(expression, moduleName, e); } } List<PredicatedHandler> handlers = PredicatedHandlersParser.parse(expression, loader); UndertowLogger.ROOT_LOGGER.debugf("Creating http handler %s from module %s", expression, moduleName); return next -> Handlers.predicates(handlers, next); } }
4,061
42.212766
125
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/AbstractFilterDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.Collections; import java.util.List; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.access.constraint.SensitivityClassification; import org.jboss.as.controller.access.management.AccessConstraintDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ public abstract class AbstractFilterDefinition extends PersistentResourceDefinition { protected AbstractFilterDefinition(PathElement path) { super(path, UndertowExtension.getResolver(Constants.FILTER, path.getKey())); } @Override public List<AccessConstraintDefinition> getAccessConstraints() { return List.of(new SensitiveTargetAccessConstraintDefinition(new SensitivityClassification(UndertowExtension.SUBSYSTEM_NAME, "undertow-filter", false, false, false))); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptyList(); } }
2,389
40.929825
175
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/AffinityResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.function.UnaryOperator; import org.jboss.as.clustering.controller.ChildResourceDefinition; import org.jboss.as.clustering.controller.ResourceDescriptor; import org.jboss.as.clustering.controller.RestartParentResourceRegistrar; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; /** * Base class for affinity resources. * * @author Radoslav Husar */ public abstract class AffinityResourceDefinition extends ChildResourceDefinition<ManagementResourceRegistration> { protected static PathElement pathElement(String value) { return PathElement.pathElement(Constants.AFFINITY, value); } static final PathElement WILDCARD_PATH = pathElement(PathElement.WILDCARD_VALUE); private final UnaryOperator<ResourceDescriptor> configurator; AffinityResourceDefinition(PathElement path, UnaryOperator<ResourceDescriptor> configurator) { super(path, UndertowExtension.getResolver(Constants.FILTER, ModClusterDefinition.PATH_ELEMENT.getKey(), path.getKey(), path.getValue())); this.configurator = configurator; } @Override public ManagementResourceRegistration register(ManagementResourceRegistration parent) { ManagementResourceRegistration registration = parent.registerSubModel(this); ResourceDescriptor descriptor = this.configurator.apply(new ResourceDescriptor(this.getResourceDescriptionResolver())); new RestartParentResourceRegistrar(ModClusterServiceConfigurator::new, descriptor).register(registration); return registration; } }
2,787
42.5625
145
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/FilterAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceTarget; import org.wildfly.extension.undertow.UndertowService; import java.util.Collection; import java.util.function.Consumer; import io.undertow.server.HandlerWrapper; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ class FilterAdd extends AbstractAddStepHandler { private HandlerWrapperFactory factory; FilterAdd(HandlerWrapperFactory factory, Collection<AttributeDefinition> attributes) { super(attributes); this.factory = factory; } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final String name = context.getCurrentAddressValue(); final ServiceTarget target = context.getServiceTarget(); final ServiceBuilder<?> sb = target.addService(UndertowService.FILTER.append(name)); final Consumer<HandlerWrapper> serviceConsumer = sb.provides(UndertowService.FILTER.append(name)); HandlerWrapper wrapper = this.factory.createHandlerWrapper(context, model); sb.setInstance(Service.newInstance(serviceConsumer, wrapper)); sb.setInitialMode(ServiceController.Mode.ON_DEMAND); sb.install(); } }
2,739
40.515152
131
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ModClusterNodeDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.EnumSet; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import io.undertow.server.handlers.proxy.mod_cluster.ModCluster; import io.undertow.server.handlers.proxy.mod_cluster.ModClusterStatus; import org.jboss.as.clustering.controller.FunctionExecutor; import org.jboss.as.clustering.controller.FunctionExecutorRegistry; import org.jboss.as.clustering.controller.Metric; import org.jboss.as.clustering.controller.MetricExecutor; import org.jboss.as.clustering.controller.MetricFunction; import org.jboss.as.clustering.controller.MetricHandler; import org.jboss.as.clustering.controller.Operation; import org.jboss.as.clustering.controller.OperationExecutor; import org.jboss.as.clustering.controller.OperationFunction; import org.jboss.as.clustering.controller.OperationHandler; import org.jboss.as.controller.AbstractAttributeDefinitionBuilder; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PrimitiveListAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; /** * Runtime representation of a mod_cluster node * * @author Stuart Douglas */ public class ModClusterNodeDefinition extends SimpleResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.NODE); static final ResourceDescriptionResolver RESOLVER = UndertowExtension.getResolver(Constants.FILTER, ModClusterDefinition.PATH_ELEMENT.getKey(), ModClusterBalancerDefinition.PATH_ELEMENT.getKey(), PATH_ELEMENT.getKey()); static final BiFunction<String, ModelType, PrimitiveListAttributeDefinition.Builder> PRIMITIVE_LIST_BUILDER_FACTORY = PrimitiveListAttributeDefinition.Builder::new; enum NodeMetric implements Metric<ModClusterStatus.Node> { LOAD(Constants.LOAD, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getLoad()); } }, STATUS(Constants.STATUS, ModelType.STRING) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getStatus().name()); } }, LOAD_BALANCING_GROUP(Constants.LOAD_BALANCING_GROUP, ModelType.STRING) { @Override public ModelNode execute(ModClusterStatus.Node node) { return Optional.ofNullable(node.getDomain()).map(ModelNode::new).orElse(null); } }, CACHE_CONNECTIONS(Constants.CACHE_CONNECTIONS, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getCacheConnections()); } }, MAX_CONNECTIONS(Constants.MAX_CONNECTIONS, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getMaxConnections()); } }, OPEN_CONNECTIONS(Constants.OPEN_CONNECTIONS, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getOpenConnections()); } }, PING(Constants.PING, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getPing()); } }, READ(Constants.READ, ModelType.LONG) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getRead()); } @Override <D extends AttributeDefinition, B extends AbstractAttributeDefinitionBuilder<B, D>> B configure(B builder) { return builder.setMeasurementUnit(MeasurementUnit.BYTES); } }, REQUEST_QUEUE_SIZE(Constants.REQUEST_QUEUE_SIZE, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getRequestQueueSize()); } }, TIMEOUT(Constants.TIMEOUT, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getTimeout()); } @Override <D extends AttributeDefinition, B extends AbstractAttributeDefinitionBuilder<B, D>> B configure(B builder) { return builder.setMeasurementUnit(MeasurementUnit.SECONDS); } }, WRITTEN(Constants.WRITTEN, ModelType.LONG) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getTransferred()); } @Override <D extends AttributeDefinition, B extends AbstractAttributeDefinitionBuilder<B, D>> B configure(B builder) { return builder.setMeasurementUnit(MeasurementUnit.BYTES); } }, TTL(Constants.TTL, ModelType.LONG) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getTtl()); } }, FLUSH_PACKETS(Constants.FLUSH_PACKETS, ModelType.BOOLEAN) { @Override public ModelNode execute(ModClusterStatus.Node node) { return node.isFlushPackets() ? ModelNode.TRUE : ModelNode.FALSE; } }, QUEUE_NEW_REQUESTS(Constants.QUEUE_NEW_REQUESTS, ModelType.BOOLEAN) { @Override public ModelNode execute(ModClusterStatus.Node node) { return node.isQueueNewRequests() ? ModelNode.TRUE : ModelNode.FALSE; } }, URI(Constants.URI, ModelType.STRING) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getUri().toString()); } }, ALIASES(Constants.ALIASES, ModelType.STRING, PRIMITIVE_LIST_BUILDER_FACTORY) { @Override public ModelNode execute(ModClusterStatus.Node node) { ModelNode result = new ModelNode(); for (String alias : node.getAliases()) { result.add(alias); } return result; } }, ELECTED(Constants.ELECTED, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Node node) { return new ModelNode(node.getElected()); } }, ; private final AttributeDefinition definition; NodeMetric(String name, ModelType type) { this(name, type, SimpleAttributeDefinitionBuilder::new); } <D extends AttributeDefinition, B extends AbstractAttributeDefinitionBuilder<B, D>> NodeMetric(String name, ModelType type, BiFunction<String, ModelType, B> builderFactory) { this.definition = this.configure(builderFactory.apply(name, type)) .setRequired(false) .setStorageRuntime() .build(); } <D extends AttributeDefinition, B extends AbstractAttributeDefinitionBuilder<B, D>> B configure(B builder) { return builder; } @Override public AttributeDefinition getDefinition() { return this.definition; } } enum NodeOperation implements Operation<ModClusterStatus.Node> { ENABLE(Constants.ENABLE, ModClusterStatus.Context::enable), DISABLE(Constants.DISABLE, ModClusterStatus.Context::disable), STOP(Constants.STOP, ModClusterStatus.Context::stop), ; private OperationDefinition definition; private final Consumer<ModClusterStatus.Context> operation; NodeOperation(String name, Consumer<ModClusterStatus.Context> operation) { this.definition = SimpleOperationDefinitionBuilder.of(name, RESOLVER).setRuntimeOnly().build(); this.operation = operation; } @Override public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterStatus.Node node) { node.getContexts().forEach(this.operation); return null; } @Override public OperationDefinition getDefinition() { return this.definition; } } private final FunctionExecutorRegistry<ModCluster> registry; ModClusterNodeDefinition(FunctionExecutorRegistry<ModCluster> registry) { super(new Parameters(PATH_ELEMENT, RESOLVER).setRuntime()); this.registry = registry; } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerSubModel(new ModClusterContextDefinition(this.registry)); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { new OperationHandler<>(new NodeOperationExecutor(new FunctionExecutorFactory(this.registry)), NodeOperation.class).register(resourceRegistration); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { OperationStepHandler handler = new MetricHandler<>(new NodeMetricExecutor(new FunctionExecutorFactory(this.registry)), NodeMetric.class); // TODO Consider registering some subset of these as proper metrics for (NodeMetric metric : EnumSet.allOf(NodeMetric.class)) { resourceRegistration.registerReadOnlyAttribute(metric.getDefinition(), handler); } } static class FunctionExecutorFactory implements Function<OperationContext, FunctionExecutor<ModCluster>> { private final FunctionExecutorRegistry<ModCluster> registry; FunctionExecutorFactory(FunctionExecutorRegistry<ModCluster> registry) { this.registry = registry; } @Override public FunctionExecutor<ModCluster> apply(OperationContext context) { PathAddress serviceAddress = context.getCurrentAddress().getParent().getParent(); return this.registry.get(new ModClusterServiceNameProvider(serviceAddress).getServiceName()); } } static final Function<OperationContext, Function<ModCluster, ModClusterStatus.Node>> NODE_FUNCTION_FACTORY = new Function<>() { @Override public Function<ModCluster, ModClusterStatus.Node> apply(OperationContext context) { PathAddress nodeAddress = context.getCurrentAddress(); String nodeName = nodeAddress.getLastElement().getValue(); PathAddress balancerAddress = nodeAddress.getParent(); String balancerName = balancerAddress.getLastElement().getValue(); return new NodeFunction(balancerName, nodeName); } }; static class NodeMetricExecutor implements MetricExecutor<ModClusterStatus.Node> { private final Function<OperationContext, FunctionExecutor<ModCluster>> factory; NodeMetricExecutor(Function<OperationContext, FunctionExecutor<ModCluster>> factory) { this.factory = factory; } @Override public ModelNode execute(OperationContext context, Metric<ModClusterStatus.Node> metric) throws OperationFailedException { FunctionExecutor<ModCluster> executor = this.factory.apply(context); Function<ModCluster, ModClusterStatus.Node> mapper = NODE_FUNCTION_FACTORY.apply(context); return (executor != null) ? executor.execute(new MetricFunction<>(mapper, metric)) : null; } } static class NodeOperationExecutor implements OperationExecutor<ModClusterStatus.Node> { private final Function<OperationContext, FunctionExecutor<ModCluster>> factory; NodeOperationExecutor(Function<OperationContext, FunctionExecutor<ModCluster>> factory) { this.factory = factory; } @Override public ModelNode execute(OperationContext context, ModelNode op, Operation<ModClusterStatus.Node> operation) throws OperationFailedException { FunctionExecutor<ModCluster> executor = this.factory.apply(context); Function<ModCluster, ModClusterStatus.Node> mapper = NODE_FUNCTION_FACTORY.apply(context); return (executor != null) ? executor.execute(new OperationFunction<>(context, op, mapper, operation)) : null; } } static class NodeFunction implements Function<ModCluster, ModClusterStatus.Node> { private final String balancerName; private final String nodeName; NodeFunction(String balancerName, String nodeName) { this.balancerName = balancerName; this.nodeName = nodeName; } @Override public ModClusterStatus.Node apply(ModCluster service) { ModClusterStatus.LoadBalancer balancer = service.getController().getStatus().getLoadBalancer(this.balancerName); return (balancer != null) ? balancer.getNode(this.nodeName) : null; } } }
15,207
43.081159
223
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ModClusterDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import static org.jboss.as.controller.PathElement.pathElement; import static org.wildfly.extension.undertow.Capabilities.CAPABILITY_MOD_CLUSTER_FILTER; import static org.wildfly.extension.undertow.Capabilities.REF_SSL_CONTEXT; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import io.undertow.Handlers; import io.undertow.UndertowOptions; import io.undertow.predicate.Predicate; import io.undertow.predicate.PredicateParser; import io.undertow.protocols.ajp.AjpClientRequestClientStreamSinkChannel; import io.undertow.protocols.http2.Http2Channel; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.proxy.mod_cluster.MCMPConfig; import io.undertow.server.handlers.proxy.mod_cluster.ModCluster; import org.jboss.as.clustering.controller.ResourceDescriptor; import org.jboss.as.clustering.controller.ResourceServiceHandler; import org.jboss.as.clustering.controller.ServiceValueCaptor; import org.jboss.as.clustering.controller.ServiceValueCaptorServiceConfigurator; import org.jboss.as.clustering.controller.ServiceValueExecutorRegistry; import org.jboss.as.clustering.controller.ServiceValueRegistry; import org.jboss.as.clustering.controller.SimpleResourceRegistrar; import org.jboss.as.clustering.controller.UnaryCapabilityNameResolver; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.operations.validation.EnumValidator; import org.jboss.as.controller.operations.validation.IntRangeValidator; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.io.OptionAttributeDefinition; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.PredicateValidator; import org.wildfly.extension.undertow.UndertowService; /** * mod_cluster front-end handler. This acts like a filter, but does not re-use a lot of the filter code as it * needs to inject various services. * * @author Stuart Douglas * @author Radoslav Husar */ public class ModClusterDefinition extends AbstractFilterDefinition { public static final PathElement PATH_ELEMENT = pathElement(Constants.MOD_CLUSTER); enum Capability implements org.jboss.as.clustering.controller.Capability { MOD_CLUSTER_FILTER_CAPABILITY(CAPABILITY_MOD_CLUSTER_FILTER, HandlerWrapper.class), ; private final RuntimeCapability<Void> definition; Capability(String name, Class<?> serviceValueType) { this.definition = RuntimeCapability.Builder.of(name, true, serviceValueType).setDynamicNameMapper(UnaryCapabilityNameResolver.DEFAULT).build(); } @Override public RuntimeCapability<Void> getDefinition() { return this.definition; } } public static final AttributeDefinition MANAGEMENT_SOCKET_BINDING = new SimpleAttributeDefinitionBuilder(Constants.MANAGEMENT_SOCKET_BINDING, ModelType.STRING) .setAllowExpression(true) .setRequired(true) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF) .setCapabilityReference(Capabilities.REF_SOCKET_BINDING) .setRestartAllServices() .build(); public static final AttributeDefinition ADVERTISE_SOCKET_BINDING = new SimpleAttributeDefinitionBuilder(Constants.ADVERTISE_SOCKET_BINDING, ModelType.STRING) .setAllowExpression(true) .setRequired(false) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF) .setCapabilityReference(Capabilities.REF_SOCKET_BINDING) .setRestartAllServices() .build(); public static final AttributeDefinition SECURITY_KEY = new SimpleAttributeDefinitionBuilder(Constants.SECURITY_KEY, ModelType.STRING) .setAllowExpression(true) .setRequired(false) .setRestartAllServices() .build(); public static final AttributeDefinition ADVERTISE_PROTOCOL = new SimpleAttributeDefinitionBuilder(Constants.ADVERTISE_PROTOCOL, ModelType.STRING) .setAllowExpression(true) .setRequired(false) .setDefaultValue(new ModelNode("http")) .setRestartAllServices() .build(); public static final AttributeDefinition ADVERTISE_PATH = new SimpleAttributeDefinitionBuilder(Constants.ADVERTISE_PATH, ModelType.STRING) .setAllowExpression(true) .setRequired(false) .setDefaultValue(new ModelNode("/")) .setRestartAllServices() .build(); public static final AttributeDefinition ADVERTISE_FREQUENCY = new SimpleAttributeDefinitionBuilder(Constants.ADVERTISE_FREQUENCY, ModelType.INT) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.MILLISECONDS) .setRequired(false) .setDefaultValue(new ModelNode(10000)) .setRestartAllServices() .build(); public static final AttributeDefinition FAILOVER_STRATEGY = new SimpleAttributeDefinitionBuilder(Constants.FAILOVER_STRATEGY, ModelType.STRING) .setRequired(false) .setValidator(EnumValidator.create(FailoverStrategy.class)) .setRestartAllServices() .setDefaultValue(new ModelNode(FailoverStrategy.LOAD_BALANCED.name())) .build(); public static final AttributeDefinition HEALTH_CHECK_INTERVAL = new SimpleAttributeDefinitionBuilder(Constants.HEALTH_CHECK_INTERVAL, ModelType.INT) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.MILLISECONDS) .setRequired(false) .setDefaultValue(new ModelNode(10000)) .setRestartAllServices() .build(); public static final AttributeDefinition BROKEN_NODE_TIMEOUT = new SimpleAttributeDefinitionBuilder(Constants.BROKEN_NODE_TIMEOUT, ModelType.INT) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.MILLISECONDS) .setRequired(false) .setDefaultValue(new ModelNode(60000)) //TODO: what is a good default? .setRestartAllServices() .build(); public static final AttributeDefinition WORKER = new SimpleAttributeDefinitionBuilder(Constants.WORKER, ModelType.STRING) .setAllowExpression(true) .setRequired(false) .setDefaultValue(new ModelNode("default")) .setCapabilityReference(Capabilities.REF_IO_WORKER) .setRestartAllServices() .build(); public static final AttributeDefinition MAX_REQUEST_TIME = new SimpleAttributeDefinitionBuilder(Constants.MAX_REQUEST_TIME, ModelType.INT) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.MILLISECONDS) .setRequired(false) .setDefaultValue(new ModelNode(-1)) .setRestartAllServices() .build(); public static final AttributeDefinition MANAGEMENT_ACCESS_PREDICATE = new SimpleAttributeDefinitionBuilder(Constants.MANAGEMENT_ACCESS_PREDICATE, ModelType.STRING) .setAllowExpression(true) .setRequired(false) .setRestartAllServices() .setValidator(PredicateValidator.INSTANCE) .build(); public static final AttributeDefinition CONNECTIONS_PER_THREAD = new SimpleAttributeDefinitionBuilder(Constants.CONNECTIONS_PER_THREAD, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(40)) .setRestartAllServices() .build(); public static final AttributeDefinition CACHED_CONNECTIONS_PER_THREAD = new SimpleAttributeDefinitionBuilder(Constants.CACHED_CONNECTIONS_PER_THREAD, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(40)) .setRestartAllServices() .build(); public static final AttributeDefinition CONNECTION_IDLE_TIMEOUT = new SimpleAttributeDefinitionBuilder(Constants.CONNECTION_IDLE_TIMEOUT, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.SECONDS) .setDefaultValue(new ModelNode(60)) .setRestartAllServices() .build(); public static final AttributeDefinition REQUEST_QUEUE_SIZE = new SimpleAttributeDefinitionBuilder(Constants.REQUEST_QUEUE_SIZE, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(1000)) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SSL_CONTEXT = new SimpleAttributeDefinitionBuilder(Constants.SSL_CONTEXT, ModelType.STRING, true) .setAlternatives(Constants.SECURITY_REALM) .setCapabilityReference(REF_SSL_CONTEXT) .setRestartAllServices() .setValidator(new StringLengthValidator(1)) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SSL_REF) .build(); public static final SimpleAttributeDefinition SECURITY_REALM = new SimpleAttributeDefinitionBuilder(Constants.SECURITY_REALM, ModelType.STRING) .setAlternatives(Constants.SSL_CONTEXT) .setRequired(false) .setRestartAllServices() .setValidator(new StringLengthValidator(1)) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SECURITY_REALM_REF) .setDeprecated(ModelVersion.create(4, 0, 0)) .build(); public static final SimpleAttributeDefinition USE_ALIAS = new SimpleAttributeDefinitionBuilder(Constants.USE_ALIAS, ModelType.BOOLEAN) .setRequired(false) .setDefaultValue(ModelNode.FALSE) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition ENABLE_HTTP2 = new SimpleAttributeDefinitionBuilder(Constants.ENABLE_HTTP2, ModelType.BOOLEAN) .setRequired(false) .setDefaultValue(ModelNode.FALSE) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition MAX_AJP_PACKET_SIZE = new SimpleAttributeDefinitionBuilder(Constants.MAX_AJP_PACKET_SIZE, ModelType.INT) .setRequired(false) .setRestartAllServices() .setMeasurementUnit(MeasurementUnit.BYTES) .setAllowExpression(true) .setDefaultValue(new ModelNode(AjpClientRequestClientStreamSinkChannel.DEFAULT_MAX_DATA_SIZE)) .setValidator(new IntRangeValidator(1)) .build(); public static final OptionAttributeDefinition HTTP2_ENABLE_PUSH = OptionAttributeDefinition.builder("http2-enable-push", UndertowOptions.HTTP2_SETTINGS_ENABLE_PUSH) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setDefaultValue(ModelNode.TRUE) .build(); public static final OptionAttributeDefinition HTTP2_HEADER_TABLE_SIZE = OptionAttributeDefinition.builder("http2-header-table-size", UndertowOptions.HTTP2_SETTINGS_HEADER_TABLE_SIZE) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.BYTES) .setDefaultValue(new ModelNode(UndertowOptions.HTTP2_SETTINGS_HEADER_TABLE_SIZE_DEFAULT)) .setValidator(new IntRangeValidator(1)) .build(); public static final OptionAttributeDefinition HTTP2_INITIAL_WINDOW_SIZE = OptionAttributeDefinition.builder("http2-initial-window-size", UndertowOptions.HTTP2_SETTINGS_INITIAL_WINDOW_SIZE) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.BYTES) .setDefaultValue(new ModelNode(Http2Channel.DEFAULT_INITIAL_WINDOW_SIZE)) .setValidator(new IntRangeValidator(1)) .build(); public static final OptionAttributeDefinition HTTP2_MAX_CONCURRENT_STREAMS = OptionAttributeDefinition.builder("http2-max-concurrent-streams", UndertowOptions.HTTP2_SETTINGS_MAX_CONCURRENT_STREAMS) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setValidator(new IntRangeValidator(1)) .build(); public static final OptionAttributeDefinition HTTP2_MAX_FRAME_SIZE = OptionAttributeDefinition.builder("http2-max-frame-size", UndertowOptions.HTTP2_SETTINGS_MAX_FRAME_SIZE) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.BYTES) .setDefaultValue(new ModelNode(Http2Channel.DEFAULT_MAX_FRAME_SIZE)) .setValidator(new IntRangeValidator(1)) .build(); public static final OptionAttributeDefinition HTTP2_MAX_HEADER_LIST_SIZE = OptionAttributeDefinition.builder("http2-max-header-list-size", UndertowOptions.HTTP2_SETTINGS_MAX_HEADER_LIST_SIZE) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.BYTES) .setValidator(new IntRangeValidator(1)) .build(); public static final AttributeDefinition MAX_RETRIES = new SimpleAttributeDefinitionBuilder(Constants.MAX_RETRIES, ModelType.INT) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setDefaultValue(new ModelNode(1L)) .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(MANAGEMENT_SOCKET_BINDING, ADVERTISE_SOCKET_BINDING, SECURITY_KEY, ADVERTISE_PROTOCOL, ADVERTISE_PATH, ADVERTISE_FREQUENCY, FAILOVER_STRATEGY, HEALTH_CHECK_INTERVAL, BROKEN_NODE_TIMEOUT, WORKER, MAX_REQUEST_TIME, MANAGEMENT_ACCESS_PREDICATE, CONNECTIONS_PER_THREAD, CACHED_CONNECTIONS_PER_THREAD, CONNECTION_IDLE_TIMEOUT, REQUEST_QUEUE_SIZE, SECURITY_REALM, SSL_CONTEXT, USE_ALIAS, ENABLE_HTTP2, MAX_AJP_PACKET_SIZE, HTTP2_MAX_HEADER_LIST_SIZE, HTTP2_MAX_FRAME_SIZE, HTTP2_MAX_CONCURRENT_STREAMS, HTTP2_INITIAL_WINDOW_SIZE, HTTP2_HEADER_TABLE_SIZE, HTTP2_ENABLE_PUSH, MAX_RETRIES); private final ServiceValueExecutorRegistry<ModCluster> registry = new ServiceValueExecutorRegistry<>(); ModClusterDefinition() { super(PATH_ELEMENT); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addAttributes(ATTRIBUTES) .addCapabilities(Capability.class) .addRequiredSingletonChildren(SingleAffinityResourceDefinition.PATH) .setResourceTransformation(ModClusterResource::new) ; ModClusterResourceServiceHandler handler = new ModClusterResourceServiceHandler(this.registry); new SimpleResourceRegistrar(descriptor, handler).register(resourceRegistration); } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { new NoAffinityResourceDefinition().register(resourceRegistration); new SingleAffinityResourceDefinition().register(resourceRegistration); new RankedAffinityResourceDefinition().register(resourceRegistration); resourceRegistration.registerSubModel(new ModClusterBalancerDefinition(this.registry)); } static class ModClusterResourceServiceHandler implements ResourceServiceHandler { private final ServiceValueRegistry<ModCluster> registry; ModClusterResourceServiceHandler(ServiceValueRegistry<ModCluster> registry) { this.registry = registry; } @Override public void installServices(OperationContext context, ModelNode model) throws OperationFailedException { String managementAccessPredicateString = ModClusterDefinition.MANAGEMENT_ACCESS_PREDICATE.resolveModelAttribute(context, model).asStringOrNull(); Predicate managementAccessPredicate = (managementAccessPredicateString != null) ? PredicateParser.parse(managementAccessPredicateString, this.getClass().getClassLoader()) : null; ModClusterServiceConfigurator configurator = new ModClusterServiceConfigurator(context.getCurrentAddress()); configurator.configure(context, model).build(context.getServiceTarget()).setInitialMode(ServiceController.Mode.ON_DEMAND).install(); RuntimeCapability<Void> capability = ModClusterDefinition.Capability.MOD_CLUSTER_FILTER_CAPABILITY.getDefinition(); CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(capability); Consumer<HandlerWrapper> filter = builder.provides(capability, UndertowService.FILTER.append(context.getCurrentAddressValue())); Supplier<ModCluster> serviceRequirement = builder.requires(configurator.getServiceName()); Supplier<MCMPConfig> configRequirement = builder.requires(configurator.getConfigServiceName()); HandlerWrapper wrapper = new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler next) { ModCluster modCluster = serviceRequirement.get(); MCMPConfig config = configRequirement.get(); //this is a bit of a hack at the moment. Basically we only want to create a single mod_cluster instance //not matter how many filter refs use it, also mod_cluster at this point has no way //to specify the next handler. To get around this we invoke the mod_proxy handler //and then if it has not dispatched or handled the request then we know that we can //just pass it on to the next handler final HttpHandler proxyHandler = modCluster.createProxyHandler(next); final HttpHandler realNext = new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { proxyHandler.handleRequest(exchange); if (!exchange.isDispatched() && !exchange.isComplete()) { exchange.setStatusCode(200); next.handleRequest(exchange); } } }; return (managementAccessPredicate != null) ? Handlers.predicate(managementAccessPredicate, config.create(modCluster, realNext), next) : config.create(modCluster, realNext); } }; builder.setInstance(Service.newInstance(filter, wrapper)).setInitialMode(ServiceController.Mode.ON_DEMAND).install(); new ServiceValueCaptorServiceConfigurator<>(new ModClusterResourceServiceValueCaptor(context, this.registry.add(configurator.getServiceName()))).build(context.getServiceTarget()).install(); } @Override public void removeServices(OperationContext context, ModelNode model) { ServiceName serviceName = new ModClusterServiceNameProvider(context.getCurrentAddress()).getServiceName(); context.removeService(new ServiceValueCaptorServiceConfigurator<>(this.registry.remove(serviceName)).getServiceName()); context.removeService(serviceName); context.removeService(ModClusterDefinition.Capability.MOD_CLUSTER_FILTER_CAPABILITY.getDefinition().getCapabilityServiceName(context.getCurrentAddress())); } } static class ModClusterResourceServiceValueCaptor implements ServiceValueCaptor<ModCluster> { private final ServiceValueCaptor<ModCluster> captor; private final Consumer<ModCluster> consumer; ModClusterResourceServiceValueCaptor(OperationContext context, ServiceValueCaptor<ModCluster> captor) { this.captor = captor; this.consumer = (ModClusterResource) context.readResource(PathAddress.EMPTY_ADDRESS); } @Override public ServiceName getServiceName() { return this.captor.getServiceName(); } @Override public void accept(ModCluster service) { this.captor.accept(service); this.consumer.accept(service); } } }
22,829
51.004556
201
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/RankedAffinityResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import org.jboss.as.clustering.controller.SimpleResourceDescriptorConfigurator; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.Constants; /** * Affinity resource configuring ranked affinity handling which requires a delimiter to be specified. * * @author Radoslav Husar */ public class RankedAffinityResourceDefinition extends AffinityResourceDefinition { public static final PathElement PATH = pathElement(Constants.RANKED); public enum Attribute implements org.jboss.as.clustering.controller.Attribute { DELIMITER(Constants.DELIMITER, ModelType.STRING, new ModelNode(".")), ; private final AttributeDefinition definition; Attribute(String name, ModelType type, ModelNode defaultValue) { this.definition = new SimpleAttributeDefinitionBuilder(name, type) .setRequired(defaultValue == null) .setAllowExpression(true) .setDefaultValue(defaultValue) .setRestartAllServices() .build(); } @Override public AttributeDefinition getDefinition() { return this.definition; } } public RankedAffinityResourceDefinition() { super(PATH, new SimpleResourceDescriptorConfigurator<>(Attribute.class)); } }
2,605
38.484848
101
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/SimpleFilterDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ServiceRemoveStepHandler; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.wildfly.extension.undertow.UndertowService; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. */ abstract class SimpleFilterDefinition extends AbstractFilterDefinition { private final HandlerWrapperFactory factory; protected SimpleFilterDefinition(PathElement path, HandlerWrapperFactory factory) { super(path); this.factory = factory; } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { FilterAdd add = new FilterAdd(this.factory, this.getAttributes()); registerAddOperation(resourceRegistration, add, OperationEntry.Flag.RESTART_RESOURCE_SERVICES); registerRemoveOperation(resourceRegistration, new ServiceRemoveStepHandler(UndertowService.FILTER, add), OperationEntry.Flag.RESTART_RESOURCE_SERVICES); } }
2,135
41.72
160
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/NoAffinityResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.function.UnaryOperator; import org.jboss.as.controller.PathElement; import org.wildfly.extension.undertow.Constants; /** * Affinity resource configuring no affinity handling. * * @author Radoslav Husar */ public class NoAffinityResourceDefinition extends AffinityResourceDefinition { public static final PathElement PATH = pathElement(Constants.NONE); public NoAffinityResourceDefinition() { super(PATH, UnaryOperator.identity()); } }
1,553
35.139535
78
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/GzipFilterDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import io.undertow.server.HandlerWrapper; import io.undertow.server.handlers.encoding.ContentEncodingRepository; import io.undertow.server.handlers.encoding.EncodingHandler; import io.undertow.server.handlers.encoding.GzipEncodingProvider; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.PathElement; import org.jboss.dmr.ModelNode; /** * @author Tomaz Cerar (c) 2014 Red Hat Inc. */ public class GzipFilterDefinition extends SimpleFilterDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement("gzip"); GzipFilterDefinition() { super(PATH_ELEMENT, GzipFilterDefinition::createHandlerWrapper); } static HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) { ContentEncodingRepository repository = new ContentEncodingRepository().addEncodingHandler("gzip", new GzipEncodingProvider(), 50); return next -> new EncodingHandler(next, repository); } }
2,054
41.8125
138
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/FailoverStrategy.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; /** * @author Radoslav Husar */ public enum FailoverStrategy { /** * Failover target chosen via load balancing mechanism. */ LOAD_BALANCED, /** * Failover target chosen deterministically from the associated session identifier. */ DETERMINISTIC, ; }
1,363
34.894737
87
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/FilterRefDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import io.undertow.predicate.Predicate; import io.undertow.predicate.PredicateParser; import io.undertow.server.HandlerWrapper; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ServiceRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.operations.validation.IntRangeValidator; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.FilterLocation; import org.wildfly.extension.undertow.PredicateValidator; import org.wildfly.extension.undertow.UndertowExtension; import org.wildfly.extension.undertow.UndertowFilter; import org.wildfly.extension.undertow.UndertowService; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class FilterRefDefinition extends PersistentResourceDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.FILTER_REF); public static final AttributeDefinition PREDICATE = new SimpleAttributeDefinitionBuilder("predicate", ModelType.STRING) .setRequired(false) .setAllowExpression(true) .setRestartAllServices() .setValidator(PredicateValidator.INSTANCE) .build(); public static final AttributeDefinition PRIORITY = new SimpleAttributeDefinitionBuilder("priority", ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(1)) .setValidator(new IntRangeValidator(1, true, true)) .setRestartAllServices() .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(PREDICATE, PRIORITY); public FilterRefDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey())) .setAddHandler(new FilterRefAdd()) .setRemoveHandler(new ServiceRemoveStepHandler(new FilterRefAdd()) { @Override protected ServiceName serviceName(String name, PathAddress address) { return UndertowService.getFilterRefServiceName(address, name); } }) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static class FilterRefAdd extends AbstractAddStepHandler { FilterRefAdd() { super(FilterRefDefinition.PREDICATE, PRIORITY); } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final PathAddress address = context.getCurrentAddress(); final String name = context.getCurrentAddressValue(); final String locationType = address.getElement(address.size() - 2).getKey(); final ServiceName locationSN; if (locationType.equals(Constants.HOST)) { final PathAddress hostAddress = address.getParent(); final PathAddress serverAddress = hostAddress.getParent(); final String serverName = serverAddress.getLastElement().getValue(); final String hostName = hostAddress.getLastElement().getValue(); locationSN = context.getCapabilityServiceName(Capabilities.CAPABILITY_HOST, FilterLocation.class, serverName, hostName); } else { final PathAddress locationAddress = address.getParent(); final PathAddress hostAddress = locationAddress.getParent(); final PathAddress serverAddress = hostAddress.getParent(); final String locationName = locationAddress.getLastElement().getValue(); final String serverName = serverAddress.getLastElement().getValue(); final String hostName = hostAddress.getLastElement().getValue(); locationSN = context.getCapabilityServiceName(Capabilities.CAPABILITY_LOCATION, FilterLocation.class, serverName, hostName, locationName); } Predicate predicate = null; if (model.hasDefined(PREDICATE.getName())) { String predicateString = PREDICATE.resolveModelAttribute(context, model).asString(); predicate = PredicateParser.parse(predicateString, getClass().getClassLoader()); } int priority = PRIORITY.resolveModelAttribute(context, operation).asInt(); final ServiceTarget target = context.getServiceTarget(); final ServiceName sn = UndertowService.getFilterRefServiceName(address, name); final ServiceBuilder<?> sb = target.addService(sn); final Consumer<UndertowFilter> frConsumer = sb.provides(sn); final Supplier<HandlerWrapper> fSupplier = sb.requires(UndertowService.FILTER.append(name)); final Supplier<FilterLocation> lSupplier = sb.requires(locationSN); sb.setInstance(new FilterService(frConsumer, fSupplier, lSupplier, predicate, priority)); sb.install(); } } }
7,018
48.083916
154
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ResponseHeaderFilterDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.List; import io.undertow.server.HandlerWrapper; import io.undertow.server.handlers.SetHeaderHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ public class ResponseHeaderFilterDefinition extends SimpleFilterDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement("response-header"); public static final AttributeDefinition NAME = new SimpleAttributeDefinitionBuilder("header-name", ModelType.STRING) .setRequired(true) .setAllowExpression(true) .setRestartAllServices() .build(); public static final AttributeDefinition VALUE = new SimpleAttributeDefinitionBuilder("header-value", ModelType.STRING) .setRequired(true) .setAllowExpression(true) .setRestartAllServices() .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(NAME, VALUE); ResponseHeaderFilterDefinition() { super(PATH_ELEMENT, ResponseHeaderFilterDefinition::createHandlerWrapper); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) throws OperationFailedException { String name = NAME.resolveModelAttribute(context, model).asString(); String value = VALUE.resolveModelAttribute(context, model).asString(); return next -> new SetHeaderHandler(next, name, value); } }
3,007
40.205479
123
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ModClusterBalancerDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.EnumSet; import java.util.Optional; import java.util.function.Function; import io.undertow.server.handlers.proxy.mod_cluster.ModCluster; import io.undertow.server.handlers.proxy.mod_cluster.ModClusterStatus; import io.undertow.server.handlers.proxy.mod_cluster.ModClusterStatus.LoadBalancer; import org.jboss.as.clustering.controller.FunctionExecutor; import org.jboss.as.clustering.controller.FunctionExecutorRegistry; import org.jboss.as.clustering.controller.Metric; import org.jboss.as.clustering.controller.MetricExecutor; import org.jboss.as.clustering.controller.MetricFunction; import org.jboss.as.clustering.controller.MetricHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; /** * Runtime representation of a mod_cluster balancer * * @author Stuart Douglas */ class ModClusterBalancerDefinition extends SimpleResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.BALANCER); enum LoadBalancerMetric implements Metric<ModClusterStatus.LoadBalancer> { STICKY_SESSION_COOKIE(Constants.STICKY_SESSION_COOKIE, ModelType.STRING) { @Override public ModelNode execute(LoadBalancer balancer) { return Optional.ofNullable(balancer.getStickySessionCookie()).map(ModelNode::new).orElse(null); } }, STICKY_SESSION_PATH(Constants.STICKY_SESSION_PATH, ModelType.STRING) { @Override public ModelNode execute(LoadBalancer balancer) { return Optional.ofNullable(balancer.getStickySessionPath()).map(ModelNode::new).orElse(null); } }, MAX_ATTEMPTS(Constants.MAX_ATTEMPTS, ModelType.INT) { @Override public ModelNode execute(LoadBalancer balancer) { return new ModelNode(balancer.getMaxRetries()); } }, WAIT_WORKER(Constants.WAIT_WORKER, ModelType.INT) { @Override public ModelNode execute(LoadBalancer balancer) { return new ModelNode(balancer.getWaitWorker()); } }, STICKY_SESSION(Constants.STICKY_SESSION, ModelType.BOOLEAN) { @Override public ModelNode execute(LoadBalancer balancer) { return balancer.isStickySession() ? ModelNode.TRUE : ModelNode.FALSE; } }, STICKY_SESSION_FORCE(Constants.STICKY_SESSION_FORCE, ModelType.BOOLEAN) { @Override public ModelNode execute(LoadBalancer balancer) { return balancer.isStickySessionForce() ? ModelNode.TRUE : ModelNode.FALSE; } }, STICKY_SESSION_REMOVE(Constants.STICKY_SESSION_REMOVE, ModelType.BOOLEAN) { @Override public ModelNode execute(LoadBalancer balancer) { return balancer.isStickySessionRemove() ? ModelNode.TRUE : ModelNode.FALSE; } }, ; private final AttributeDefinition definition; LoadBalancerMetric(String name, ModelType type) { this.definition = new SimpleAttributeDefinitionBuilder(name, type) .setRequired(false) .setStorageRuntime() .build(); } @Override public AttributeDefinition getDefinition() { return this.definition; } } private final FunctionExecutorRegistry<ModCluster> registry; ModClusterBalancerDefinition(FunctionExecutorRegistry<ModCluster> registry) { super(new Parameters(PATH_ELEMENT, UndertowExtension.getResolver(Constants.FILTER, ModClusterDefinition.PATH_ELEMENT.getKey(), PATH_ELEMENT.getKey())).setRuntime()); this.registry = registry; } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerSubModel(new ModClusterNodeDefinition(this.registry)); resourceRegistration.registerSubModel(new ModClusterLoadBalancingGroupDefinition(this.registry)); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { OperationStepHandler handler = new MetricHandler<>(new LoadBalancerMetricExecutor(this.registry), LoadBalancerMetric.class); // TODO Should some subset of these be registered as metrics? for (LoadBalancerMetric metric : EnumSet.allOf(LoadBalancerMetric.class)) { resourceRegistration.registerReadOnlyAttribute(metric.getDefinition(), handler); } } static class LoadBalancerMetricExecutor implements MetricExecutor<ModClusterStatus.LoadBalancer> { private final FunctionExecutorRegistry<ModCluster> registry; LoadBalancerMetricExecutor(FunctionExecutorRegistry<ModCluster> registry) { this.registry = registry; } @Override public ModelNode execute(OperationContext context, Metric<ModClusterStatus.LoadBalancer> metric) throws OperationFailedException { PathAddress balancerAddress = context.getCurrentAddress(); String balancerName = balancerAddress.getLastElement().getValue(); PathAddress serviceAddress = balancerAddress.getParent(); FunctionExecutor<ModCluster> executor = this.registry.get(new ModClusterServiceNameProvider(serviceAddress).getServiceName()); return (executor != null) ? executor.execute(new MetricFunction<>(new LoadBalancerFunction(balancerName), metric)) : null; } } static class LoadBalancerFunction implements Function<ModCluster, ModClusterStatus.LoadBalancer> { private final String balancerName; LoadBalancerFunction(String balancerName) { this.balancerName = balancerName; } @Override public LoadBalancer apply(ModCluster service) { return service.getController().getStatus().getLoadBalancer(this.balancerName); } } }
7,660
43.80117
173
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ModClusterResource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import io.undertow.server.handlers.proxy.mod_cluster.ModCluster; import io.undertow.server.handlers.proxy.mod_cluster.ModClusterStatus; import io.undertow.util.CopyOnWriteMap; import org.jboss.as.clustering.controller.ChildResourceProvider; import org.jboss.as.clustering.controller.ComplexResource; import org.jboss.as.clustering.controller.SimpleChildResourceProvider; import org.jboss.as.controller.registry.PlaceholderResource; import org.jboss.as.controller.registry.Resource; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Runtime resource implementation for {@link ModCluster}. * @author Paul Ferraro */ public class ModClusterResource extends ComplexResource implements Consumer<ModCluster> { private final Map<String, ChildResourceProvider> providers; public ModClusterResource(Resource resource) { this(resource, new CopyOnWriteMap<>()); } private ModClusterResource(Resource resource, Map<String, ChildResourceProvider> providers) { super(resource, providers, ModClusterResource::new); this.providers = providers; } @Override public void accept(ModCluster service) { this.providers.put(ModClusterBalancerDefinition.PATH_ELEMENT.getKey(), new ModClusterBalancerResourceProvider(service)); } static class ModClusterBalancerResourceProvider implements ChildResourceProvider { private final ModCluster service; ModClusterBalancerResourceProvider(ModCluster service) { this.service = service; } @Override public Resource getChild(String name) { ModClusterStatus status = this.service.getController().getStatus(); ModClusterStatus.LoadBalancer balancer = status.getLoadBalancer(name); return (balancer != null) ? new ComplexResource(PlaceholderResource.INSTANCE, Map.of(ModClusterNodeDefinition.PATH_ELEMENT.getKey(), new ModClusterNodeResourceProvider(balancer), ModClusterLoadBalancingGroupDefinition.PATH_ELEMENT.getKey(), new SimpleChildResourceProvider(balancer.getNodes().stream().map(ModClusterStatus.Node::getDomain).filter(Predicate.not(Objects::isNull)).distinct().collect(Collectors.toSet())))) : null; } @Override public Set<String> getChildren() { ModClusterStatus status = this.service.getController().getStatus(); return status.getLoadBalancers().stream().map(ModClusterStatus.LoadBalancer::getName).collect(Collectors.toSet()); } } static class ModClusterNodeResourceProvider implements ChildResourceProvider { private final ModClusterStatus.LoadBalancer balancer; ModClusterNodeResourceProvider(ModClusterStatus.LoadBalancer balancer) { this.balancer = balancer; } @Override public Resource getChild(String name) { ModClusterStatus.Node node = this.balancer.getNode(name); return (node != null) ? new ComplexResource(PlaceholderResource.INSTANCE, Map.of(ModClusterContextDefinition.PATH_ELEMENT.getKey(), new SimpleChildResourceProvider(node.getContexts().stream().map(ModClusterStatus.Context::getName).collect(Collectors.toSet())))) : null; } @Override public Set<String> getChildren() { return this.balancer.getNodes().stream().map(ModClusterStatus.Node::getName).collect(Collectors.toSet()); } } }
4,596
43.631068
440
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/CustomFilterDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.List; import java.util.Map; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeMarshallers; import org.jboss.as.controller.AttributeParsers; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PropertiesAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.wildfly.extension.undertow.deployment.ConfiguredHandlerWrapper; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author Tomaz Cerar (c) 2014 Red Hat Inc. */ public class CustomFilterDefinition extends SimpleFilterDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement("custom-filter"); public static final AttributeDefinition CLASS_NAME = new SimpleAttributeDefinitionBuilder("class-name", ModelType.STRING) .setRequired(true) .setAllowExpression(true) .setRestartAllServices() .build(); public static final AttributeDefinition MODULE = new SimpleAttributeDefinitionBuilder("module", ModelType.STRING) .setRequired(true) .setAllowExpression(true) .setRestartAllServices() .build(); public static final PropertiesAttributeDefinition PARAMETERS = new PropertiesAttributeDefinition.Builder("parameters", true) .setRequired(false) .setAllowExpression(true) .setAttributeParser(new AttributeParsers.PropertiesParser(null, "param", false)) .setAttributeMarshaller(new AttributeMarshallers.PropertiesAttributeMarshaller(null, "param", false)) .setRestartAllServices() .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(CLASS_NAME, MODULE, PARAMETERS); CustomFilterDefinition() { super(PATH_ELEMENT, CustomFilterDefinition::createHandlerWrapper); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) throws OperationFailedException { String className = CLASS_NAME.resolveModelAttribute(context, model).asString(); String moduleName = MODULE.resolveModelAttribute(context, model).asString(); Map<String, String> parameters = PARAMETERS.unwrap(context, model); UndertowLogger.ROOT_LOGGER.debugf("Creating http handler %s from module %s with parameters %s", className, moduleName, parameters); // Resolve module lazily return new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { Class<?> handlerClass = getHandlerClass(className, moduleName); return new ConfiguredHandlerWrapper(handlerClass, parameters).wrap(handler); } }; } private static Class<?> getHandlerClass(String className, String moduleName) { ModuleLoader moduleLoader = Module.getBootModuleLoader(); try { Module filterModule = moduleLoader.loadModule(moduleName); return filterModule.getClassLoader().loadClassLocal(className); } catch (ModuleLoadException | ClassNotFoundException e) { throw UndertowLogger.ROOT_LOGGER.couldNotLoadHandlerFromModule(className,moduleName,e); } } }
4,863
43.218182
139
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/HandlerWrapperFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import io.undertow.server.HandlerWrapper; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; /** * Factory for creating a {@link HandlerWrapper}. * @author Paul Ferraro */ public interface HandlerWrapperFactory { HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) throws OperationFailedException; }
1,496
38.394737
115
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ErrorPageDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import io.undertow.server.HandlerWrapper; import io.undertow.server.handlers.error.FileErrorPageHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.Constants; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ public class ErrorPageDefinition extends SimpleFilterDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.ERROR_PAGE); public static final AttributeDefinition CODE = new SimpleAttributeDefinitionBuilder("code", ModelType.INT) .setAllowExpression(true) .setRequired(true) .setRestartAllServices() .build(); public static final AttributeDefinition PATH = new SimpleAttributeDefinitionBuilder("path", ModelType.STRING) .setAllowExpression(true) .setRequired(false) .setRestartAllServices() .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(CODE, PATH); ErrorPageDefinition() { super(PATH_ELEMENT, ErrorPageDefinition::createHandlerWrapper); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) throws OperationFailedException { int code = CODE.resolveModelAttribute(context, model).asInt(); String path = PATH.resolveModelAttribute(context, model).asStringOrNull(); return next -> new FileErrorPageHandler(next, Paths.get(path), code); } }
3,056
40.310811
123
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ModClusterLoadBalancingGroupDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import io.undertow.server.handlers.proxy.mod_cluster.ModCluster; import io.undertow.server.handlers.proxy.mod_cluster.ModClusterStatus; import org.jboss.as.clustering.controller.FunctionExecutor; import org.jboss.as.clustering.controller.FunctionExecutorRegistry; import org.jboss.as.clustering.controller.Operation; import org.jboss.as.clustering.controller.OperationExecutor; import org.jboss.as.clustering.controller.OperationFunction; import org.jboss.as.clustering.controller.OperationHandler; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; /** * Runtime representation of a mod_cluster context * * @author Stuart Douglas */ public class ModClusterLoadBalancingGroupDefinition extends SimpleResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.LOAD_BALANCING_GROUP); static final ResourceDescriptionResolver RESOLVER = UndertowExtension.getResolver(Constants.FILTER, ModClusterDefinition.PATH_ELEMENT.getKey(), ModClusterBalancerDefinition.PATH_ELEMENT.getKey(), PATH_ELEMENT.getKey()); enum LoadBalancingGroupOperation implements Operation<Map.Entry<ModClusterStatus.LoadBalancer, String>> { ENABLE_NODES(Constants.ENABLE_NODES, ModClusterStatus.Context::enable), DISABLE_NODES(Constants.DISABLE_NODES, ModClusterStatus.Context::disable), STOP_NODES(Constants.STOP_NODES, ModClusterStatus.Context::stop), ; private OperationDefinition definition; private final Consumer<ModClusterStatus.Context> operation; LoadBalancingGroupOperation(String name, Consumer<ModClusterStatus.Context> operation) { this.definition = SimpleOperationDefinitionBuilder.of(name, RESOLVER).setRuntimeOnly().build(); this.operation = operation; } @Override public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, Map.Entry<ModClusterStatus.LoadBalancer, String> entry) { ModClusterStatus.LoadBalancer balancer = entry.getKey(); String groupName = entry.getValue(); for (ModClusterStatus.Node node : balancer.getNodes()) { if (groupName.equals(node.getDomain())) { for (ModClusterStatus.Context context : node.getContexts()) { this.operation.accept(context); } } } return null; } @Override public OperationDefinition getDefinition() { return this.definition; } } private final FunctionExecutorRegistry<ModCluster> registry; ModClusterLoadBalancingGroupDefinition(FunctionExecutorRegistry<ModCluster> registry) { super(new Parameters(PATH_ELEMENT, RESOLVER).setRuntime()); this.registry = registry; } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { new OperationHandler<>(new LoadBalancingGroupOperationExecutor(this.registry), LoadBalancingGroupOperation.class).register(resourceRegistration); } static final Function<OperationContext, Function<ModCluster, Map.Entry<ModClusterStatus.LoadBalancer, String>>> LOAD_BALANCING_GROUP_FUNCTION_FACTORY = new Function<>() { @Override public Function<ModCluster, Map.Entry<ModClusterStatus.LoadBalancer, String>> apply(OperationContext context) { PathAddress groupAddress = context.getCurrentAddress(); String groupName = groupAddress.getLastElement().getValue(); PathAddress balancerAddress = groupAddress.getParent(); String balancerName = balancerAddress.getLastElement().getValue(); return new LoadBalancingGroupFunction(balancerName, groupName); } }; static class LoadBalancingGroupFunction implements Function<ModCluster, Map.Entry<ModClusterStatus.LoadBalancer, String>> { private final String balancerName; private final String groupName; LoadBalancingGroupFunction(String balancerName, String groupName) { this.balancerName = balancerName; this.groupName = groupName; } @Override public Map.Entry<ModClusterStatus.LoadBalancer, String> apply(ModCluster service) { ModClusterStatus.LoadBalancer balancer = service.getController().getStatus().getLoadBalancer(this.balancerName); return (balancer != null) ? Map.entry(balancer, this.groupName) : null; } } static class LoadBalancingGroupOperationExecutor implements OperationExecutor<Map.Entry<ModClusterStatus.LoadBalancer, String>> { private final FunctionExecutorRegistry<ModCluster> registry; LoadBalancingGroupOperationExecutor(FunctionExecutorRegistry<ModCluster> registry) { this.registry = registry; } @Override public ModelNode execute(OperationContext context, ModelNode op, Operation<Map.Entry<ModClusterStatus.LoadBalancer, String>> operation) throws OperationFailedException { PathAddress serviceAddress = context.getCurrentAddress().getParent().getParent(); FunctionExecutor<ModCluster> executor = this.registry.get(new ModClusterServiceNameProvider(serviceAddress).getServiceName()); Function<ModCluster, Map.Entry<ModClusterStatus.LoadBalancer, String>> mapper = LOAD_BALANCING_GROUP_FUNCTION_FACTORY.apply(context); return (executor != null) ? executor.execute(new OperationFunction<>(context, op, mapper, operation)) : null; } } }
7,377
48.516779
223
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ModClusterContextDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.EnumSet; import java.util.function.Consumer; import java.util.function.Function; import io.undertow.server.handlers.proxy.mod_cluster.ModCluster; import io.undertow.server.handlers.proxy.mod_cluster.ModClusterStatus; import org.jboss.as.clustering.controller.FunctionExecutor; import org.jboss.as.clustering.controller.FunctionExecutorRegistry; import org.jboss.as.clustering.controller.Metric; import org.jboss.as.clustering.controller.MetricExecutor; import org.jboss.as.clustering.controller.MetricFunction; import org.jboss.as.clustering.controller.MetricHandler; import org.jboss.as.clustering.controller.Operation; import org.jboss.as.clustering.controller.OperationExecutor; import org.jboss.as.clustering.controller.OperationFunction; import org.jboss.as.clustering.controller.OperationHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; /** * Runtime representation of a mod_cluster context * * @author Stuart Douglas */ class ModClusterContextDefinition extends SimpleResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.CONTEXT); static final ResourceDescriptionResolver RESOLVER = UndertowExtension.getResolver(Constants.FILTER, ModClusterDefinition.PATH_ELEMENT.getKey(), ModClusterBalancerDefinition.PATH_ELEMENT.getKey(), ModClusterNodeDefinition.PATH_ELEMENT.getKey(), PATH_ELEMENT.getKey()); enum ContextMetric implements Metric<ModClusterStatus.Context> { STATUS(Constants.STATUS, ModelType.STRING) { @Override public ModelNode execute(ModClusterStatus.Context context) { return new ModelNode(context.isEnabled() ? "enabled" : context.isStopped() ? "stopped" : "disabled"); } }, REQUESTS(Constants.REQUESTS, ModelType.INT) { @Override public ModelNode execute(ModClusterStatus.Context context) { return new ModelNode(context.getRequests()); } }, ; private final AttributeDefinition definition; ContextMetric(String name, ModelType type) { this.definition = new SimpleAttributeDefinitionBuilder(name, type) .setRequired(false) .setStorageRuntime() .build(); } @Override public AttributeDefinition getDefinition() { return this.definition; } } enum ContextOperation implements Operation<ModClusterStatus.Context> { ENABLE(Constants.ENABLE, ModClusterStatus.Context::enable), DISABLE(Constants.DISABLE, ModClusterStatus.Context::disable), STOP(Constants.STOP, ModClusterStatus.Context::stop), ; private OperationDefinition definition; private final Consumer<ModClusterStatus.Context> operation; ContextOperation(String name, Consumer<ModClusterStatus.Context> operation) { this.definition = SimpleOperationDefinitionBuilder.of(name, RESOLVER).setRuntimeOnly().build(); this.operation = operation; } @Override public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterStatus.Context context) { this.operation.accept(context); return null; } @Override public OperationDefinition getDefinition() { return this.definition; } } private final FunctionExecutorRegistry<ModCluster> registry; ModClusterContextDefinition(FunctionExecutorRegistry<ModCluster> registry) { super(new Parameters(PATH_ELEMENT, RESOLVER).setRuntime()); this.registry = registry; } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { OperationStepHandler handler = new MetricHandler<>(new ContextMetricExecutor(new FunctionExecutorFactory(this.registry)), ContextMetric.class); // TODO Should some subset of these be registered as metrics? for (ContextMetric metric : EnumSet.allOf(ContextMetric.class)) { resourceRegistration.registerReadOnlyAttribute(metric.getDefinition(), handler); } } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { new OperationHandler<>(new ContextOperationExecutor(new FunctionExecutorFactory(this.registry)), ContextOperation.class).register(resourceRegistration); } static class FunctionExecutorFactory implements Function<OperationContext, FunctionExecutor<ModCluster>> { private final FunctionExecutorRegistry<ModCluster> registry; FunctionExecutorFactory(FunctionExecutorRegistry<ModCluster> registry) { this.registry = registry; } @Override public FunctionExecutor<ModCluster> apply(OperationContext context) { PathAddress serviceAddress = context.getCurrentAddress().getParent().getParent().getParent(); return this.registry.get(new ModClusterServiceNameProvider(serviceAddress).getServiceName()); } } static final Function<OperationContext, Function<ModCluster, ModClusterStatus.Context>> NODE_FUNCTION_FACTORY = new Function<>() { @Override public Function<ModCluster, ModClusterStatus.Context> apply(OperationContext context) { PathAddress contextAddress = context.getCurrentAddress(); String contextName = contextAddress.getLastElement().getValue(); PathAddress nodeAddress = contextAddress.getParent(); String nodeName = nodeAddress.getLastElement().getValue(); PathAddress balancerAddress = nodeAddress.getParent(); String balancerName = balancerAddress.getLastElement().getValue(); return new ContextFunction(balancerName, nodeName, contextName); } }; static class ContextFunction implements Function<ModCluster, ModClusterStatus.Context> { private final String balancerName; private final String nodeName; private final String contextName; ContextFunction(String balancerName, String nodeName, String contextName) { this.balancerName = balancerName; this.nodeName = nodeName; this.contextName = contextName; } @Override public ModClusterStatus.Context apply(ModCluster service) { ModClusterStatus.LoadBalancer balancer = service.getController().getStatus().getLoadBalancer(this.balancerName); ModClusterStatus.Node node = (balancer != null) ? balancer.getNode(this.nodeName) : null; return (node != null) ? node.getContext(this.contextName) : null; } } static class ContextMetricExecutor implements MetricExecutor<ModClusterStatus.Context> { private final Function<OperationContext, FunctionExecutor<ModCluster>> factory; ContextMetricExecutor(Function<OperationContext, FunctionExecutor<ModCluster>> factory) { this.factory = factory; } @Override public ModelNode execute(OperationContext context, Metric<ModClusterStatus.Context> metric) throws OperationFailedException { FunctionExecutor<ModCluster> executor = this.factory.apply(context); Function<ModCluster, ModClusterStatus.Context> mapper = NODE_FUNCTION_FACTORY.apply(context); return (executor != null) ? executor.execute(new MetricFunction<>(mapper, metric)) : null; } } static class ContextOperationExecutor implements OperationExecutor<ModClusterStatus.Context> { private final Function<OperationContext, FunctionExecutor<ModCluster>> factory; ContextOperationExecutor(Function<OperationContext, FunctionExecutor<ModCluster>> factory) { this.factory = factory; } @Override public ModelNode execute(OperationContext context, ModelNode op, Operation<ModClusterStatus.Context> operation) throws OperationFailedException { FunctionExecutor<ModCluster> executor = this.factory.apply(context); Function<ModCluster, ModClusterStatus.Context> mapper = NODE_FUNCTION_FACTORY.apply(context); return (executor != null) ? executor.execute(new OperationFunction<>(context, op, mapper, operation)) : null; } } }
10,274
45.493213
271
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/SingleAffinityResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.function.UnaryOperator; import org.jboss.as.controller.PathElement; import org.wildfly.extension.undertow.Constants; /** * Affinity resource configuring default - single - routing behavior. * * @author Radoslav Husar */ public class SingleAffinityResourceDefinition extends AffinityResourceDefinition { public static final PathElement PATH = pathElement(Constants.SINGLE); public SingleAffinityResourceDefinition() { super(PATH, UnaryOperator.identity()); } }
1,578
35.72093
82
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/FilterService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.function.Consumer; import java.util.function.Supplier; import io.undertow.Handlers; import io.undertow.predicate.Predicate; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.extension.undertow.FilterLocation; import org.wildfly.extension.undertow.UndertowFilter; /** * @author Tomaz Cerar (c) 2014 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class FilterService implements Service<UndertowFilter>, UndertowFilter { private final Consumer<UndertowFilter> serviceConsumer; private final Supplier<HandlerWrapper> wrapper; private final Supplier<FilterLocation> location; private final Predicate predicate; private final int priority; FilterService(final Consumer<UndertowFilter> serviceConsumer, final Supplier<HandlerWrapper> wrapper, final Supplier<FilterLocation> location, final Predicate predicate, final int priority) { this.serviceConsumer = serviceConsumer; this.wrapper = wrapper; this.location = location; this.predicate = predicate; this.priority = priority; } @Override public void start(final StartContext context) throws StartException { location.get().addFilter(this); serviceConsumer.accept(this); } @Override public void stop(final StopContext context) { serviceConsumer.accept(null); location.get().removeFilter(this); } @Override public int getPriority() { return priority; } @Override public UndertowFilter getValue() { return this; } @Override public HttpHandler wrap(HttpHandler next) { HttpHandler handler = this.wrapper.get().wrap(next); return (this.predicate != null) ? Handlers.predicate(this.predicate, handler, next) : handler; } }
3,113
35.209302
195
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/RequestLimitHandlerDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.List; import io.undertow.server.HandlerWrapper; import io.undertow.server.handlers.RequestLimitingHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.operations.validation.IntRangeValidator; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ public class RequestLimitHandlerDefinition extends SimpleFilterDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement("request-limit"); public static final AttributeDefinition MAX_CONCURRENT_REQUESTS = new SimpleAttributeDefinitionBuilder("max-concurrent-requests", ModelType.INT) .setValidator(new IntRangeValidator(1, false, true)) .setAllowExpression(true) .setRequired(true) .setRestartAllServices() .build(); public static final AttributeDefinition QUEUE_SIZE = new SimpleAttributeDefinitionBuilder("queue-size", ModelType.INT) .setValidator(new IntRangeValidator(0, true, true)) .setAllowExpression(true) .setRequired(false) .setDefaultValue(ModelNode.ZERO) .setRestartAllServices() .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(MAX_CONCURRENT_REQUESTS, QUEUE_SIZE); RequestLimitHandlerDefinition() { super(PATH_ELEMENT, RequestLimitHandlerDefinition::createHandlerWrapper); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) throws OperationFailedException { int maxConcurrentRequests = MAX_CONCURRENT_REQUESTS.resolveModelAttribute(context, model).asInt(); int queueSize = QUEUE_SIZE.resolveModelAttribute(context, model).asInt(); return next -> new RequestLimitingHandler(maxConcurrentRequests, queueSize, next); } }
3,369
41.658228
148
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/ModClusterServiceNameProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import org.jboss.as.controller.PathAddress; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.extension.undertow.UndertowService; /** * Provides the service name for {@link io.undertow.server.handlers.proxy.mod_cluster.ModCluster}. * @author Paul Ferraro */ public class ModClusterServiceNameProvider extends SimpleServiceNameProvider { public ModClusterServiceNameProvider(PathAddress address) { super(UndertowService.FILTER.append(address.getLastElement().getValue(), "service")); } }
1,615
40.435897
98
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/RewriteFilterDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.List; import io.undertow.attribute.ExchangeAttributes; import io.undertow.server.HandlerWrapper; import io.undertow.server.handlers.RedirectHandler; import io.undertow.server.handlers.SetAttributeHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.Constants; /** * @author Stuart Douglas */ public class RewriteFilterDefinition extends SimpleFilterDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.REWRITE); public static final AttributeDefinition TARGET = new SimpleAttributeDefinitionBuilder("target", ModelType.STRING) .setRequired(true) .setAllowExpression(true) .setRestartAllServices() .build(); public static final AttributeDefinition REDIRECT = new SimpleAttributeDefinitionBuilder("redirect", ModelType.BOOLEAN) .setRequired(false) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .setRestartAllServices() .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(TARGET, REDIRECT); RewriteFilterDefinition() { super(PATH_ELEMENT, RewriteFilterDefinition::createHandlerWrapper); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) throws OperationFailedException { String target = TARGET.resolveModelAttribute(context, model).asString(); boolean redirect = REDIRECT.resolveModelAttribute(context, model).asBoolean(); return next -> redirect ? new RedirectHandler(target) : new SetAttributeHandler(next, ExchangeAttributes.relativePath(), ExchangeAttributes.parser(RewriteFilterDefinition.class.getClassLoader()).parse(target)); } }
3,294
40.708861
218
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/filters/BasicAuthHandler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.filters; import java.util.Collection; import java.util.Collections; import io.undertow.security.handlers.AuthenticationCallHandler; import io.undertow.server.HandlerWrapper; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * TODO: This appears to be useless, we should probably get rid of it, or replace it with something useful * * * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ @Deprecated public class BasicAuthHandler extends SimpleFilterDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement("basic-auth"); public static final AttributeDefinition SECURITY_DOMAIN = new SimpleAttributeDefinitionBuilder("security-domain", ModelType.STRING) .setRequired(true) .setRestartAllServices() .build(); private BasicAuthHandler() { super(PATH_ELEMENT, BasicAuthHandler::createHandlerWrapper); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.singleton(SECURITY_DOMAIN); } static HandlerWrapper createHandlerWrapper(OperationContext context, ModelNode model) { return AuthenticationCallHandler::new; } }
2,510
37.630769
135
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/SessionManagementProviderFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.metadata.web.jboss.ReplicationConfig; import org.wildfly.clustering.web.container.SessionManagementProvider; /** * Returns the appropriate {@link SessionManagementProvider} for the given deployment unit. * @author Paul Ferraro */ public interface SessionManagementProviderFactory { /** * Returns the appropriate {@link SessionManagementProvider} for the specified deployment unit, * generated from the specified {@link ReplicationConfig} if necessary. * @param unit a deployment unit * @param config a legacy {@link ReplicationConfig} * @return a session management provider */ SessionManagementProvider createSessionManagementProvider(DeploymentUnit unit, ReplicationConfig config); }
1,872
42.55814
109
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/SessionConfigWrapperFactoryServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import java.util.function.Consumer; import java.util.function.Function; import io.undertow.servlet.api.SessionConfigWrapper; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.web.session.AffinityLocator; import org.jboss.as.web.session.SessionIdentifierCodec; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.CompositeDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.extension.undertow.CookieConfig; /** * Configures a service that provides a {@link SessionConfigWrapper} factory. * @author Paul Ferraro */ public class SessionConfigWrapperFactoryServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Function<CookieConfig, SessionConfigWrapper> { private final SupplierDependency<SessionIdentifierCodec> codecDependency; private final SupplierDependency<AffinityLocator> locatorDependency; public SessionConfigWrapperFactoryServiceConfigurator(ServiceName name, SupplierDependency<SessionIdentifierCodec> codecDependency, SupplierDependency<AffinityLocator> locatorDependency) { super(name); this.codecDependency = codecDependency; this.locatorDependency = locatorDependency; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceName name = this.getServiceName(); ServiceBuilder<?> builder = target.addService(name); Consumer<Function<CookieConfig, SessionConfigWrapper>> function = new CompositeDependency(this.codecDependency, this.locatorDependency).register(builder).provides(name); return builder.setInstance(Service.newInstance(function, this)); } @Override public SessionConfigWrapper apply(CookieConfig config) { return (config != null) ? new AffinitySessionConfigWrapper(config, this.locatorDependency.get()) : new CodecSessionConfigWrapper(this.codecDependency.get()); } }
3,232
45.185714
192
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/SharedSessionConfigSchema.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import java.util.List; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.xml.IntVersionSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.jbossallxml.JBossAllSchema; import org.jboss.as.web.session.SharedSessionManagerConfig; import org.jboss.staxmapper.IntVersion; import org.jboss.staxmapper.XMLExtendedStreamReader; /** * @author Paul Ferraro */ public enum SharedSessionConfigSchema implements JBossAllSchema<SharedSessionConfigSchema, SharedSessionManagerConfig> { VERSION_1_0(1, 0), VERSION_2_0(2, 0), ; private final VersionedNamespace<IntVersion, SharedSessionConfigSchema> namespace; SharedSessionConfigSchema(int major, int minor) { this.namespace = IntVersionSchema.createURN(List.of(IntVersionSchema.JBOSS_IDENTIFIER, this.getLocalName()), new IntVersion(major, minor)); } @Override public String getLocalName() { return "shared-session-config"; } @Override public VersionedNamespace<IntVersion, SharedSessionConfigSchema> getNamespace() { return this.namespace; } @Override public SharedSessionManagerConfig parse(XMLExtendedStreamReader reader, DeploymentUnit unit) throws XMLStreamException { return new SharedSessionConfigParser(this).parse(reader, unit); } }
2,479
37.153846
147
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/SharedSessionConfigXMLReader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.as.web.session.SharedSessionManagerConfig; import org.jboss.metadata.parser.jbossweb.ReplicationConfigParser; import org.jboss.metadata.parser.servlet.SessionConfigMetaDataParser; import org.jboss.metadata.property.PropertyReplacer; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLExtendedStreamReader; /** * @author Paul Ferraro */ public class SharedSessionConfigXMLReader implements XMLElementReader<SharedSessionManagerConfig> { private final SharedSessionConfigSchema schema; private final PropertyReplacer replacer; public SharedSessionConfigXMLReader(SharedSessionConfigSchema schema, PropertyReplacer replacer) { this.schema = schema; this.replacer = replacer; } @SuppressWarnings("deprecation") @Override public void readElement(XMLExtendedStreamReader reader, SharedSessionManagerConfig result) throws XMLStreamException { ParseUtils.requireNoAttributes(reader); if (!this.schema.since(SharedSessionConfigSchema.VERSION_2_0)) { // Prior to 2.0, shared session manager was distributable by default result.setDistributable(true); } while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) { switch (reader.getLocalName()) { case "max-active-sessions": { int value = Integer.parseInt(this.replacer.replaceProperties(reader.getElementText())); if (value > 0) { result.setMaxActiveSessions(value); } break; } case "replication-config": { if (this.schema.since(SharedSessionConfigSchema.VERSION_2_0)) { throw ParseUtils.unexpectedElement(reader); } result.setReplicationConfig(ReplicationConfigParser.parse(reader, this.replacer)); break; } case "session-config": { result.setSessionConfig(SessionConfigMetaDataParser.parse(reader, this.replacer)); break; } case "distributable": { if (this.schema.since(SharedSessionConfigSchema.VERSION_2_0)) { ParseUtils.requireNoAttributes(reader); ParseUtils.requireNoContent(reader); result.setDistributable(true); break; } } default: { throw ParseUtils.unexpectedElement(reader); } } } } }
3,924
40.315789
122
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/SessionManagerFactoryServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import java.util.function.Consumer; import java.util.function.Supplier; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.SimpleServiceNameProvider; import io.undertow.servlet.api.SessionManagerFactory; /** * Configures a service providing a {@link SessionManagerFactory}. * @author Paul Ferraro */ public class SessionManagerFactoryServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator { private final Supplier<SessionManagerFactory> provider; public SessionManagerFactoryServiceConfigurator(ServiceName name, Supplier<SessionManagerFactory> provider) { super(name); this.provider = provider; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<SessionManagerFactory> injector = builder.provides(this.getServiceName()); return builder.setInstance(Service.newInstance(injector, this.provider.get())); } }
2,308
39.508772
130
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/SharedSessionConfigParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import org.jboss.as.ee.structure.JBossDescriptorPropertyReplacement; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.jbossallxml.JBossAllXMLParser; import org.jboss.as.web.session.SharedSessionManagerConfig; import org.jboss.metadata.property.PropertyReplacer; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.wildfly.extension.undertow.logging.UndertowLogger; import javax.xml.stream.XMLStreamException; /** * Parse shared session manager config * * @author Stuart Douglas */ public class SharedSessionConfigParser implements JBossAllXMLParser<SharedSessionManagerConfig> { private final SharedSessionConfigSchema schema; public SharedSessionConfigParser(SharedSessionConfigSchema schema) { this.schema = schema; } @Override public SharedSessionManagerConfig parse(XMLExtendedStreamReader reader, DeploymentUnit unit) throws XMLStreamException { if (unit.getParent() != null) { UndertowLogger.ROOT_LOGGER.sharedSessionConfigNotInRootDeployment(unit.getName()); return null; } PropertyReplacer replacer = JBossDescriptorPropertyReplacement.propertyReplacer(unit); SharedSessionManagerConfig result = new SharedSessionManagerConfig(); new SharedSessionConfigXMLReader(this.schema, replacer).readElement(reader, result); return result; } }
2,483
40.4
124
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/CodecSessionConfigWrapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import org.jboss.as.web.session.SessionIdentifierCodec; import io.undertow.server.session.SessionConfig; import io.undertow.servlet.api.Deployment; import io.undertow.servlet.api.SessionConfigWrapper; /** * Adds session identifier encoding/decoding to a {@link SessionConfig}. * @author Paul Ferraro */ public class CodecSessionConfigWrapper implements SessionConfigWrapper { private final SessionIdentifierCodec codec; public CodecSessionConfigWrapper(SessionIdentifierCodec codec) { this.codec = codec; } @Override public SessionConfig wrap(SessionConfig config, Deployment deployment) { return new CodecSessionConfig(config, this.codec); } }
1,766
35.8125
76
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/SimpleAffinityLocatorServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import java.util.function.Consumer; import java.util.function.Function; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.web.session.AffinityLocator; import org.jboss.as.web.session.SimpleAffinityLocator; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Server; /** * Configures a {@link Service} providing a non-distributable {@link AffinityLocator} implementation. * * @author Radoslav Husar */ class SimpleAffinityLocatorServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Function<Server, AffinityLocator> { private final String serverName; private volatile SupplierDependency<Server> server; public SimpleAffinityLocatorServiceConfigurator(ServiceName name, String serverName) { super(name); this.serverName = serverName; } @Override public AffinityLocator apply(Server server) { return new SimpleAffinityLocator(server.getRoute()); } @Override public ServiceConfigurator configure(CapabilityServiceSupport support) { this.server = new ServiceSupplierDependency<>(support.getCapabilityServiceName(Capabilities.CAPABILITY_SERVER, this.serverName)); return this; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<AffinityLocator> locator = this.server.register(builder).provides(this.getServiceName()); Service service = new FunctionalService<>(locator, this, this.server); return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); } }
3,382
41.2875
158
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/DistributableServerRuntimeHandler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import org.jboss.as.controller.OperationContext; /** * Installs any runtime services necessary to support distributable web applications on a given server. * @author Paul Ferraro */ public interface DistributableServerRuntimeHandler { void execute(OperationContext context, String serverName); }
1,377
39.529412
103
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/CodecSessionConfig.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import org.jboss.as.web.session.SessionIdentifierCodec; import io.undertow.server.HttpServerExchange; import io.undertow.server.session.SessionConfig; /** * {@link SessionConfig} decorator that performs encoding/decoding of the session identifier. * In this way, routing is completely opaque to the request, session, and session manager. * @author Paul Ferraro */ public class CodecSessionConfig implements SessionConfig { private final SessionConfig config; private final SessionIdentifierCodec codec; public CodecSessionConfig(SessionConfig config, SessionIdentifierCodec codec) { this.config = config; this.codec = codec; } @Override public void setSessionId(HttpServerExchange exchange, String sessionId) { CharSequence encodedSessionId = this.codec.encode(sessionId); String requestedSessionId = this.config.findSessionId(exchange); // Apply only if identifier changed if (!encodedSessionId.equals(requestedSessionId)) { this.config.setSessionId(exchange, encodedSessionId.toString()); } } @Override public void clearSession(HttpServerExchange exchange, String sessionId) { CharSequence encodedSessionId = this.codec.encode(sessionId); this.config.clearSession(exchange, encodedSessionId.toString()); } @Override public String findSessionId(HttpServerExchange exchange) { String requestedSessionId = this.config.findSessionId(exchange); return (requestedSessionId != null) ? this.codec.decode(requestedSessionId).toString() : null; } @Override public SessionCookieSource sessionCookieSource(HttpServerExchange exchange) { return this.config.sessionCookieSource(exchange); } @Override public String rewriteUrl(String originalUrl, String sessionId) { CharSequence encodedSessionId = this.codec.encode(sessionId); return this.config.rewriteUrl(originalUrl, encodedSessionId.toString()); } }
3,078
38.987013
102
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/NonDistributableSessionManagementProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import java.util.List; import java.util.function.Function; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.msc.service.ServiceName; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.web.container.SessionManagementProvider; import org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration; import org.wildfly.clustering.web.container.WebDeploymentConfiguration; import io.undertow.servlet.api.SessionManagerFactory; /** * {@link SessionManagementProvider} for non-distributed web deployments. * @author Paul Ferraro */ public class NonDistributableSessionManagementProvider implements SessionManagementProvider { private final Function<SessionManagerFactoryConfiguration, SessionManagerFactory> factory; public NonDistributableSessionManagementProvider(Function<SessionManagerFactoryConfiguration, SessionManagerFactory> factory) { this.factory = factory; } @Override public Iterable<CapabilityServiceConfigurator> getSessionManagerFactoryServiceConfigurators(ServiceName name, SessionManagerFactoryConfiguration configuration) { return List.of(new SessionManagerFactoryServiceConfigurator(name, () -> this.factory.apply(configuration))); } @Override public Iterable<CapabilityServiceConfigurator> getSessionAffinityServiceConfigurators(ServiceName name, WebDeploymentConfiguration configuration) { CapabilityServiceConfigurator codecConfigurator = new SimpleSessionIdentifierCodecServiceConfigurator(name.append("codec"), configuration.getServerName()); CapabilityServiceConfigurator locatorConfigurator = new SimpleAffinityLocatorServiceConfigurator(name.append("locator"), configuration.getServerName()); CapabilityServiceConfigurator wrapperFactoryConfigurator = new SessionConfigWrapperFactoryServiceConfigurator(name, new ServiceSupplierDependency<>(codecConfigurator), new ServiceSupplierDependency<>(locatorConfigurator)); return List.of(codecConfigurator, locatorConfigurator, wrapperFactoryConfigurator); } }
3,185
51.229508
230
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/SimpleSessionIdentifierCodecServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import java.util.function.Consumer; import java.util.function.Function; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.web.session.RoutingSupport; import org.jboss.as.web.session.SessionIdentifierCodec; import org.jboss.as.web.session.SimpleRoutingSupport; import org.jboss.as.web.session.SimpleSessionIdentifierCodec; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Server; /** * Configures a Service providing a non-distributable {@link SessionIdentifierCodec} implementation. * @author Paul Ferraro */ public class SimpleSessionIdentifierCodecServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Function<Server, SessionIdentifierCodec> { private final String serverName; private final RoutingSupport routing = new SimpleRoutingSupport(); private volatile SupplierDependency<Server> server; public SimpleSessionIdentifierCodecServiceConfigurator(ServiceName name, String serverName) { super(name); this.serverName = serverName; } @Override public SessionIdentifierCodec apply(Server server) { return new SimpleSessionIdentifierCodec(this.routing, server.getRoute()); } @Override public ServiceConfigurator configure(CapabilityServiceSupport support) { this.server = new ServiceSupplierDependency<>(support.getCapabilityServiceName(Capabilities.CAPABILITY_SERVER, this.serverName)); return this; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<SessionIdentifierCodec> codec = this.server.register(builder).provides(this.getServiceName()); Service service = new FunctionalService<>(codec, this, this.server); return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); } }
3,622
43.182927
179
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/AffinitySessionConfigWrapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import java.util.EnumMap; import java.util.Locale; import java.util.Map; import io.undertow.server.session.PathParameterSessionConfig; import io.undertow.server.session.SessionConfig; import io.undertow.server.session.SessionCookieConfig; import io.undertow.servlet.api.Deployment; import io.undertow.servlet.api.SessionConfigWrapper; import org.jboss.as.web.session.AffinityLocator; import org.wildfly.extension.undertow.CookieConfig; /** * Adds affinity locator handling to a {@link SessionConfig}. * * @author Radoslav Husar */ public class AffinitySessionConfigWrapper implements SessionConfigWrapper { private final Map<SessionConfig.SessionCookieSource, SessionConfig> affinityConfigMap = new EnumMap<>(SessionConfig.SessionCookieSource.class); private final AffinityLocator locator; public AffinitySessionConfigWrapper(CookieConfig config, AffinityLocator locator) { this.locator = locator; // Setup SessionCookieSource->SessionConfig mapping: // SessionConfig.SessionCookieSource.COOKIE SessionCookieConfig cookieSessionConfig = new SessionCookieConfig(); cookieSessionConfig.setCookieName(config.getName()); if (config.getDomain() != null) { cookieSessionConfig.setDomain(config.getDomain()); } if (config.getHttpOnly() != null) { cookieSessionConfig.setHttpOnly(config.getHttpOnly()); } if (config.getSecure() != null) { cookieSessionConfig.setSecure(config.getSecure()); } if (config.getMaxAge() != null) { cookieSessionConfig.setMaxAge(config.getMaxAge()); } affinityConfigMap.put(SessionConfig.SessionCookieSource.COOKIE, cookieSessionConfig); // SessionConfig.SessionCookieSource.URL // In this case use the cookie name as the path parameter String pathParameterName = config.getName().toLowerCase(Locale.ENGLISH); PathParameterSessionConfig pathParameterSessionConfig = new PathParameterSessionConfig(pathParameterName); affinityConfigMap.put(SessionConfig.SessionCookieSource.URL, pathParameterSessionConfig); } @Override public SessionConfig wrap(SessionConfig sessionConfig, Deployment deployment) { return new AffinitySessionConfig(sessionConfig, this.affinityConfigMap, this.locator); } }
3,433
39.880952
147
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/session/AffinitySessionConfig.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.session; import java.util.Map; import io.undertow.server.HttpServerExchange; import io.undertow.server.session.SessionConfig; import org.jboss.as.web.session.AffinityLocator; /** * Decorates {@link SessionConfig} with affinity encoding into a separate a cookie. * * @author Radoslav Husar */ public class AffinitySessionConfig implements SessionConfig { private final SessionConfig sessionConfig; private final Map<SessionCookieSource, SessionConfig> affinityConfigMap; private final AffinityLocator locator; public AffinitySessionConfig(SessionConfig sessionConfig, Map<SessionCookieSource, SessionConfig> affinityConfigMap, AffinityLocator locator) { this.sessionConfig = sessionConfig; this.affinityConfigMap = affinityConfigMap; this.locator = locator; } @Override public void setSessionId(HttpServerExchange exchange, String sessionId) { String requestedSessionId = this.sessionConfig.findSessionId(exchange); if (!sessionId.equals(requestedSessionId)) { this.sessionConfig.setSessionId(exchange, sessionId); } String affinity = this.locator.locate(sessionId); if (affinity != null) { // Always write affinity for every request if using cookies!! this.sessionConfigInUse(exchange).setSessionId(exchange, affinity); } } @Override public void clearSession(HttpServerExchange exchange, String sessionId) { this.sessionConfig.clearSession(exchange, sessionId); SessionConfig sessionConfigInUse = sessionConfigInUse(exchange); String existingAffinity = sessionConfigInUse.findSessionId(exchange); if (existingAffinity != null) { sessionConfigInUse.clearSession(exchange, existingAffinity); } } @Override public String findSessionId(HttpServerExchange exchange) { return this.sessionConfig.findSessionId(exchange); } @Override public SessionCookieSource sessionCookieSource(HttpServerExchange exchange) { return this.sessionConfig.sessionCookieSource(exchange); } @Override public String rewriteUrl(String originalUrl, String sessionId) { String url = this.sessionConfig.rewriteUrl(originalUrl, sessionId); String route = this.locator.locate(sessionId); if (route != null) { if (url.equals(originalUrl)) { // Rewritten URLs is unchanged -> use SessionCookieSource.COOKIE return this.affinityConfigMap.get(SessionCookieSource.COOKIE).rewriteUrl(url, route); } else { // Rewritten URL is different from the original URL -> use SessionCookieSource.URL return this.affinityConfigMap.get(SessionCookieSource.URL).rewriteUrl(url, route); } } return url; } private SessionConfig sessionConfigInUse(HttpServerExchange exchange) { switch (sessionConfig.sessionCookieSource(exchange)) { case URL: { return this.affinityConfigMap.get(SessionCookieSource.URL); } default: { return this.affinityConfigMap.get(SessionCookieSource.COOKIE); } } } }
4,314
37.526786
147
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/handlers/HandlerDefinitions.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.handlers; import java.util.Collection; import java.util.Collections; import java.util.List; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyRemoveStepHandler; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.SimpleResourceDefinition; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. */ public class HandlerDefinitions extends PersistentResourceDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.CONFIGURATION, Constants.HANDLER); public HandlerDefinitions() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getValue())) .setAddHandler(new ModelOnlyAddStepHandler()) .setRemoveHandler(ModelOnlyRemoveStepHandler.INSTANCE) ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptySet(); } @Override public List<? extends PersistentResourceDefinition> getChildren() { return List.of( new FileHandlerDefinition(), new ReverseProxyHandlerDefinition()); } }
2,485
38.460317
123
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/handlers/HandlerAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.handlers; import java.util.Collection; import java.util.function.Consumer; import java.util.function.Supplier; import io.undertow.server.HttpHandler; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceController; import org.wildfly.extension.requestcontroller.RequestController; import org.wildfly.extension.undertow.Capabilities; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class HandlerAdd extends AbstractAddStepHandler { private HandlerFactory factory; HandlerAdd(HandlerFactory factory, Collection<AttributeDefinition> attributes) { super(attributes); this.factory = factory; } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final String name = context.getCurrentAddressValue(); final RuntimeCapability<Void> newCapability = HandlerDefinition.CAPABILITY.fromBaseCapability(context.getCurrentAddress()); final boolean capabilityAvailable = context.hasOptionalCapability(Capabilities.REF_REQUEST_CONTROLLER, newCapability.getName(), null); final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(HandlerDefinition.CAPABILITY); final Consumer<HttpHandler> hhConsumer = sb.provides(HandlerDefinition.CAPABILITY); final Supplier<RequestController> rcSupplier = capabilityAvailable ? sb.requiresCapability(Capabilities.REF_REQUEST_CONTROLLER, RequestController.class) : null; sb.setInstance(new HandlerService(hhConsumer, rcSupplier, this.factory.createHandler(context, model), name)); sb.setInitialMode(ServiceController.Mode.ON_DEMAND); sb.install(); } }
3,192
45.955882
168
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/handlers/FileHandlerDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.handlers; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.resource.PathResourceManager; import io.undertow.server.handlers.resource.ResourceHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ public class FileHandlerDefinition extends HandlerDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.FILE); /*<file path="/opt/data" cache-buffer-size="1024" cache-buffers="1024"/>*/ public static final AttributeDefinition PATH = new SimpleAttributeDefinitionBuilder(Constants.PATH, ModelType.STRING) .setRequired(true) .setAllowExpression(true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition CACHE_BUFFER_SIZE = new SimpleAttributeDefinitionBuilder("cache-buffer-size", ModelType.LONG) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(1024)) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition CACHE_BUFFERS = new SimpleAttributeDefinitionBuilder("cache-buffers", ModelType.LONG) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(1024)) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition DIRECTORY_LISTING = new SimpleAttributeDefinitionBuilder(Constants.DIRECTORY_LISTING, ModelType.BOOLEAN) .setRequired(false) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition FOLLOW_SYMLINK = new SimpleAttributeDefinitionBuilder("follow-symlink", ModelType.BOOLEAN) .setRequired(false) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final StringListAttributeDefinition SAFE_SYMLINK_PATHS = new StringListAttributeDefinition.Builder("safe-symlink-paths") .setRequired(false) .setAllowExpression(true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition CASE_SENSITIVE = new SimpleAttributeDefinitionBuilder("case-sensitive", ModelType.BOOLEAN) .setRequired(false) .setAllowExpression(true) .setDefaultValue(ModelNode.TRUE) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(PATH, CACHE_BUFFER_SIZE, CACHE_BUFFERS, DIRECTORY_LISTING, FOLLOW_SYMLINK, CASE_SENSITIVE, SAFE_SYMLINK_PATHS); FileHandlerDefinition() { super(PATH_ELEMENT, FileHandlerDefinition::createHandler); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static HttpHandler createHandler(final OperationContext context, ModelNode model) throws OperationFailedException { final String path = PATH.resolveModelAttribute(context, model).asString(); final boolean directoryListing = DIRECTORY_LISTING.resolveModelAttribute(context, model).asBoolean(); final boolean followSymlink = FOLLOW_SYMLINK.resolveModelAttribute(context, model).asBoolean(); final boolean caseSensitive = CASE_SENSITIVE.resolveModelAttribute(context, model).asBoolean(); final long cacheBufferSize = CACHE_BUFFER_SIZE.resolveModelAttribute(context, model).asLong(); final long cacheBuffers = CACHE_BUFFERS.resolveModelAttribute(context, model).asLong(); final List<String> safePaths = SAFE_SYMLINK_PATHS.unwrap(context, model); final String[] paths = safePaths.toArray(new String[safePaths.size()]); UndertowLogger.ROOT_LOGGER.creatingFileHandler(path, directoryListing, followSymlink, caseSensitive, safePaths); Path base; try { base = Paths.get(path).normalize().toRealPath(); //workaround for JBEAP-10231 } catch (IOException e) { throw new OperationFailedException(UndertowLogger.ROOT_LOGGER.unableAddHandlerForPath(path)); } PathResourceManager resourceManager = new PathResourceManager(base, cacheBufferSize * cacheBuffers, caseSensitive, followSymlink, paths); ResourceHandler handler = new ResourceHandler(resourceManager); handler.setDirectoryListingEnabled(directoryListing); return handler; } }
6,548
48.992366
188
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/handlers/ReverseProxyHandlerDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.handlers; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.ResponseCodeHandler; import io.undertow.server.handlers.proxy.LoadBalancingProxyClient; import io.undertow.server.handlers.proxy.ProxyHandler; import io.undertow.util.Headers; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.Constants; import java.util.Collection; import java.util.List; /** * @author Stuart Douglas */ public class ReverseProxyHandlerDefinition extends HandlerDefinition { public static final PathElement PATH_ELEMENT =PathElement.pathElement(Constants.REVERSE_PROXY); public static final AttributeDefinition PROBLEM_SERVER_RETRY = new SimpleAttributeDefinitionBuilder(Constants.PROBLEM_SERVER_RETRY, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(30)) .setMeasurementUnit(MeasurementUnit.SECONDS) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition SESSION_COOKIE_NAMES = new SimpleAttributeDefinitionBuilder(Constants.SESSION_COOKIE_NAMES, ModelType.STRING) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode("JSESSIONID")) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition CONNECTIONS_PER_THREAD = new SimpleAttributeDefinitionBuilder(Constants.CONNECTIONS_PER_THREAD, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(40)) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition MAX_REQUEST_TIME = new SimpleAttributeDefinitionBuilder(Constants.MAX_REQUEST_TIME, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(-1)) .setMeasurementUnit(MeasurementUnit.MILLISECONDS) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition REQUEST_QUEUE_SIZE = new SimpleAttributeDefinitionBuilder(Constants.REQUEST_QUEUE_SIZE, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(10)) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition CACHED_CONNECTIONS_PER_THREAD = new SimpleAttributeDefinitionBuilder(Constants.CACHED_CONNECTIONS_PER_THREAD, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(5)) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition CONNECTION_IDLE_TIMEOUT = new SimpleAttributeDefinitionBuilder(Constants.CONNECTION_IDLE_TIMEOUT, ModelType.INT) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode(60000)) .setMeasurementUnit(MeasurementUnit.MILLISECONDS) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .build(); public static final AttributeDefinition MAX_RETRIES = new SimpleAttributeDefinitionBuilder(Constants.MAX_RETRIES, ModelType.INT) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setDefaultValue(new ModelNode(1L)) .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(CONNECTIONS_PER_THREAD, SESSION_COOKIE_NAMES, PROBLEM_SERVER_RETRY, REQUEST_QUEUE_SIZE, MAX_REQUEST_TIME, CACHED_CONNECTIONS_PER_THREAD, CONNECTION_IDLE_TIMEOUT, MAX_RETRIES); ReverseProxyHandlerDefinition() { super(PATH_ELEMENT, ReverseProxyHandlerDefinition::createHandler); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } @Override protected List<? extends PersistentResourceDefinition> getChildren() { return List.of(new ReverseProxyHandlerHostDefinition()); } static HttpHandler createHandler(final OperationContext context, ModelNode model) throws OperationFailedException { String sessionCookieNames = SESSION_COOKIE_NAMES.resolveModelAttribute(context, model).asString(); int connectionsPerThread = CONNECTIONS_PER_THREAD.resolveModelAttribute(context, model).asInt(); int problemServerRetry = PROBLEM_SERVER_RETRY.resolveModelAttribute(context, model).asInt(); int maxTime = MAX_REQUEST_TIME.resolveModelAttribute(context, model).asInt(); int requestQueueSize = REQUEST_QUEUE_SIZE.resolveModelAttribute(context, model).asInt(); int cachedConnectionsPerThread = CACHED_CONNECTIONS_PER_THREAD.resolveModelAttribute(context, model).asInt(); int connectionIdleTimeout = CONNECTION_IDLE_TIMEOUT.resolveModelAttribute(context, model).asInt(); int maxRetries = MAX_RETRIES.resolveModelAttribute(context, model).asInt(); final LoadBalancingProxyClient lb = new LoadBalancingProxyClient(exchange -> { //we always create a new connection for upgrade requests return exchange.getRequestHeaders().contains(Headers.UPGRADE); }) .setConnectionsPerThread(connectionsPerThread) .setMaxQueueSize(requestQueueSize) .setSoftMaxConnectionsPerThread(cachedConnectionsPerThread) .setTtl(connectionIdleTimeout) .setProblemServerRetry(problemServerRetry); String[] sessionIds = sessionCookieNames.split(","); for (String id : sessionIds) { lb.addSessionCookieName(id); } return ProxyHandler.builder() .setProxyClient(lb) .setMaxRequestTime(maxTime) .setNext(ResponseCodeHandler.HANDLE_404) .setRewriteHostHeader(false) .setReuseXForwarded(false) .setMaxConnectionRetries(maxRetries) .build(); } }
7,780
47.030864
252
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/handlers/HandlerService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.handlers; import java.util.Collections; import java.util.function.Consumer; import java.util.function.Supplier; import io.undertow.server.HttpHandler; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.requestcontroller.RequestController; import org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public final class HandlerService implements Service<HttpHandler> { private final Consumer<HttpHandler> httpHandlerConsumer; private final Supplier<RequestController> requestController; private final HttpHandler httpHandler; private volatile ControlPoint controlPoint; private volatile HttpHandler realHandler; private final String name; HandlerService(final Consumer<HttpHandler> httpHandlerConsumer, final Supplier<RequestController> requestController, HttpHandler httpHandler, final String name) { this.httpHandlerConsumer = httpHandlerConsumer; this.requestController = requestController; this.httpHandler = httpHandler; this.name = name; } @Override public void start(final StartContext context) { UndertowLogger.ROOT_LOGGER.tracef("starting handler: %s", httpHandler); if (requestController != null) { controlPoint = requestController.get().getControlPoint("org.wildfly.extension.undertow.handlers", name); realHandler = new GlobalRequestControllerHandler(httpHandler, controlPoint, Collections.emptyList()); } else { realHandler = httpHandler; } httpHandlerConsumer.accept(realHandler); } @Override public void stop(final StopContext context) { httpHandlerConsumer.accept(null); if (controlPoint != null) { requestController.get().removeControlPoint(controlPoint); controlPoint = null; } } @Override public HttpHandler getValue() throws IllegalStateException, IllegalArgumentException { return realHandler; } }
3,407
39.094118
116
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/handlers/ReverseProxyHandlerHostDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.handlers; import static org.wildfly.extension.undertow.Capabilities.REF_OUTBOUND_SOCKET; import static org.wildfly.extension.undertow.Capabilities.REF_SSL_CONTEXT; import static org.wildfly.extension.undertow.Capabilities.CAPABILITY_REVERSE_PROXY_HANDLER_HOST; import static org.wildfly.extension.undertow.logging.UndertowLogger.ROOT_LOGGER; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import javax.net.ssl.SSLContext; import io.undertow.UndertowOptions; import io.undertow.protocols.ssl.UndertowXnioSsl; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.proxy.LoadBalancingProxyClient; import io.undertow.server.handlers.proxy.ProxyHandler; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ServiceRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.capability.DynamicNameMappers; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.as.network.OutboundSocketBinding; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; import org.wildfly.extension.undertow.UndertowSubsystemModel; import org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler; import org.xnio.OptionMap; import org.xnio.Options; import org.xnio.Xnio; import org.xnio.ssl.XnioSsl; /** * @author Stuart Douglas * @author Tomaz Cerar * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class ReverseProxyHandlerHostDefinition extends PersistentResourceDefinition { public static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.HOST); private static final RuntimeCapability<Void> REVERSE_PROXY_HOST_RUNTIME_CAPABILITY = RuntimeCapability.Builder.of(CAPABILITY_REVERSE_PROXY_HANDLER_HOST, true, ReverseProxyHostService.class) .setDynamicNameMapper(DynamicNameMappers.PARENT) .build(); public static final SimpleAttributeDefinition OUTBOUND_SOCKET_BINDING = new SimpleAttributeDefinitionBuilder("outbound-socket-binding", ModelType.STRING) .setRequired(true) .setValidator(new StringLengthValidator(1, false)) .setAllowExpression(true) .setRestartAllServices() .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF) .setCapabilityReference(REF_OUTBOUND_SOCKET) .build(); public static final AttributeDefinition SCHEME = new SimpleAttributeDefinitionBuilder("scheme", ModelType.STRING) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode("http")) .setRestartAllServices() .build(); public static final AttributeDefinition PATH = new SimpleAttributeDefinitionBuilder("path", ModelType.STRING) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode("/")) .setRestartAllServices() .build(); public static final AttributeDefinition INSTANCE_ID = new SimpleAttributeDefinitionBuilder(Constants.INSTANCE_ID, ModelType.STRING) .setRequired(false) .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SSL_CONTEXT = new SimpleAttributeDefinitionBuilder(Constants.SSL_CONTEXT, ModelType.STRING, true) .setAlternatives(Constants.SECURITY_REALM) .setCapabilityReference(REF_SSL_CONTEXT) .setRestartAllServices() .setValidator(new StringLengthValidator(1)) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SSL_REF) .build(); public static final SimpleAttributeDefinition SECURITY_REALM = new SimpleAttributeDefinitionBuilder(Constants.SECURITY_REALM, ModelType.STRING) .setAlternatives(Constants.SSL_CONTEXT) .setRequired(false) .setRestartAllServices() .setValidator(new StringLengthValidator(1)) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SECURITY_REALM_REF) .setDeprecated(UndertowSubsystemModel.VERSION_12_0_0.getVersion()) .build(); public static final SimpleAttributeDefinition ENABLE_HTTP2 = new SimpleAttributeDefinitionBuilder(Constants.ENABLE_HTTP2, ModelType.BOOLEAN) .setRequired(false) .setDefaultValue(ModelNode.FALSE) .setRestartAllServices() .build(); public static final Collection<AttributeDefinition> ATTRIBUTES = List.of(OUTBOUND_SOCKET_BINDING, SCHEME, INSTANCE_ID, PATH, SSL_CONTEXT, SECURITY_REALM, ENABLE_HTTP2); ReverseProxyHandlerHostDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(Constants.HANDLER, Constants.REVERSE_PROXY, PATH_ELEMENT.getKey())) .setCapabilities(REVERSE_PROXY_HOST_RUNTIME_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); ReverseProxyHostAdd add = new ReverseProxyHostAdd(this.getAttributes()); registerAddOperation(resourceRegistration, add, OperationEntry.Flag.RESTART_RESOURCE_SERVICES); registerRemoveOperation(resourceRegistration, new ServiceRemoveStepHandler(add) { @Override protected ServiceName serviceName(String name, final PathAddress address) { return REVERSE_PROXY_HOST_RUNTIME_CAPABILITY.getCapabilityServiceName(address); } }, OperationEntry.Flag.RESTART_RESOURCE_SERVICES); } private static class ReverseProxyHostAdd extends AbstractAddStepHandler { public ReverseProxyHostAdd(Collection<AttributeDefinition> attributes) { super(attributes); } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final PathAddress address = context.getCurrentAddress(); final String proxyName = address.getElement(address.size() - 2).getValue(); final String socketBinding = OUTBOUND_SOCKET_BINDING.resolveModelAttribute(context, model).asString(); final String scheme = SCHEME.resolveModelAttribute(context, model).asString(); final String path = PATH.resolveModelAttribute(context, model).asString(); final boolean enableHttp2 = ENABLE_HTTP2.resolveModelAttribute(context, model).asBoolean(); final String jvmRoute; final ModelNode securityRealm = SECURITY_REALM.resolveModelAttribute(context, model); if (securityRealm.isDefined()) { throw ROOT_LOGGER.runtimeSecurityRealmUnsupported(); } final ModelNode sslContext = SSL_CONTEXT.resolveModelAttribute(context, model); if (model.hasDefined(Constants.INSTANCE_ID)) { jvmRoute = INSTANCE_ID.resolveModelAttribute(context, model).asString(); } else { jvmRoute = null; } final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(REVERSE_PROXY_HOST_RUNTIME_CAPABILITY); final Consumer<ReverseProxyHostService> serviceConsumer = sb.provides(REVERSE_PROXY_HOST_RUNTIME_CAPABILITY); final Supplier<HttpHandler> phSupplier = sb.requiresCapability(Capabilities.CAPABILITY_HANDLER, HttpHandler.class, proxyName); final Supplier<OutboundSocketBinding> sbSupplier = sb.requiresCapability(Capabilities.REF_OUTBOUND_SOCKET, OutboundSocketBinding.class, socketBinding); final Supplier<SSLContext> scSupplier = sslContext.isDefined() ? sb.requiresCapability(REF_SSL_CONTEXT, SSLContext.class, sslContext.asString()) : null; sb.setInstance(new ReverseProxyHostService(serviceConsumer, phSupplier, sbSupplier, scSupplier, scheme, jvmRoute, path, enableHttp2)); sb.install(); } } private static final class ReverseProxyHostService implements Service { private final Consumer<ReverseProxyHostService> serviceConsumer; private final Supplier<HttpHandler> proxyHandler; private final Supplier<OutboundSocketBinding> socketBinding; private final Supplier<SSLContext> sslContext; private final String instanceId; private final String scheme; private final String path; private final boolean enableHttp2; private ReverseProxyHostService(final Consumer<ReverseProxyHostService> serviceConsumer, final Supplier<HttpHandler> proxyHandler, final Supplier<OutboundSocketBinding> socketBinding, final Supplier<SSLContext> sslContext, String scheme, String instanceId, String path, boolean enableHttp2) { this.serviceConsumer = serviceConsumer; this.proxyHandler = proxyHandler; this.socketBinding = socketBinding; this.sslContext = sslContext; this.instanceId = instanceId; this.scheme = scheme; this.path = path; this.enableHttp2 = enableHttp2; } private URI getUri() throws URISyntaxException { OutboundSocketBinding binding = socketBinding.get(); return new URI(scheme, null, binding.getUnresolvedDestinationAddress(), binding.getDestinationPort(), path, null, null); } @Override public void start(final StartContext startContext) throws StartException { //todo: this is a bit of a hack, as the proxy handler may be wrapped by a request controller handler for graceful shutdown ProxyHandler proxyHandler = (ProxyHandler) (this.proxyHandler.get() instanceof GlobalRequestControllerHandler ? ((GlobalRequestControllerHandler)this.proxyHandler.get()).getNext() : this.proxyHandler.get()); final LoadBalancingProxyClient client = (LoadBalancingProxyClient) proxyHandler.getProxyClient(); try { SSLContext sslContext = this.sslContext != null ? this.sslContext.get() : null; if (sslContext == null) { client.addHost(getUri(), instanceId, null, OptionMap.create(UndertowOptions.ENABLE_HTTP2, enableHttp2)); } else { OptionMap.Builder builder = OptionMap.builder(); builder.set(Options.USE_DIRECT_BUFFERS, true); OptionMap combined = builder.getMap(); XnioSsl xnioSsl = new UndertowXnioSsl(Xnio.getInstance(), combined, sslContext); client.addHost(getUri(), instanceId, xnioSsl, OptionMap.create(UndertowOptions.ENABLE_HTTP2, enableHttp2)); } serviceConsumer.accept(this); } catch (URISyntaxException e) { throw new StartException(e); } } @Override public void stop(final StopContext stopContext) { serviceConsumer.accept(null); ProxyHandler proxyHandler = (ProxyHandler) (this.proxyHandler.get() instanceof GlobalRequestControllerHandler ? ((GlobalRequestControllerHandler)this.proxyHandler.get()).getNext() : this.proxyHandler.get()); final LoadBalancingProxyClient client = (LoadBalancingProxyClient) proxyHandler.getProxyClient(); try { client.removeHost(getUri()); } catch (URISyntaxException e) { throw new RuntimeException(e); //impossible } } } }
14,207
51.043956
219
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/handlers/HandlerDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.handlers; import java.util.List; import io.undertow.server.HttpHandler; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ServiceRemoveStepHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.access.constraint.SensitivityClassification; import org.jboss.as.controller.access.management.AccessConstraintDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; import org.wildfly.extension.undertow.UndertowService; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. */ abstract class HandlerDefinition extends PersistentResourceDefinition { static final RuntimeCapability<Void> CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_HANDLER, true, HttpHandler.class).build(); private final HandlerFactory factory; protected HandlerDefinition(PathElement path, HandlerFactory factory) { super(new SimpleResourceDefinition.Parameters(path, UndertowExtension.getResolver(Constants.HANDLER, path.getKey()))); this.factory = factory; } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { HandlerAdd add = new HandlerAdd(this.factory, this.getAttributes()); registerAddOperation(resourceRegistration, add, OperationEntry.Flag.RESTART_RESOURCE_SERVICES); registerRemoveOperation(resourceRegistration, new ServiceRemoveStepHandler(UndertowService.HANDLER, add), OperationEntry.Flag.RESTART_RESOURCE_SERVICES); } @Override public void registerCapabilities(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerCapability(CAPABILITY); } @Override public List<AccessConstraintDefinition> getAccessConstraints() { return List.of(new SensitiveTargetAccessConstraintDefinition(new SensitivityClassification(UndertowExtension.SUBSYSTEM_NAME, "undertow-handler", false, false, false))); } }
3,463
45.186667
176
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/handlers/HandlerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.handlers; import io.undertow.server.HttpHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; /** * Factory for creating {@link HttpHandler} implementations from a resource model * @author Paul Ferraro */ public interface HandlerFactory { HttpHandler createHandler(final OperationContext context, ModelNode model) throws OperationFailedException; }
1,515
38.894737
111
java
null
wildfly-main/rts/src/test/java/org/wildfly/extension/rts/RTSSubsystemTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.rts; import java.io.IOException; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; /** * @author <a href="mailto:[email protected]">Gytis Trikleris</a> */ public class RTSSubsystemTestCase extends AbstractSubsystemBaseTest { public RTSSubsystemTestCase() { super(RTSSubsystemExtension.SUBSYSTEM_NAME, new RTSSubsystemExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem.xml"); } @Override protected String getSubsystemXsdPath() throws Exception { return "schema/wildfly-rts_1_0.xsd"; } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.withCapabilities("org.wildfly.transactions.xa-resource-recovery-registry"); } }
1,937
35.566038
115
java
null
wildfly-main/rts/src/main/java/org/wildfly/extension/rts/RTSSubsystemDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.rts; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelType; import org.wildfly.extension.rts.configuration.Attribute; /** * * @author <a href="mailto:[email protected]">Gytis Trikleris</a> * */ public final class RTSSubsystemDefinition extends SimpleResourceDefinition { static final String XA_RESOURCE_RECOVERY_CAPABILITY = "org.wildfly.transactions.xa-resource-recovery-registry"; /** Private capability that currently just represents the existence of the subsystem */ public static final RuntimeCapability<Void> RTS_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.rts", false, Void.class) .addRequirements(XA_RESOURCE_RECOVERY_CAPABILITY) .build(); public static final RuntimeCapability<Void> RTS_COORDINATOR_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.rts.coordinator", false, Void.class) .addRequirements(XA_RESOURCE_RECOVERY_CAPABILITY) .build(); public static final RuntimeCapability<Void> RTS_PARTICIPANT_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.rts.participant", false, Void.class) .addRequirements(XA_RESOURCE_RECOVERY_CAPABILITY) .build(); public static final RuntimeCapability<Void> RTS_VOLATILE_PARTICIPANT_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.rts.volatile-participant", false, Void.class) .addRequirements(XA_RESOURCE_RECOVERY_CAPABILITY) .build(); protected static final SimpleAttributeDefinition SERVER = new SimpleAttributeDefinitionBuilder(Attribute.SERVER.getLocalName(), ModelType.STRING, true) .setAllowExpression(false) .setXmlName(Attribute.SERVER.getLocalName()) .setFlags(AttributeAccess.Flag.RESTART_JVM) .build(); protected static final SimpleAttributeDefinition HOST = new SimpleAttributeDefinitionBuilder(Attribute.HOST.getLocalName(), ModelType.STRING, true) .setAllowExpression(false) .setXmlName(Attribute.HOST.getLocalName()) .setFlags(AttributeAccess.Flag.RESTART_JVM) .build(); protected static final SimpleAttributeDefinition SOCKET_BINDING = new SimpleAttributeDefinitionBuilder(Attribute.SOCKET_BINDING.getLocalName(), ModelType.STRING, true) .setAllowExpression(false) .setXmlName(Attribute.SOCKET_BINDING.getLocalName()) .setFlags(AttributeAccess.Flag.RESTART_JVM) .build(); RTSSubsystemDefinition() { super(new Parameters(RTSSubsystemExtension.SUBSYSTEM_PATH, RTSSubsystemExtension.getResourceDescriptionResolver(null)) .setAddHandler(RTSSubsystemAdd.INSTANCE) .setRemoveHandler(RTSSubsystemRemove.INSTANCE) .setCapabilities(RTS_CAPABILITY) ); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadWriteAttribute(SERVER, null, new ReloadRequiredWriteAttributeHandler(SERVER)); resourceRegistration.registerReadWriteAttribute(HOST, null, new ReloadRequiredWriteAttributeHandler(HOST)); resourceRegistration.registerReadWriteAttribute(SOCKET_BINDING, null, new ReloadRequiredWriteAttributeHandler(SOCKET_BINDING)); } }
5,090
49.91
183
java
null
wildfly-main/rts/src/main/java/org/wildfly/extension/rts/RTSSubsystemExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.rts; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.msc.service.ServiceName; /** * * @author <a href="mailto:[email protected]">Gytis Trikleris</a> * */ public final class RTSSubsystemExtension implements Extension { /** * The name space used for the {@code substystem} element */ public static final String NAMESPACE = "urn:jboss:domain:rts:1.0"; /** * The name of our subsystem within the model. */ public static final String SUBSYSTEM_NAME = "rts"; public static final ServiceName RTS = ServiceName.JBOSS.append(SUBSYSTEM_NAME); public static final ServiceName COORDINATOR = RTS.append("coordinator"); public static final ServiceName PARTICIPANT = RTS.append("participant"); public static final ServiceName VOLATILE_PARTICIPANT = RTS.append("volatile-participant"); public static final ServiceName INBOUND_BRIDGE = RTS.append("inbound-bridge"); protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); private static final String RESOURCE_NAME = RTSSubsystemExtension.class.getPackage().getName() + ".LocalDescriptions"; private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 0, 0); /** * The parser used for parsing our subsystem */ private final RTSSubsystemParser parser = new RTSSubsystemParser(); static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String keyPrefix) { String prefix = SUBSYSTEM_NAME + (keyPrefix == null ? "" : "." + keyPrefix); return new StandardResourceDescriptionResolver(prefix, RESOURCE_NAME, RTSSubsystemExtension.class.getClassLoader(), true, false); } @Override public void initializeParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE, () -> parser); } @Override public void initialize(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new RTSSubsystemDefinition()); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); subsystem.registerXMLElementWriter(parser); } }
4,049
41.1875
132
java
null
wildfly-main/rts/src/main/java/org/wildfly/extension/rts/RTSSubsystemRemove.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.rts; import org.jboss.as.controller.AbstractRemoveStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; import org.wildfly.extension.rts.logging.RTSLogger; /** * * @author <a href="mailto:[email protected]">Gytis Trikleris</a> * */ final class RTSSubsystemRemove extends AbstractRemoveStepHandler { static final RTSSubsystemRemove INSTANCE = new RTSSubsystemRemove(); private RTSSubsystemRemove() { } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { RTSLogger.ROOT_LOGGER.trace("RTSSubsystemRemove.performRuntime"); context.removeService(RTSSubsystemExtension.COORDINATOR); context.removeService(RTSSubsystemExtension.PARTICIPANT); context.removeService(RTSSubsystemExtension.VOLATILE_PARTICIPANT); context.removeService(RTSSubsystemExtension.INBOUND_BRIDGE); } }
2,078
37.5
131
java
null
wildfly-main/rts/src/main/java/org/wildfly/extension/rts/RTSSubsystemParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.rts; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import java.util.EnumSet; import java.util.List; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.as.controller.persistence.SubsystemMarshallingContext; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLElementWriter; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.jboss.staxmapper.XMLExtendedStreamWriter; import org.wildfly.extension.rts.configuration.Attribute; import org.wildfly.extension.rts.configuration.Element; import org.wildfly.extension.rts.logging.RTSLogger; /** * The subsystem parser, which uses stax to read and write to and from xml * * @author <a href="mailto:[email protected]">Gytis Trikleris</a> * */ final class RTSSubsystemParser implements XMLStreamConstants, XMLElementReader<List<ModelNode>>, XMLElementWriter<SubsystemMarshallingContext> { @Override public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException { RTSLogger.ROOT_LOGGER.trace("RTSSubsystemParser.writeContent"); context.startSubsystemElement(RTSSubsystemExtension.NAMESPACE, false); ModelNode node = context.getModelNode(); writer.writeStartElement(Element.SERVLET.getLocalName()); RTSSubsystemDefinition.SERVER.marshallAsAttribute(node, writer); RTSSubsystemDefinition.HOST.marshallAsAttribute(node, writer); RTSSubsystemDefinition.SOCKET_BINDING.marshallAsAttribute(node, writer); writer.writeEndElement(); writer.writeEndElement(); } @Override public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException { RTSLogger.ROOT_LOGGER.trace("RTSSubsystemParser.readElement"); // no attributes if (reader.getAttributeCount() > 0) { throw ParseUtils.unexpectedAttribute(reader, 0); } final ModelNode subsystem = Util.getEmptyOperation(ADD, PathAddress.pathAddress(RTSSubsystemExtension.SUBSYSTEM_PATH).toModelNode()); list.add(subsystem); // elements final EnumSet<Element> encountered = EnumSet.noneOf(Element.class); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final Element element = Element.forName(reader.getLocalName()); if (!encountered.add(element)) { throw ParseUtils.unexpectedElement(reader); } if (element.equals(Element.SERVLET)) { parseServletElement(reader, subsystem); } else { throw ParseUtils.unexpectedElement(reader); } } } private void parseServletElement(XMLExtendedStreamReader reader, ModelNode subsystem) throws XMLStreamException { final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case SERVER: RTSSubsystemDefinition.SERVER.parseAndSetParameter(value, subsystem, reader); break; case HOST: RTSSubsystemDefinition.HOST.parseAndSetParameter(value, subsystem, reader); break; case SOCKET_BINDING: RTSSubsystemDefinition.SOCKET_BINDING.parseAndSetParameter(value, subsystem, reader); break; default: throw ParseUtils.unexpectedAttribute(reader, i); } } // Handle elements ParseUtils.requireNoContent(reader); } }
5,153
38.646154
141
java
null
wildfly-main/rts/src/main/java/org/wildfly/extension/rts/RTSSubsystemAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.rts; import static org.jboss.as.controller.resource.AbstractSocketBindingResourceDefinition.SOCKET_BINDING_CAPABILITY_NAME; import static org.wildfly.extension.rts.RTSSubsystemDefinition.RTS_COORDINATOR_CAPABILITY; import static org.wildfly.extension.rts.RTSSubsystemDefinition.RTS_PARTICIPANT_CAPABILITY; import static org.wildfly.extension.rts.RTSSubsystemDefinition.RTS_VOLATILE_PARTICIPANT_CAPABILITY; import static org.wildfly.extension.rts.RTSSubsystemDefinition.XA_RESOURCE_RECOVERY_CAPABILITY; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.network.SocketBinding; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.wildfly.extension.rts.configuration.Attribute; import org.wildfly.extension.rts.deployment.InboundBridgeDeploymentProcessor; import org.wildfly.extension.rts.logging.RTSLogger; import org.wildfly.extension.rts.service.CoordinatorService; import org.wildfly.extension.rts.service.InboundBridgeService; import org.wildfly.extension.rts.service.ParticipantService; import org.wildfly.extension.rts.service.VolatileParticipantService; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Host; import java.util.function.Supplier; /** * * @author <a href="mailto:[email protected]">Gytis Trikleris</a> * */ final class RTSSubsystemAdd extends AbstractBoottimeAddStepHandler { static final RTSSubsystemAdd INSTANCE = new RTSSubsystemAdd(); private RTSSubsystemAdd() { } @Override protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException { RTSLogger.ROOT_LOGGER.trace("RTSSubsystemAdd.populateModel"); RTSSubsystemDefinition.SERVER.validateAndSet(operation, model); RTSSubsystemDefinition.HOST.validateAndSet(operation, model); RTSSubsystemDefinition.SOCKET_BINDING.validateAndSet(operation, model); } @Override public void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { RTSLogger.ROOT_LOGGER.trace("RTSSubsystemAdd.performBoottime"); registerCoordinatorService(context, model); registerParticipantService(context, model); registerVolatileParticipantService(context, model); registerInboundBridgeService(context); registerDeploymentProcessors(context); } private void registerInboundBridgeService(final OperationContext context) { final InboundBridgeService inboundBridgeService = new InboundBridgeService(); final ServiceBuilder<InboundBridgeService> inboundBridgeServiceBuilder = context .getServiceTarget() .addService(RTSSubsystemExtension.INBOUND_BRIDGE, inboundBridgeService); inboundBridgeServiceBuilder.requires(context.getCapabilityServiceName(XA_RESOURCE_RECOVERY_CAPABILITY, null)); inboundBridgeServiceBuilder.requires(RTSSubsystemExtension.PARTICIPANT); inboundBridgeServiceBuilder .setInitialMode(ServiceController.Mode.ACTIVE) .install(); } private void registerCoordinatorService(final OperationContext context, final ModelNode model) { final String socketBindingName = model.get(Attribute.SOCKET_BINDING.getLocalName()).asString(); final String serverName = model.get(Attribute.SERVER.getLocalName()).asString(); final String hostName = model.get(Attribute.HOST.getLocalName()).asString(); final CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(RTS_COORDINATOR_CAPABILITY); Supplier<Host> hostSupplier = builder.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverName, hostName); Supplier<SocketBinding> socketBindingSupplier = builder.requiresCapability(SOCKET_BINDING_CAPABILITY_NAME, SocketBinding.class, socketBindingName); final CoordinatorService coordinatorService = new CoordinatorService(hostSupplier, socketBindingSupplier); builder.setInstance(coordinatorService) .addAliases(RTSSubsystemExtension.COORDINATOR) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); } private void registerParticipantService(final OperationContext context, final ModelNode model) { final String socketBindingName = model.get(Attribute.SOCKET_BINDING.getLocalName()).asString(); final String serverName = model.get(Attribute.SERVER.getLocalName()).asString(); final String hostName = model.get(Attribute.HOST.getLocalName()).asString(); final CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(RTS_PARTICIPANT_CAPABILITY); Supplier<Host> hostSupplier = builder.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverName, hostName); Supplier<SocketBinding> socketBindingSupplier = builder.requiresCapability(SOCKET_BINDING_CAPABILITY_NAME, SocketBinding.class, socketBindingName); final ParticipantService participantService = new ParticipantService(hostSupplier, socketBindingSupplier); builder.setInstance(participantService) .addAliases(RTSSubsystemExtension.PARTICIPANT) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); } private void registerVolatileParticipantService(final OperationContext context, final ModelNode model) { final String socketBindingName = model.get(Attribute.SOCKET_BINDING.getLocalName()).asString(); final String serverName = model.get(Attribute.SERVER.getLocalName()).asString(); final String hostName = model.get(Attribute.HOST.getLocalName()).asString(); final CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(RTS_VOLATILE_PARTICIPANT_CAPABILITY); Supplier<Host> hostSupplier = builder.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverName, hostName); Supplier<SocketBinding> socketBindingSupplier = builder.requiresCapability(SOCKET_BINDING_CAPABILITY_NAME, SocketBinding.class, socketBindingName); final VolatileParticipantService volatileParticipantService = new VolatileParticipantService(hostSupplier, socketBindingSupplier); builder.setInstance(volatileParticipantService) .addAliases(RTSSubsystemExtension.VOLATILE_PARTICIPANT) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); } private void registerDeploymentProcessors(final OperationContext context) { context.addStep(new AbstractDeploymentChainStep() { public void execute(final DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(RTSSubsystemExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_RTS_PROVIDERS, new InboundBridgeDeploymentProcessor()); } }, OperationContext.Stage.RUNTIME); } }
8,492
53.442308
155
java
null
wildfly-main/rts/src/main/java/org/wildfly/extension/rts/configuration/Element.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.rts.configuration; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:[email protected]">Gytis Trikleris</a> */ public enum Element { // must be first UNKNOWN(null), SERVLET("servlet"); private final String name; Element(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Element> MAP; static { final Map<String, Element> map = new HashMap<String, Element>(); for (Element element : values()) { final String name = element.getLocalName(); if (name != null) { map.put(name, element); } } MAP = map; } public static Element forName(String localName) { final Element element = MAP.get(localName); return element == null ? UNKNOWN : element; } }
2,038
28.985294
72
java
null
wildfly-main/rts/src/main/java/org/wildfly/extension/rts/configuration/Attribute.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.rts.configuration; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:[email protected]">Gytis Trikleris</a> */ public enum Attribute { UNKNOWN(null), SERVER("server"), HOST("host"), SOCKET_BINDING("socket-binding"); private final String name; Attribute(final String name) { this.name = name; } /** * Get the local name of this attribute. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Attribute> MAP; static { final Map<String, Attribute> map = new HashMap<String, Attribute>(); for (Attribute element : values()) { final String name = element.getLocalName(); if (name != null) map.put(name, element); } MAP = map; } public static Attribute forName(String localName) { final Attribute element = MAP.get(localName); return element == null ? UNKNOWN : element; } public String toString() { return getLocalName(); } }
2,153
28.916667
76
java