Search in sources :

Example 6 with ErrorPage

use of io.undertow.servlet.api.ErrorPage in project runwar by cfmlprojects.

the class Server method startServer.

public synchronized void startServer(final ServerOptions options) throws Exception {
    serverOptions = (ServerOptionsImpl) options;
    LoggerFactory.init(serverOptions);
    serverState = ServerState.STARTING;
    if (serverOptions.getAction().equals("stop")) {
        Stop.stopServer(serverOptions, true);
    }
    serverName = serverOptions.getServerName();
    portNumber = serverOptions.getPortNumber();
    socketNumber = serverOptions.getSocketNumber();
    String cfengine = serverOptions.getCFEngineName();
    String processName = serverOptions.getProcessName();
    String contextPath = serverOptions.getContextPath();
    String host = serverOptions.getHost();
    File warFile = serverOptions.getWarFile();
    if (serverOptions.getStatusFile() != null) {
        statusFile = serverOptions.getStatusFile();
    }
    String warPath = serverOptions.getWarPath();
    char[] stoppassword = serverOptions.getStopPassword();
    boolean ignoreWelcomePages = false;
    boolean ignoreRestMappings = false;
    LOG.info("Starting RunWAR " + getVersion());
    // unset this so thing that reconfigure will find theirs
    System.setProperty("log4j.configuration", "");
    ensureJavaVersion();
    securityManager = new SecurityManager();
    if (serverOptions.isBackground()) {
        setServerState(ServerState.STARTING_BACKGROUND);
        // this will eventually system.exit();
        LaunchUtil.relaunchAsBackgroundProcess(serverOptions.setBackground(false), true);
        setServerState(ServerState.STARTED_BACKGROUND);
        // just in case
        Thread.sleep(200);
        System.exit(0);
    }
    // if the war is archived, unpack it to system temp
    if (warFile.exists() && !warFile.isDirectory()) {
        URL zipResource = warFile.toURI().toURL();
        String warDir = warFile.getName().toLowerCase().replace(".war", "");
        warFile = new File(warFile.getParentFile(), warDir);
        if (!warFile.exists()) {
            warFile.mkdir();
            LOG.debug("Exploding compressed WAR to " + warFile.getAbsolutePath());
            LaunchUtil.unzipResource(zipResource, warFile, false);
        } else {
            LOG.debug("Using already exploded WAR in " + warFile.getAbsolutePath());
        }
        warPath = warFile.getAbsolutePath();
        if (serverOptions.getWarFile().getAbsolutePath().equals(serverOptions.getCfmlDirs())) {
            serverOptions.setCfmlDirs(warFile.getAbsolutePath());
        }
    }
    if (!warFile.exists()) {
        throw new RuntimeException("war does not exist: " + warFile.getAbsolutePath());
    }
    File webinf = serverOptions.getWebInfDir();
    File webXmlFile = serverOptions.getWebXmlFile();
    String libDirs = serverOptions.getLibDirs();
    URL jarURL = serverOptions.getJarURL();
    // If this folder is a proper war, add its WEB-INF/lib folder to the passed libDirs
    if (warFile.isDirectory() && webXmlFile != null && webXmlFile.exists()) {
        if (libDirs == null) {
            libDirs = "";
        } else if (libDirs.length() > 0) {
            libDirs = libDirs + ",";
        }
        libDirs = libDirs + webinf.getAbsolutePath() + "/lib";
        LOG.info("Adding additional lib dir of: " + webinf.getAbsolutePath() + "/lib");
    }
    List<URL> cp = new ArrayList<URL>();
    // cp.add(Server.class.getProtectionDomain().getCodeSource().getLocation());
    if (libDirs != null)
        cp.addAll(getJarList(libDirs));
    if (jarURL != null)
        cp.add(jarURL);
    if (serverOptions.getMariaDB4jImportSQLFile() != null) {
        System.out.println("ADDN" + serverOptions.getMariaDB4jImportSQLFile().toURI().toURL());
        cp.add(serverOptions.getMariaDB4jImportSQLFile().toURI().toURL());
    }
    cp.addAll(getClassesList(new File(webinf, "/classes")));
    initClassLoader(cp);
    serverMode = Mode.WAR;
    if (!webinf.exists()) {
        serverMode = Mode.DEFAULT;
        if (getCFMLServletClass(cfengine) != null) {
            serverMode = Mode.SERVLET;
        }
    }
    LOG.debugf("Server Mode: %s", serverMode);
    sysOutTee = null;
    sysErrTee = null;
    String osName = System.getProperties().getProperty("os.name");
    String iconPNG = System.getProperty("cfml.server.trayicon");
    if (iconPNG != null && iconPNG.length() > 0) {
        serverOptions.setIconImage(iconPNG);
    }
    String dockIconPath = System.getProperty("cfml.server.dockicon");
    if (dockIconPath == null || dockIconPath.length() == 0) {
        dockIconPath = serverOptions.getIconImage();
    }
    if (osName != null && osName.startsWith("Mac OS X")) {
        Image dockIcon = Tray.getIconImage(dockIconPath);
        System.setProperty("com.apple.mrj.application.apple.menu.about.name", processName);
        System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("-Xdock:name", processName);
        try {
            Class<?> appClass = Class.forName("com.apple.eawt.Application");
            Method getAppMethod = appClass.getMethod("getApplication");
            Object appInstance = getAppMethod.invoke(null);
            Method dockMethod = appInstance.getClass().getMethod("setDockIconImage", java.awt.Image.class);
            dockMethod.invoke(appInstance, dockIcon);
        } catch (Exception e) {
            LOG.warn("error setting dock icon image", e);
        }
    }
    LOG.info(bar);
    LOG.info("Starting - port:" + portNumber + " stop-port:" + socketNumber + " warpath:" + warPath);
    LOG.info("context: " + contextPath + "  -  version: " + getVersion());
    String cfmlDirs = serverOptions.getCfmlDirs();
    if (cfmlDirs.length() > 0) {
        LOG.info("web-dirs: " + cfmlDirs);
    }
    LOG.info("Log Directory: " + serverOptions.getLogDir().getAbsolutePath());
    LOG.info(bar);
    addShutDownHook();
    portNumber = getPortOrErrorOut(portNumber, host);
    socketNumber = getPortOrErrorOut(socketNumber, host);
    LOG.info("Adding mariadb manager");
    mariadb4jManager = new MariaDB4jManager(_classLoader);
    if (serverOptions.getWelcomeFiles() != null && serverOptions.getWelcomeFiles().length > 0) {
        ignoreWelcomePages = true;
    } else {
        serverOptions.setWelcomeFiles(defaultWelcomeFiles);
    }
    if (serverOptions.getServletRestMappings() != null && serverOptions.getServletRestMappings().length > 0) {
        ignoreRestMappings = true;
    }
    LOG.debug("Transfer Min Size: " + serverOptions.getTransferMinSize());
    xnio = Xnio.getInstance("nio", Server.class.getClassLoader());
    worker = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, 8).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
    final DeploymentInfo servletBuilder = deployment().setContextPath(contextPath.equals("/") ? "" : contextPath).setTempDir(new File(System.getProperty("java.io.tmpdir"))).setDeploymentName(warPath).setServerName("WildFly / Undertow");
    // hack to prevent . being picked up as the system path (jacob.x.dll)
    if (System.getProperty("java.library.path") == null) {
        if (webXmlFile != null) {
            System.setProperty("java.library.path", getThisJarLocation().getPath() + ':' + new File(webXmlFile.getParentFile(), "lib").getPath());
        } else {
            System.setProperty("java.library.path", getThisJarLocation().getPath() + ':' + new File(warFile, "/WEB-INF/lib/").getPath());
        }
    } else {
        System.setProperty("java.library.path", getThisJarLocation().getPath() + System.getProperty("path.separator") + System.getProperty("java.library.path"));
    }
    LOG.trace("java.library.path:" + System.getProperty("java.library.path"));
    final SessionCookieConfig sessionConfig = new SessionCookieConfig();
    final SessionAttachmentHandler sessionAttachmentHandler = new SessionAttachmentHandler(new InMemorySessionManager("", 1, true), sessionConfig);
    configureServerResourceHandler(servletBuilder, sessionConfig, warFile, webinf, webXmlFile, cfmlDirs, cfengine, ignoreWelcomePages, ignoreRestMappings);
    if (cfengine.equals("adobe")) {
        String cfclassesDir = (String) servletBuilder.getServletContextAttributes().get("coldfusion.compiler.outputDir");
        if (cfclassesDir == null || cfclassesDir.startsWith("/WEB-INF")) {
            // TODO: figure out why adobe needs the absolute path, vs. /WEB-INF/cfclasses
            File cfclassesDirFile = new File(webinf, "/cfclasses");
            cfclassesDir = cfclassesDirFile.getAbsolutePath();
            LOG.debug("ADOBE - coldfusion.compiler.outputDir set to " + cfclassesDir);
            if (!cfclassesDirFile.exists()) {
                cfclassesDirFile.mkdir();
            }
            servletBuilder.addServletContextAttribute("coldfusion.compiler.outputDir", cfclassesDir);
        }
    }
    if (serverOptions.isEnableBasicAuth()) {
        securityManager.configureAuth(servletBuilder, serverOptions);
    }
    configureURLRewrite(servletBuilder, webinf);
    configurePathInfoFilter(servletBuilder);
    if (serverOptions.isCacheEnabled()) {
        addCacheHandler(servletBuilder);
    } else {
        LOG.debug("File cache is disabled");
    }
    if (serverOptions.isCustomHTTPStatusEnabled()) {
        servletBuilder.setSendCustomReasonPhraseOnError(true);
    }
    if (serverOptions.getErrorPages() != null) {
        for (Integer errorCode : serverOptions.getErrorPages().keySet()) {
            String location = serverOptions.getErrorPages().get(errorCode);
            if (errorCode == 1) {
                servletBuilder.addErrorPage(new ErrorPage(location));
                LOG.debug("Adding default error location: " + location);
            } else {
                servletBuilder.addErrorPage(new ErrorPage(location, errorCode));
                LOG.debug("Adding " + errorCode + " error code location: " + location);
            }
        }
    }
    // someday we may wanna listen for changes
    /*
        servletBuilder.getResourceManager().registerResourceChangeListener(new ResourceChangeListener() {
            @Override
            public void handleChanges(Collection<ResourceChangeEvent> changes) {
                for(ResourceChangeEvent change : changes) {
                    RunwarLogger.ROOT_LOGGER.info("CHANGE");
                    RunwarLogger.ROOT_LOGGER.info(change.getResource());
                    RunwarLogger.ROOT_LOGGER.info(change.getType().name());
                    manager.getDeployment().getServletPaths().invalidate();
                }
            }
        });
        */
    // this prevents us from having to use our own ResourceHandler (directory listing, welcome files, see below) and error handler for now
    servletBuilder.addServlet(new ServletInfo(io.undertow.servlet.handlers.ServletPathMatches.DEFAULT_SERVLET_NAME, DefaultServlet.class).addInitParam("directory-listing", Boolean.toString(serverOptions.isDirectoryListingEnabled())));
    // servletBuilder.setExceptionHandler(LoggingExceptionHandler.DEFAULT);
    List<?> welcomePages = servletBuilder.getWelcomePages();
    if (ignoreWelcomePages) {
        LOG.debug("Ignoring web.xml welcome file, so adding server options welcome files to deployment manager.");
        servletBuilder.addWelcomePages(serverOptions.getWelcomeFiles());
    } else if (welcomePages.size() == 0) {
        LOG.debug("No welcome pages set yet, so adding defaults to deployment manager.");
        servletBuilder.addWelcomePages(defaultWelcomeFiles);
    }
    LOG.info("welcome pages in deployment manager: " + servletBuilder.getWelcomePages());
    if (ignoreRestMappings) {
        LOG.info("Overriding web.xml rest mappings with " + Arrays.toString(serverOptions.getServletRestMappings()));
        Iterator<Entry<String, ServletInfo>> it = servletBuilder.getServlets().entrySet().iterator();
        while (it.hasNext()) {
            ServletInfo restServlet = it.next().getValue();
            LOG.trace("Checking servelet named: " + restServlet.getName() + "to see if it's a REST servlet.");
            if (restServlet.getName().toLowerCase().equals("restservlet") || restServlet.getName().toLowerCase().equals("cfrestservlet")) {
                for (String path : serverOptions.getServletRestMappings()) {
                    restServlet.addMapping(path);
                    LOG.info("Added rest mapping: " + path + " to " + restServlet.getName());
                }
            }
        }
    }
    // TODO: probably best to create a new worker for websockets, if we want fastness, but for now we share
    // TODO: add buffer pool size (maybe-- direct is best at 16k), enable/disable be good I reckon tho
    servletBuilder.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, new WebSocketDeploymentInfo().setBuffers(new DefaultByteBufferPool(true, 1024 * 16)).setWorker(worker));
    LOG.debug("Added websocket context");
    manager = defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    HttpHandler servletHandler = manager.start();
    LOG.debug("started servlet deployment manager");
    /*
        List welcomePages =  manager.getDeployment().getDeploymentInfo().getWelcomePages();
        CFMLResourceHandler resourceHandler = new CFMLResourceHandler(servletBuilder.getResourceManager(), servletHandler, welcomePages);
        resourceHandler.setDirectoryListingEnabled(directoryListingEnabled);
        PathHandler pathHandler = Handlers.path(Handlers.redirect(contextPath))
                .addPrefixPath(contextPath, resourceHandler);
        HttpHandler errPageHandler = new SimpleErrorPageHandler(pathHandler);
        Builder serverBuilder = Undertow.builder().addHttpListener(portNumber, host).setHandler(errPageHandler);
*/
    Builder serverBuilder = Undertow.builder();
    if (serverOptions.isEnableHTTP()) {
        serverBuilder.addHttpListener(portNumber, host);
    }
    if (serverOptions.isHTTP2Enabled()) {
        LOG.info("Enabling HTTP2 protocol");
        LaunchUtil.assertJavaVersion8();
        if (!serverOptions.isEnableSSL()) {
            LOG.warn("SSL is required for HTTP2.  Enabling default SSL server.");
            serverOptions.setEnableSSL(true);
        }
        serverOptions.setSSLPort(serverOptions.getSSLPort() + 1);
        serverBuilder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
    // serverBuilder.setSocketOption(Options.REUSE_ADDRESSES, true);
    }
    if (serverOptions.isEnableSSL()) {
        int sslPort = serverOptions.getSSLPort();
        serverOptions.setDirectBuffers(true);
        LOG.info("Enabling SSL protocol on port " + sslPort);
        try {
            if (serverOptions.getSSLCertificate() != null) {
                File certfile = serverOptions.getSSLCertificate();
                File keyfile = serverOptions.getSSLKey();
                char[] keypass = serverOptions.getSSLKeyPass();
                String[] sslAddCerts = serverOptions.getSSLAddCerts();
                sslContext = SSLUtil.createSSLContext(certfile, keyfile, keypass, sslAddCerts);
                if (keypass != null)
                    Arrays.fill(keypass, '*');
            } else {
                sslContext = SSLUtil.createSSLContext();
            }
            serverBuilder.addHttpsListener(sslPort, host, sslContext);
        } catch (Exception e) {
            LOG.error("Unable to start SSL:" + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
    if (serverOptions.isEnableAJP()) {
        LOG.info("Enabling AJP protocol on port " + serverOptions.getAJPPort());
        serverBuilder.addAjpListener(serverOptions.getAJPPort(), host);
    }
    if (serverOptions.getBufferSize() != 0) {
        LOG.info("Buffer Size: " + serverOptions.getBufferSize());
        serverBuilder.setBufferSize(serverOptions.getBufferSize());
    }
    if (serverOptions.getIoThreads() != 0) {
        LOG.info("IO Threads: " + serverOptions.getIoThreads());
        serverBuilder.setIoThreads(serverOptions.getIoThreads());
    }
    if (serverOptions.getWorkerThreads() != 0) {
        LOG.info("Worker threads: " + serverOptions.getWorkerThreads());
        serverBuilder.setWorkerThreads(serverOptions.getWorkerThreads());
    }
    LOG.info("Direct Buffers: " + serverOptions.isDirectBuffers());
    serverBuilder.setDirectBuffers(serverOptions.isDirectBuffers());
    final PathHandler pathHandler = new PathHandler(Handlers.redirect(contextPath)) {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            // sessionConfig.setSessionId(exchange, ""); // TODO: see if this suppresses jsessionid
            if (exchange.getRequestPath().endsWith(".svgz")) {
                exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, "gzip");
            }
            // clear any welcome-file info cached after initial request *NOT THREAD SAFE*
            if (serverOptions.isDirectoryListingRefreshEnabled() && exchange.getRequestPath().endsWith("/")) {
                // RunwarLogger.ROOT_LOGGER.trace("*** Resetting servlet path info");
                manager.getDeployment().getServletPaths().invalidate();
            }
            if (serverOptions.isDebug() && exchange.getRequestPath().endsWith("/dumprunwarrequest")) {
                new RequestDumper().handleRequest(exchange);
            } else {
                super.handleRequest(exchange);
            }
        }
    };
    pathHandler.addPrefixPath(contextPath, servletHandler);
    if (serverOptions.isSecureCookies()) {
        sessionConfig.setHttpOnly(true);
        sessionConfig.setSecure(true);
    }
    sessionAttachmentHandler.setNext(pathHandler);
    HttpHandler errPageHandler;
    if (serverOptions.isGzipEnabled()) {
        final EncodingHandler handler = new EncodingHandler(new ContentEncodingRepository().addEncodingHandler("gzip", new GzipEncodingProvider(), 50, Predicates.parse("max-content-size[5]"))).setNext(pathHandler);
        errPageHandler = new ErrorHandler(handler);
    } else {
        errPageHandler = new ErrorHandler(pathHandler);
    }
    if (serverOptions.logAccessEnable()) {
        // final String PATTERN = "cs-uri cs(test-header) x-O(aa) x-H(secure)";
        DefaultAccessLogReceiver accessLogReceiver = DefaultAccessLogReceiver.builder().setLogWriteExecutor(worker).setOutputDirectory(options.getLogAccessDir().toPath()).setLogBaseName(options.getLogAccessBaseFileName()).build();
        LOG.info("Logging combined access to " + options.getLogAccessDir());
        // errPageHandler = new AccessLogHandler(errPageHandler, logReceiver, PATTERN, new ExtendedAccessLogParser( Server.class.getClassLoader()).parse(PATTERN));
        // errPageHandler = new AccessLogHandler(errPageHandler, logReceiver,"common", Server.class.getClassLoader());
        errPageHandler = new AccessLogHandler(errPageHandler, accessLogReceiver, "combined", Server.class.getClassLoader());
    }
    if (serverOptions.logRequestsEnable()) {
        LOG.error("Request log output currently goes to server.log");
        LOG.debug("Enabling request dumper");
        DefaultAccessLogReceiver requestsLogReceiver = DefaultAccessLogReceiver.builder().setLogWriteExecutor(worker).setOutputDirectory(options.getLogRequestsDir().toPath()).setLogBaseName(options.getLogRequestsBaseFileName()).build();
        errPageHandler = new RequestDebugHandler(errPageHandler, requestsLogReceiver);
    }
    if (serverOptions.isProxyPeerAddressEnabled()) {
        LOG.debug("Enabling Proxy Peer Address handling");
        errPageHandler = new SSLHeaderHandler(new ProxyPeerAddressHandler(errPageHandler));
    }
    Undertow reverseProxy = null;
    if (serverOptions.isHTTP2Enabled()) {
        LOG.debug("Enabling HTTP2 Upgrade and LearningPushHandler");
        /**
         * To not be dependent on java9 or crazy requirements, we set up a proxy to enable http2, and swap it with the actual SSL server (thus the port++/port--)
         */
        errPageHandler = new Http2UpgradeHandler(errPageHandler);
        errPageHandler = Handlers.header(predicate(secure(), errPageHandler, new HttpHandler() {

            @Override
            public void handleRequest(HttpServerExchange exchange) throws Exception {
                exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (serverOptions.getSSLPort() - 1) + exchange.getRelativePath());
                exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
            }
        }), "x-undertow-transport", ExchangeAttributes.transportProtocol());
        errPageHandler = new SessionAttachmentHandler(new LearningPushHandler(100, -1, errPageHandler), new InMemorySessionManager("runwarsessions"), new SessionCookieConfig());
        LoadBalancingProxyClient proxy = new LoadBalancingProxyClient().addHost(new URI("https://localhost:" + serverOptions.getSSLPort()), null, new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, SSLUtil.createClientSSLContext()), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).setConnectionsPerThread(20);
        ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(proxy).setMaxRequestTime(30000).setNext(ResponseCodeHandler.HANDLE_404).build();
        reverseProxy = Undertow.builder().setServerOption(UndertowOptions.ENABLE_HTTP2, true).addHttpsListener(serverOptions.getSSLPort() - 1, serverOptions.getHost(), sslContext).setHandler(proxyHandler).build();
    }
    if (serverOptions.isEnableBasicAuth()) {
        securityManager.configureAuth(errPageHandler, serverBuilder, options);
    // serverBuilder.setHandler(errPageHandler);
    } else {
        serverBuilder.setHandler(errPageHandler);
    }
    try {
        PID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        String pidFile = serverOptions.getPidFile();
        if (pidFile != null && pidFile.length() > 0) {
            File file = new File(pidFile);
            file.deleteOnExit();
            PrintWriter writer = new PrintWriter(file);
            writer.print(PID);
            writer.close();
        }
    } catch (Exception e) {
        LOG.error("Unable to get PID:" + e.getMessage());
    }
    serverBuilder.setWorker(worker);
    undertow = serverBuilder.build();
    // start the stop monitor thread
    assert monitor == null;
    monitor = new MonitorThread(stoppassword);
    monitor.start();
    LOG.debug("started stop monitor");
    if (serverOptions.isTrayEnabled()) {
        try {
            Tray.hookTray(this);
            LOG.debug("hooked system tray");
        } catch (Throwable e) {
            LOG.error("system tray hook failed", e);
        }
    } else {
        LOG.debug("System tray integration disabled");
    }
    if (serverOptions.isOpenbrowser()) {
        LOG.debug("Starting open browser action");
        new Server(3);
    }
    // if this println changes be sure to update the LaunchUtil so it will know success
    String sslInfo = serverOptions.isEnableSSL() ? " https-port:" + serverOptions.getSSLPort() : "";
    String msg = "Server is up - http-port:" + portNumber + sslInfo + " stop-port:" + socketNumber + " PID:" + PID + " version " + getVersion();
    LOG.info(msg);
    System.out.println(msg);
    if (serverOptions.isTrayEnabled()) {
        LaunchUtil.displayMessage("info", msg);
    }
    setServerState(ServerState.STARTED);
    if (serverOptions.isMariaDB4jEnabled()) {
        try {
            mariadb4jManager.start(serverOptions.getMariaDB4jPort(), serverOptions.getMariaDB4jBaseDir(), serverOptions.getMariaDB4jDataDir(), serverOptions.getMariaDB4jImportSQLFile());
        } catch (Exception dbStartException) {
            LOG.error("Could not start MariaDB4j", dbStartException);
            System.out.println("Error starting MariaDB4j: " + dbStartException.getMessage());
        }
    }
    try {
        undertow.start();
        if (serverOptions.isHTTP2Enabled()) {
            LOG.debug("Starting HTTP2 proxy");
            reverseProxy.start();
        }
    } catch (Exception any) {
        if (any.getCause() instanceof java.net.SocketException && any.getCause().getMessage().equals("Permission denied")) {
            System.err.println("You need to be root or Administrator to bind to a port below 1024!");
        } else {
            any.printStackTrace();
        }
        System.exit(1);
    }
}
Also used : ErrorPage(io.undertow.servlet.api.ErrorPage) Builder(io.undertow.Undertow.Builder) ArrayList(java.util.ArrayList) PathHandler(io.undertow.server.handlers.PathHandler) DefaultAccessLogReceiver(io.undertow.server.handlers.accesslog.DefaultAccessLogReceiver) Image(java.awt.Image) LearningPushHandler(io.undertow.server.handlers.LearningPushHandler) ServletInfo(io.undertow.servlet.api.ServletInfo) ProxyPeerAddressHandler(io.undertow.server.handlers.ProxyPeerAddressHandler) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) HttpHandler(io.undertow.server.HttpHandler) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) ProxyHandler(io.undertow.server.handlers.proxy.ProxyHandler) SSLHeaderHandler(io.undertow.server.handlers.SSLHeaderHandler) Method(java.lang.reflect.Method) LoadBalancingProxyClient(io.undertow.server.handlers.proxy.LoadBalancingProxyClient) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) File(java.io.File) Undertow(io.undertow.Undertow) SecurityManager(runwar.security.SecurityManager) RequestDebugHandler(runwar.undertow.RequestDebugHandler) ContentEncodingRepository(io.undertow.server.handlers.encoding.ContentEncodingRepository) RequestDumper(runwar.util.RequestDumper) EncodingHandler(io.undertow.server.handlers.encoding.EncodingHandler) URI(java.net.URI) URL(java.net.URL) GzipEncodingProvider(io.undertow.server.handlers.encoding.GzipEncodingProvider) HttpServerExchange(io.undertow.server.HttpServerExchange) Entry(java.util.Map.Entry) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) PrintWriter(java.io.PrintWriter) MariaDB4jManager(runwar.mariadb4j.MariaDB4jManager) Http2UpgradeHandler(io.undertow.server.protocol.http2.Http2UpgradeHandler) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) AccessLogHandler(io.undertow.server.handlers.accesslog.AccessLogHandler) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler)

