Example usage for javax.servlet DispatcherType ASYNC

List of usage examples for javax.servlet DispatcherType ASYNC

Introduction

In this page you can find the example usage for javax.servlet DispatcherType ASYNC.

Prototype

DispatcherType ASYNC

To view the source code for javax.servlet DispatcherType ASYNC.

Click Source Link

Usage

From source file:com.jsmartframework.web.manager.ContextControl.java

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {//from w w  w.ja v a 2s  .  co m
        ServletContext servletContext = event.getServletContext();

        CONFIG.init(servletContext);
        if (CONFIG.getContent() == null) {
            throw new RuntimeException("Configuration file " + Constants.WEB_CONFIG_XML
                    + " was not found in WEB-INF resources folder!");
        }

        String contextConfigLocation = "com.jsmartframework.web.manager";
        if (CONFIG.getContent().getPackageScan() != null) {
            contextConfigLocation += "," + CONFIG.getContent().getPackageScan();
        }

        // Configure necessary parameters in the ServletContext to set Spring configuration without needing an XML file
        AnnotationConfigWebApplicationContext configWebAppContext = new AnnotationConfigWebApplicationContext();
        configWebAppContext.setConfigLocation(contextConfigLocation);

        CONTEXT_LOADER = new ContextLoader(configWebAppContext);
        CONTEXT_LOADER.initWebApplicationContext(servletContext);

        TagEncrypter.init();
        TEXTS.init();
        IMAGES.init(servletContext);
        HANDLER.init(servletContext);

        // ServletControl -> @MultipartConfig @WebServlet(name = "ServletControl", displayName = "ServletControl", loadOnStartup = 1)
        Servlet servletControl = servletContext.createServlet(
                (Class<? extends Servlet>) Class.forName("com.jsmartframework.web.manager.ServletControl"));
        ServletRegistration.Dynamic servletControlReg = (ServletRegistration.Dynamic) servletContext
                .addServlet("ServletControl", servletControl);
        servletControlReg.setAsyncSupported(true);
        servletControlReg.setLoadOnStartup(1);

        // ServletControl Initial Parameters
        InitParam[] initParams = CONFIG.getContent().getInitParams();
        if (initParams != null) {
            for (InitParam initParam : initParams) {
                servletControlReg.setInitParameter(initParam.getName(), initParam.getValue());
            }
        }

        // MultiPart to allow file upload on ServletControl
        MultipartConfigElement multipartElement = getServletMultipartElement();
        if (multipartElement != null) {
            servletControlReg.setMultipartConfig(multipartElement);
        }

        // Security constraint to ServletControl
        ServletSecurityElement servletSecurityElement = getServletSecurityElement(servletContext);
        if (servletSecurityElement != null) {
            servletControlReg.setServletSecurity(servletSecurityElement);
        }

        // TODO: Fix problem related to authentication by container to use SSL dynamically (Maybe create more than one servlet for secure and non-secure patterns)
        // Check also the use of request.login(user, pswd)
        // Check the HttpServletRequest.BASIC_AUTH, CLIENT_CERT_AUTH, FORM_AUTH, DIGEST_AUTH
        // servletReg.setRunAsRole("admin");
        // servletContext.declareRoles("admin");

        // ServletControl URL mapping
        String[] servletMapping = getServletMapping();
        servletControlReg.addMapping(servletMapping);

        // ErrorFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter errorFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.ErrorFilter"));
        FilterRegistration.Dynamic errorFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("ErrorFilter", errorFilter);

        errorFilterReg.setAsyncSupported(true);
        errorFilterReg.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR), true, "/*");

        // EncodeFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter encodeFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.EncodeFilter"));
        FilterRegistration.Dynamic encodeFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("EncodeFilter", encodeFilter);

        encodeFilterReg.setAsyncSupported(true);
        encodeFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // CacheFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter cacheFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.CacheFilter"));
        FilterRegistration.Dynamic cacheFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("CacheFilter", cacheFilter);

        cacheFilterReg.setAsyncSupported(true);
        cacheFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // Add custom filters defined by client
        for (String filterName : sortCustomFilters()) {
            Filter customFilter = servletContext
                    .createFilter((Class<? extends Filter>) HANDLER.webFilters.get(filterName));
            HANDLER.executeInjection(customFilter);

            WebFilter webFilter = customFilter.getClass().getAnnotation(WebFilter.class);
            FilterRegistration.Dynamic customFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter(filterName, customFilter);

            if (webFilter.initParams() != null) {
                for (WebInitParam initParam : webFilter.initParams()) {
                    customFilterReg.setInitParameter(initParam.name(), initParam.value());
                }
            }
            customFilterReg.setAsyncSupported(webFilter.asyncSupported());
            customFilterReg.addMappingForUrlPatterns(EnumSet.copyOf(Arrays.asList(webFilter.dispatcherTypes())),
                    true, webFilter.urlPatterns());
        }

        // FilterControl -> @WebFilter(servletNames = {"ServletControl"})
        Filter filterControl = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.FilterControl"));
        FilterRegistration.Dynamic filterControlReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("FilterControl", filterControl);

        filterControlReg.setAsyncSupported(true);
        filterControlReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // OutputFilter -> @WebFilter(servletNames = {"ServletControl"})
        Filter outputFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.OutputFilter"));
        FilterRegistration.Dynamic outputFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("OutputFilter", outputFilter);

        outputFilterReg.setAsyncSupported(true);
        outputFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // AsyncFilter -> @WebFilter(servletNames = {"ServletControl"})
        // Filter used case AsyncContext is dispatched internally by AsyncBean implementation
        Filter asyncFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.AsyncFilter"));
        FilterRegistration.Dynamic asyncFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("AsyncFilter", asyncFilter);

        asyncFilterReg.setAsyncSupported(true);
        asyncFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.ASYNC), true, "ServletControl");

        // SessionControl -> @WebListener
        EventListener sessionListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.SessionControl"));
        servletContext.addListener(sessionListener);

        // RequestControl -> @WebListener
        EventListener requestListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.RequestControl"));
        servletContext.addListener(requestListener);

        // Custom WebServlet -> Custom Servlets created by application
        for (String servletName : HANDLER.webServlets.keySet()) {
            Servlet customServlet = servletContext
                    .createServlet((Class<? extends Servlet>) HANDLER.webServlets.get(servletName));
            HANDLER.executeInjection(customServlet);

            WebServlet webServlet = customServlet.getClass().getAnnotation(WebServlet.class);
            ServletRegistration.Dynamic customReg = (ServletRegistration.Dynamic) servletContext
                    .addServlet(servletName, customServlet);

            customReg.setLoadOnStartup(webServlet.loadOnStartup());
            customReg.setAsyncSupported(webServlet.asyncSupported());

            WebInitParam[] customInitParams = webServlet.initParams();
            if (customInitParams != null) {
                for (WebInitParam customInitParam : customInitParams) {
                    customReg.setInitParameter(customInitParam.name(), customInitParam.value());
                }
            }

            // Add mapping url for custom servlet
            customReg.addMapping(webServlet.urlPatterns());

            if (customServlet.getClass().isAnnotationPresent(MultipartConfig.class)) {
                customReg.setMultipartConfig(new MultipartConfigElement(
                        customServlet.getClass().getAnnotation(MultipartConfig.class)));
            }
        }

        // Controller Dispatcher for Spring MVC
        Set<String> requestPaths = HANDLER.requestPaths.keySet();
        if (!requestPaths.isEmpty()) {
            ServletRegistration.Dynamic mvcDispatcherReg = servletContext.addServlet("DispatcherServlet",
                    new DispatcherServlet(configWebAppContext));
            mvcDispatcherReg.setLoadOnStartup(1);
            mvcDispatcherReg.addMapping(requestPaths.toArray(new String[requestPaths.size()]));

            // RequestPathFilter -> @WebFilter(servletNames = {"DispatcherServlet"})
            Filter requestPathFilter = servletContext.createFilter((Class<? extends Filter>) Class
                    .forName("com.jsmartframework.web.manager.RequestPathFilter"));
            FilterRegistration.Dynamic reqPathFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter("RequestPathFilter", requestPathFilter);

            reqPathFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST,
                    DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE, DispatcherType.ASYNC),
                    true, "DispatcherServlet");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.eclipse.gyrex.http.jetty.internal.app.ApplicationHandler.java

@Override
public void doScope(String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {

    /*/* ww  w .  jav a 2s  .co  m*/
     * IMPLEMENTATION NOTE
     *
     * This method is overridden to customize the path handling.
     *
     * Normally, a ContextHandler has a context path. However, the ApplicationHandler
     * must inherit the context path from the calling ApplicationHandlerCollection because
     * it changes depending on the incoming url.
     *
     * Additionally, class loader handling has been disabled in order to rely on the Equinox default.
     */

    // note, we do not support requests going through different contexts
    final ContextHandler.Context origContext = baseRequest.getContext();
    if ((origContext != null) && (origContext != _scontext))
        throw new IllegalStateException(
                "origContext != this context, nesting/cross-application routing not supported!");

    // backup paths
    final String origContextPath = baseRequest.getContextPath();
    final String origServletPath = baseRequest.getServletPath();
    final String origPathInfo = baseRequest.getPathInfo();

    // if the current context is not set, we need to set and restore
    final boolean newContext = (origContext == null) || (currentContextPath.get() == null);

    // set 'current' context path if not already set
    if (newContext) {
        // note, we rely on ApplicationHandlerCollection to pre-set the
        // correct context path on the request
        currentContextPath.set(baseRequest.getContextPath());
    }
    try {
        final String contextPath = currentContextPath.get();
        String pathInfo = null;

        final DispatcherType dispatch = baseRequest.getDispatcherType();

        // Are we already in this context?
        if (newContext) {
            // check the target
            if (DispatcherType.REQUEST.equals(dispatch) || DispatcherType.ASYNC.equals(dispatch)) {

                // perform checkContext to support unavailable status
                if (!checkContext(target, baseRequest, response))
                    return;

                // only accept requests coming through ApplicationHandlerCollection
                if (contextPath == null)
                    return;

                // calculate paths
                if (target.length() > contextPath.length()) {
                    if (contextPath.length() > 1) {
                        target = target.substring(contextPath.length());
                    }
                    pathInfo = target;
                } else if (contextPath.length() == 1) {
                    target = URIUtil.SLASH;
                    pathInfo = URIUtil.SLASH;
                } else {
                    // redirect null path infos in order to have context request end with /
                    baseRequest.setHandled(true);
                    if (baseRequest.getQueryString() != null) {
                        response.sendRedirect(URIUtil.addPaths(baseRequest.getRequestURI(), URIUtil.SLASH) + "?"
                                + baseRequest.getQueryString());
                    } else {
                        response.sendRedirect(URIUtil.addPaths(baseRequest.getRequestURI(), URIUtil.SLASH));
                    }
                    return;
                }
            }
        } else {
            // calculate paths for forwarded requests
            // (note, handle error dispatches like forwards for custom error handler support)
            if ((DispatcherType.FORWARD.equals(dispatch) || DispatcherType.ERROR.equals(dispatch))
                    && target.startsWith(URIUtil.SLASH)) {
                pathInfo = target;
            }
        }

        // update the paths
        baseRequest.setContext(_scontext);
        if (!DispatcherType.INCLUDE.equals(dispatch) && target.startsWith(URIUtil.SLASH)) {
            if (contextPath.length() == 1) {
                baseRequest.setContextPath(EMPTY_STRING);
            } else {
                baseRequest.setContextPath(contextPath);
            }
            baseRequest.setServletPath(null);
            baseRequest.setPathInfo(pathInfo);
        }

        // set application handler debug info reference
        if (showDebugInfo) {
            final StringBuilder dump = new StringBuilder();
            dump(dump);
            baseRequest.setAttribute(ATTRIBUTE_DEBUG_INFO, dump.toString());
        }

        // next scope
        // start manual inline of nextScope(target,baseRequest,request,response);
        if (never()) {
            nextScope(target, baseRequest, request, response);
        } else if (_nextScope != null) {
            _nextScope.doScope(target, baseRequest, request, response);
        } else if (_outerScope != null) {
            _outerScope.doHandle(target, baseRequest, request, response);
        } else {
            doHandle(target, baseRequest, request, response);
        } // end manual inline (pathetic attempt to reduce stack depth)
    } finally {
        if (newContext) {
            // reset the context and servlet path
            baseRequest.setContext(origContext);
            baseRequest.setContextPath(origContextPath);
            baseRequest.setServletPath(origServletPath);
            baseRequest.setPathInfo(origPathInfo);
            currentContextPath.set(null);
        }
    }

}

From source file:org.eclipse.gyrex.http.jetty.internal.app.ApplicationHandlerCollection.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // don't do anything if already processed
    if (response.isCommitted() || baseRequest.isHandled())
        return;/* w w  w . j  a  v a  2 s .c om*/

    final Iterator<Handler> handlers = this.handlers.iterator();
    if (!handlers.hasNext())
        return;

    final ThroughputMetric requestsMetric = metrics.getRequestsMetric();
    final long requestStart = requestsMetric.requestStarted();
    try {
        doHandle(target, baseRequest, request, response);
        if (response instanceof Response) {
            final int status = ((Response) response).getStatus();
            if (HttpStatus.isServerError(status)) {
                metrics.getRequestsMetric().requestFailed();
                metrics.error(status, ((Response) response).getReason());
            } else {
                metrics.getRequestsMetric().requestFinished(((Response) response).getContentCount(),
                        System.currentTimeMillis() - requestStart);
            }
        } else {
            metrics.getRequestsMetric().requestFinished(0, System.currentTimeMillis() - requestStart);
        }
    } catch (final EofException | RuntimeIOException | ContinuationThrowable e) {
        metrics.getRequestsMetric().requestFailed();
        throw e;
    } catch (final Exception e) {
        metrics.getRequestsMetric().requestFailed();

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type))) {
            if (e instanceof IOException)
                throw (IOException) e;
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            if (e instanceof ServletException)
                throw (ServletException) e;
        }

        // handle or log exception
        else if (e instanceof RuntimeIOException)
            throw (RuntimeIOException) e;
        else if (e instanceof EofException)
            throw (EofException) e;
        else if ((e instanceof IOException) || (e instanceof UnavailableException)
                || (e instanceof IllegalStateException)) {
            if (Platform.inDebugMode()) {
                LOG.debug("Exception processing request {}: {}", request.getRequestURI(),
                        ExceptionUtils.getMessage(e), e);
                LOG.debug(request.toString());
            }
        } else {
            LOG.error("Exception processing request {}: {}",
                    new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
            if (Platform.inDebugMode()) {
                LOG.debug(request.toString());
            }
        }

        // send error response if possible
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            if (e instanceof UnavailableException) {
                final UnavailableException ue = (UnavailableException) e;
                if (ue.isPermanent()) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
                } else {
                    response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
                }
            } else if (e instanceof IllegalStateException) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
        } else {
            // give up
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    } catch (final Error e) {
        metrics.getRequestsMetric().requestFailed();

        // only handle some errors
        if (!((e instanceof LinkageError) || (e instanceof AssertionError)))
            throw e;

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type)))
            throw e;

        LOG.error("Error processing request {}: {}",
                new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
        if (JettyDebug.debug) {
            LOG.debug(request.toString());
        }

        // TODO httpResponse.getHttpConnection().forceClose();
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } else {
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    }
}