Example 7 with ErrorPage

use of io.undertow.servlet.api.ErrorPage in project undertow by undertow-io.

the class DeploymentManagerImpl method initializeErrorPages.

private void initializeErrorPages(final DeploymentImpl deployment, final DeploymentInfo deploymentInfo) {
    final Map<Integer, String> codes = new HashMap<>();
    final Map<Class<? extends Throwable>, String> exceptions = new HashMap<>();
    String defaultErrorPage = null;
    for (final ErrorPage page : deploymentInfo.getErrorPages()) {
        if (page.getExceptionType() != null) {
            exceptions.put(page.getExceptionType(), page.getLocation());
        } else if (page.getErrorCode() != null) {
            codes.put(page.getErrorCode(), page.getLocation());
        } else {
            if (defaultErrorPage != null) {
                throw UndertowServletMessages.MESSAGES.moreThanOneDefaultErrorPage(defaultErrorPage, page.getLocation());
            } else {
                defaultErrorPage = page.getLocation();
            }
        }
    }
    deployment.setErrorPages(new ErrorPages(codes, exceptions, defaultErrorPage));
}
Also used : ErrorPage(io.undertow.servlet.api.ErrorPage) HashMap(java.util.HashMap)

Example 8 with ErrorPage

use of io.undertow.servlet.api.ErrorPage in project keycloak by keycloak.

the class SimpleWebXmlParser method parseWebXml.

void parseWebXml(Document webXml, DeploymentInfo di) {
    try {
        DocumentWrapper document = new DocumentWrapper(webXml);
        if (di.getServlets().get("ResteasyServlet") == null) {
            // SERVLETS
            Map<String, String> servletMappings = new HashMap<>();
            List<ElementWrapper> sm = document.getElementsByTagName("servlet-mapping");
            for (ElementWrapper mapping : sm) {
                String servletName = mapping.getElementByTagName("servlet-name").getText();
                String path = mapping.getElementByTagName("url-pattern").getText();
                servletMappings.put(servletName, path);
            }
            List<ElementWrapper> servlets = document.getElementsByTagName("servlet");
            for (ElementWrapper servlet : servlets) {
                String servletName = servlet.getElementByTagName("servlet-name").getText();
                ElementWrapper servletClassEw = servlet.getElementByTagName("servlet-class");
                String servletClass = servletClassEw == null ? servletName : servletClassEw.getText();
                ElementWrapper loadOnStartupEw = servlet.getElementByTagName("load-on-startup");
                Integer loadOnStartup = loadOnStartupEw == null ? null : Integer.valueOf(loadOnStartupEw.getText());
                Class<? extends Servlet> servletClazz = (Class<? extends Servlet>) Class.forName(servletClass, false, di.getClassLoader());
                ServletInfo undertowServlet = new ServletInfo(servletName, servletClazz);
                if (servletMappings.containsKey(servletName)) {
                    undertowServlet.addMapping(servletMappings.get(servletName));
                    undertowServlet.setLoadOnStartup(loadOnStartup);
                    di.addServlet(undertowServlet);
                } else {
                    log.warnf("Missing servlet-mapping for '%s'", servletName);
                }
            }
        }
        // FILTERS
        Map<String, String> filterMappings = new HashMap<>();
        List<ElementWrapper> fm = document.getElementsByTagName("filter-mapping");
        for (ElementWrapper mapping : fm) {
            String filterName = mapping.getElementByTagName("filter-name").getText();
            String path = mapping.getElementByTagName("url-pattern").getText();
            filterMappings.put(filterName, path);
        }
        List<ElementWrapper> filters = document.getElementsByTagName("filter");
        for (ElementWrapper filter : filters) {
            String filterName = filter.getElementByTagName("filter-name").getText();
            String filterClass = filter.getElementByTagName("filter-class").getText();
            Class<? extends Filter> filterClazz = (Class<? extends Filter>) Class.forName(filterClass, false, di.getClassLoader());
            FilterInfo undertowFilter = new FilterInfo(filterName, filterClazz);
            List<ElementWrapper> initParams = filter.getElementsByTagName("init-param");
            for (ElementWrapper initParam : initParams) {
                String paramName = initParam.getElementByTagName("param-name").getText();
                String paramValue = initParam.getElementByTagName("param-value").getText();
                undertowFilter.addInitParam(paramName, paramValue);
            }
            di.addFilter(undertowFilter);
            if (filterMappings.containsKey(filterName)) {
                di.addFilterUrlMapping(filterName, filterMappings.get(filterName), DispatcherType.REQUEST);
            } else {
                log.warnf("Missing filter-mapping for '%s'", filterName);
            }
        }
        // CONTEXT PARAMS
        List<ElementWrapper> contextParams = document.getElementsByTagName("context-param");
        for (ElementWrapper param : contextParams) {
            String paramName = param.getElementByTagName("param-name").getText();
            String paramValue = param.getElementByTagName("param-value").getText();
            di.addInitParameter(paramName, paramValue);
        }
        // ROLES
        List<ElementWrapper> securityRoles = document.getElementsByTagName("security-role");
        for (ElementWrapper sr : securityRoles) {
            String roleName = sr.getElementByTagName("role-name").getText();
            di.addSecurityRole(roleName);
        }
        // SECURITY CONSTRAINTS
        List<ElementWrapper> secConstraints = document.getElementsByTagName("security-constraint");
        for (ElementWrapper constraint : secConstraints) {
            String urlPattern = constraint.getElementByTagName("web-resource-collection").getElementByTagName("url-pattern").getText();
            ElementWrapper authCsnt = constraint.getElementByTagName("auth-constraint");
            String roleName = authCsnt == null ? null : authCsnt.getElementByTagName("role-name").getText();
            SecurityConstraint undertowConstraint = new SecurityConstraint();
            WebResourceCollection collection = new WebResourceCollection();
            collection.addUrlPattern(urlPattern);
            undertowConstraint.addWebResourceCollection(collection);
            if (roleName != null) {
                undertowConstraint.addRoleAllowed(roleName);
            } else {
                undertowConstraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT);
            }
            di.addSecurityConstraint(undertowConstraint);
        }
        // LOGIN CONFIG
        ElementWrapper loginCfg = document.getElementByTagName("login-config");
        if (loginCfg != null) {
            String mech = loginCfg.getElementByTagName("auth-method").getText();
            String realmName = loginCfg.getElementByTagName("realm-name").getText();
            ElementWrapper form = loginCfg.getElementByTagName("form-login-config");
            if (form != null) {
                String loginPage = form.getElementByTagName("form-login-page").getText();
                String errorPage = form.getElementByTagName("form-error-page").getText();
                di.setLoginConfig(new LoginConfig(mech, realmName, loginPage, errorPage));
            } else {
                di.setLoginConfig(new LoginConfig(realmName).addFirstAuthMethod(mech));
            }
        }
        // COOKIE CONFIG
        ElementWrapper sessionCfg = document.getElementByTagName("session-config");
        if (sessionCfg != null) {
            ElementWrapper cookieConfig = sessionCfg.getElementByTagName("cookie-config");
            String cookieName = cookieConfig.getElementByTagName("name").getText();
            ServletSessionConfig cfg = new ServletSessionConfig();
            if (cookieConfig.getElementByTagName("http-only") != null) {
                cfg.setHttpOnly(Boolean.parseBoolean(cookieConfig.getElementByTagName("http-only").getText()));
            }
            cfg.setName(cookieName);
            di.setServletSessionConfig(cfg);
        }
        // ERROR PAGES
        List<ElementWrapper> errorPages = document.getElementsByTagName("error-page");
        for (ElementWrapper errorPageWrapper : errorPages) {
            String location = errorPageWrapper.getElementByTagName("location").getText();
            ErrorPage errorPage;
            if (errorPageWrapper.getElementByTagName("error-code") != null) {
                errorPage = new ErrorPage(location, Integer.parseInt(errorPageWrapper.getElementByTagName("error-code").getText()));
            } else {
                errorPage = new ErrorPage(location);
            }
            di.addErrorPage(errorPage);
        }
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    } catch (NullPointerException npe) {
        throw new RuntimeException("Error parsing web.xml of " + di.getDeploymentName(), npe);
    }
}
Also used : WebResourceCollection(io.undertow.servlet.api.WebResourceCollection) ErrorPage(io.undertow.servlet.api.ErrorPage) HashMap(java.util.HashMap) ServletSessionConfig(io.undertow.servlet.api.ServletSessionConfig) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) ServletInfo(io.undertow.servlet.api.ServletInfo) Filter(javax.servlet.Filter) LoginConfig(io.undertow.servlet.api.LoginConfig) Servlet(javax.servlet.Servlet) FilterInfo(io.undertow.servlet.api.FilterInfo)