From source file:org.springframework.http.server.reactive.ServletHttpHandlerAdapter.java

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    if (DispatcherType.ASYNC.equals(request.getDispatcherType())) {
        Throwable ex = (Throwable) request.getAttribute(WRITE_ERROR_ATTRIBUTE_NAME);
        throw new ServletException("Write publisher error", ex);
    }/*from   w ww. j a va  2 s  .  c o m*/

    // Start async before Read/WriteListener registration
    AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(-1);

    ServerHttpRequest httpRequest = createRequest(((HttpServletRequest) request), asyncContext);
    ServerHttpResponse httpResponse = createResponse(((HttpServletResponse) response), asyncContext);

    if (HttpMethod.HEAD.equals(httpRequest.getMethod())) {
        httpResponse = new HttpHeadResponseDecorator(httpResponse);
    }

    AtomicBoolean isCompleted = new AtomicBoolean();
    HandlerResultAsyncListener listener = new HandlerResultAsyncListener(isCompleted);
    asyncContext.addListener(listener);

    HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext, isCompleted);
    this.httpHandler.handle(httpRequest, httpResponse).subscribe(subscriber);
}

From source file:org.structr.rest.service.HttpService.java

@Override
public void initialize(final Services services, final StructrConf additionalConfig)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException {

    final StructrConf finalConfig = new StructrConf();

    // Default configuration
    finalConfig.setProperty(APPLICATION_TITLE, "structr server");
    finalConfig.setProperty(APPLICATION_HOST, "0.0.0.0");
    finalConfig.setProperty(APPLICATION_HTTP_PORT, "8082");
    finalConfig.setProperty(APPLICATION_HTTPS_ENABLED, "false");
    finalConfig.setProperty(APPLICATION_HTTPS_PORT, "8083");
    finalConfig.setProperty(ASYNC, "true");
    finalConfig.setProperty(SERVLETS, "JsonRestServlet");

    finalConfig.setProperty("JsonRestServlet.class", JsonRestServlet.class.getName());
    finalConfig.setProperty("JsonRestServlet.path", "/structr/rest/*");
    finalConfig.setProperty("JsonRestServlet.resourceprovider", DefaultResourceProvider.class.getName());
    finalConfig.setProperty("JsonRestServlet.authenticator", SuperUserAuthenticator.class.getName());
    finalConfig.setProperty("JsonRestServlet.user.class", "org.structr.dynamic.User");
    finalConfig.setProperty("JsonRestServlet.user.autocreate", "false");
    finalConfig.setProperty("JsonRestServlet.defaultview", PropertyView.Public);
    finalConfig.setProperty("JsonRestServlet.outputdepth", "3");

    Services.mergeConfiguration(finalConfig, additionalConfig);

    final String mainClassName = (String) finalConfig.get(MAIN_CLASS);

    Class mainClass = null;//from   w  w w . ja va2 s .  c o  m
    if (mainClassName != null) {

        logger.log(Level.INFO, "Running main class {0}", new Object[] { mainClassName });

        try {
            mainClass = Class.forName(mainClassName);
        } catch (ClassNotFoundException ex) {
            logger.log(Level.WARNING, "Did not find class for main class from config " + mainClassName, ex);
        }

    }

    String sourceJarName = (mainClass != null ? mainClass : getClass()).getProtectionDomain().getCodeSource()
            .getLocation().toString();
    final boolean isTest = Boolean.parseBoolean(finalConfig.getProperty(Services.TESTING, "false"));

    if (!isTest
            && StringUtils.stripEnd(sourceJarName, System.getProperty("file.separator")).endsWith("classes")) {

        String jarFile = System.getProperty("jarFile");
        if (StringUtils.isEmpty(jarFile)) {
            throw new IllegalArgumentException(getClass().getName()
                    + " was started in an environment where the classloader cannot determine the JAR file containing the main class.\n"
                    + "Please specify the path to the JAR file in the parameter -DjarFile.\n"
                    + "Example: -DjarFile=${project.build.directory}/${project.artifactId}-${project.version}.jar");
        }
        sourceJarName = jarFile;
    }

    // load configuration from properties file
    applicationName = finalConfig.getProperty(APPLICATION_TITLE);
    host = finalConfig.getProperty(APPLICATION_HOST);
    basePath = finalConfig.getProperty(Services.BASE_PATH);
    httpPort = Services.parseInt(finalConfig.getProperty(APPLICATION_HTTP_PORT), 8082);
    maxIdleTime = Services.parseInt(System.getProperty("maxIdleTime"), 30000);
    requestHeaderSize = Services.parseInt(System.getProperty("requestHeaderSize"), 8192);
    async = Services.parseBoolean(finalConfig.getProperty(ASYNC), true);

    if (async) {
        logger.log(Level.INFO, "Running in asynchronous mode");
    }

    // other properties
    final String keyStorePath = finalConfig.getProperty(APPLICATION_KEYSTORE_PATH);
    final String keyStorePassword = finalConfig.getProperty(APPLICATION_KEYSTORE_PASSWORD);
    final String contextPath = System.getProperty("contextPath", "/");
    final String logPrefix = "structr";
    final boolean enableRewriteFilter = true; // configurationFile.getProperty(Services.
    final boolean enableHttps = Services.parseBoolean(finalConfig.getProperty(APPLICATION_HTTPS_ENABLED),
            false);
    final boolean enableGzipCompression = true; //
    final boolean logRequests = false; //
    final int httpsPort = Services.parseInt(finalConfig.getProperty(APPLICATION_HTTPS_PORT), 8083);

    // get current base path
    basePath = System.getProperty("home", basePath);
    if (basePath.isEmpty()) {

        // use cwd and, if that fails, /tmp as a fallback
        basePath = System.getProperty("user.dir", "/tmp");
    }

    // create base directory if it does not exist
    final File baseDir = new File(basePath);
    if (!baseDir.exists()) {
        baseDir.mkdirs();
    }

    server = new Server(httpPort);
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.addHandler(new DefaultHandler());

    final ServletContextHandler servletContext = new ServletContextHandler(server, contextPath, true, true);
    final List<Connector> connectors = new LinkedList<>();

    // create resource collection from base path & source JAR
    try {
        servletContext.setBaseResource(new ResourceCollection(Resource.newResource(basePath),
                JarResource.newJarResource(Resource.newResource(sourceJarName))));

    } catch (Throwable t) {

        logger.log(Level.WARNING, "Base resource {0} not usable: {1}",
                new Object[] { basePath, t.getMessage() });
    }

    // this is needed for the filters to work on the root context "/"
    servletContext.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/");
    servletContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

    try {

        // CMIS setup
        servletContext.addEventListener(new CmisRepositoryContextListener());

        final ServletHolder cmisAtomHolder = servletContext.addServlet(CmisAtomPubServlet.class.getName(),
                "/structr/cmis/atom/*");
        cmisAtomHolder.setInitParameter("callContextHandler", BasicAuthCallContextHandler.class.getName());
        cmisAtomHolder.setInitParameter("cmisVersion", "1.1");

        final ServletHolder cmisBrowserHolder = servletContext
                .addServlet(CmisBrowserBindingServlet.class.getName(), "/structr/cmis/browser/*");
        cmisBrowserHolder.setInitParameter("callContextHandler", BasicAuthCallContextHandler.class.getName());
        cmisBrowserHolder.setInitParameter("cmisVersion", "1.1");

    } catch (Throwable t) {
        t.printStackTrace();
    }

    hashSessionManager = new HashSessionManager();
    try {
        hashSessionManager.setStoreDirectory(new File(baseDir + "/sessions"));
    } catch (IOException ex) {
        logger.log(Level.WARNING,
                "Could not set custom session manager with session store directory {0}/sessions", baseDir);
    }

    servletContext.getSessionHandler().setSessionManager(hashSessionManager);

    if (enableRewriteFilter) {

        final FilterHolder rewriteFilter = new FilterHolder(UrlRewriteFilter.class);
        rewriteFilter.setInitParameter("confPath", "urlrewrite.xml");
        servletContext.addFilter(rewriteFilter, "/*",
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));
    }

    if (enableGzipCompression) {

        final FilterHolder gzipFilter = async ? new FilterHolder(AsyncGzipFilter.class)
                : new FilterHolder(GzipFilter.class);
        gzipFilter.setInitParameter("mimeTypes",
                "text/html,text/plain,text/css,text/javascript,application/json");
        gzipFilter.setInitParameter("bufferSize", "32768");
        gzipFilter.setInitParameter("minGzipSize", "256");
        gzipFilter.setInitParameter("deflateCompressionLevel", "9");
        gzipFilter.setInitParameter("methods", "GET,POST,PUT,HEAD,DELETE");
        servletContext.addFilter(gzipFilter, "/*",
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));

    }

    contexts.addHandler(servletContext);

    // enable request logging
    if (logRequests || "true".equals(finalConfig.getProperty("log.requests", "false"))) {

        final String etcPath = basePath + "/etc";
        final File etcDir = new File(etcPath);

        if (!etcDir.exists()) {

            etcDir.mkdir();
        }

        final String logbackConfFilePath = basePath + "/etc/logback-access.xml";
        final File logbackConfFile = new File(logbackConfFilePath);

        if (!logbackConfFile.exists()) {

            // synthesize a logback accees log config file
            List<String> config = new LinkedList<>();

            config.add("<configuration>");
            config.add("  <appender name=\"FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">");
            config.add("    <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">");
            config.add("      <fileNamePattern>logs/" + logPrefix
                    + "-%d{yyyy_MM_dd}.request.log.zip</fileNamePattern>");
            config.add("    </rollingPolicy>");
            config.add("    <encoder>");
            config.add("      <charset>UTF-8</charset>");
            config.add("      <pattern>%h %l %u %t \"%r\" %s %b %n%fullRequest%n%n%fullResponse</pattern>");
            config.add("    </encoder>");
            config.add("  </appender>");
            config.add("  <appender-ref ref=\"FILE\" />");
            config.add("</configuration>");

            try {
                logbackConfFile.createNewFile();
                FileUtils.writeLines(logbackConfFile, "UTF-8", config);

            } catch (IOException ioex) {

                logger.log(Level.WARNING, "Unable to write logback configuration.", ioex);
            }
        }

        final FilterHolder loggingFilter = new FilterHolder(TeeFilter.class);
        servletContext.addFilter(loggingFilter, "/*",
                EnumSet.of(DispatcherType.REQUEST, async ? DispatcherType.ASYNC : DispatcherType.FORWARD));
        loggingFilter.setInitParameter("includes", "");

        final RequestLogHandler requestLogHandler = new RequestLogHandler();
        final String logPath = basePath + "/logs";
        final File logDir = new File(logPath);

        // Create logs directory if not existing
        if (!logDir.exists()) {

            logDir.mkdir();

        }

        final RequestLogImpl requestLog = new RequestLogImpl();
        requestLog.setName("REQUESTLOG");
        requestLogHandler.setRequestLog(requestLog);

        final HandlerCollection handlers = new HandlerCollection();

        handlers.setHandlers(new Handler[] { contexts, requestLogHandler });

        server.setHandler(handlers);

    } else {

        server.setHandler(contexts);

    }

    final List<ContextHandler> resourceHandler = collectResourceHandlers(finalConfig);
    for (ContextHandler contextHandler : resourceHandler) {
        contexts.addHandler(contextHandler);
    }

    final Map<String, ServletHolder> servlets = collectServlets(finalConfig);

    // add servlet elements
    int position = 1;
    for (Map.Entry<String, ServletHolder> servlet : servlets.entrySet()) {

        final ServletHolder servletHolder = servlet.getValue();
        final String path = servlet.getKey();

        servletHolder.setInitOrder(position++);

        logger.log(Level.INFO, "Adding servlet {0} for {1}", new Object[] { servletHolder, path });

        servletContext.addServlet(servletHolder, path);
    }

    contexts.addHandler(servletContext);

    if (host != null && !host.isEmpty() && httpPort > -1) {

        httpConfig = new HttpConfiguration();
        httpConfig.setSecureScheme("https");
        httpConfig.setSecurePort(httpsPort);
        //httpConfig.setOutputBufferSize(8192);
        httpConfig.setRequestHeaderSize(requestHeaderSize);

        final ServerConnector httpConnector = new ServerConnector(server,
                new HttpConnectionFactory(httpConfig));

        httpConnector.setHost(host);
        httpConnector.setPort(httpPort);

        connectors.add(httpConnector);

    } else {

        logger.log(Level.WARNING,
                "Unable to configure HTTP server port, please make sure that {0} and {1} are set correctly in structr.conf.",
                new Object[] { APPLICATION_HOST, APPLICATION_HTTP_PORT });
    }

    if (enableHttps) {

        if (httpsPort > -1 && keyStorePath != null && !keyStorePath.isEmpty() && keyStorePassword != null) {

            httpsConfig = new HttpConfiguration(httpConfig);
            httpsConfig.addCustomizer(new SecureRequestCustomizer());

            final SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStorePath(keyStorePath);
            sslContextFactory.setKeyStorePassword(keyStorePassword);

            final ServerConnector https = new ServerConnector(server,
                    new SslConnectionFactory(sslContextFactory, "http/1.1"),
                    new HttpConnectionFactory(httpsConfig));

            https.setPort(httpsPort);
            https.setIdleTimeout(500000);

            https.setHost(host);
            https.setPort(httpsPort);

            connectors.add(https);

        } else {

            logger.log(Level.WARNING,
                    "Unable to configure SSL, please make sure that {0}, {1} and {2} are set correctly in structr.conf.",
                    new Object[] { APPLICATION_HTTPS_PORT, APPLICATION_KEYSTORE_PATH,
                            APPLICATION_KEYSTORE_PASSWORD });
        }
    }

    if (!connectors.isEmpty()) {

        server.setConnectors(connectors.toArray(new Connector[0]));

    } else {

        logger.log(Level.SEVERE, "No connectors configured, aborting.");
        System.exit(0);
    }

    server.setStopTimeout(1000);
    server.setStopAtShutdown(true);
}