Aggregations

ErrorPage (io.undertow.servlet.api.ErrorPage)8 ServletInfo (io.undertow.servlet.api.ServletInfo)7 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)4 FilterInfo (io.undertow.servlet.api.FilterInfo)4 HashMap (java.util.HashMap)4 PathHandler (io.undertow.server.handlers.PathHandler)3 ListenerInfo (io.undertow.servlet.api.ListenerInfo)3 LoginConfig (io.undertow.servlet.api.LoginConfig)3 MimeMapping (io.undertow.servlet.api.MimeMapping)3 SecurityConstraint (io.undertow.servlet.api.SecurityConstraint)3 HandlerWrapper (io.undertow.server.HandlerWrapper)2 HttpHandler (io.undertow.server.HttpHandler)2 ServletExtension (io.undertow.servlet.ServletExtension)2 DeploymentManager (io.undertow.servlet.api.DeploymentManager)2 ServletContainer (io.undertow.servlet.api.ServletContainer)2 ServletContainerInitializerInfo (io.undertow.servlet.api.ServletContainerInitializerInfo)2 WebResourceCollection (io.undertow.servlet.api.WebResourceCollection)2 WebSocketDeploymentInfo (io.undertow.websockets.jsr.WebSocketDeploymentInfo)2 File (java.io.File)2 IOException (java.io.IOException)2