List of usage examples for javax.servlet DispatcherType FORWARD
DispatcherType FORWARD
To view the source code for javax.servlet DispatcherType FORWARD.
Click Source Link
From source file:com.github.tomakehurst.wiremock.jetty9.JettyHttpServer.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private ServletContextHandler addMockServiceContext(StubRequestHandler stubRequestHandler, FileSource fileSource, Notifier notifier) { ServletContextHandler mockServiceContext = new ServletContextHandler(jettyServer, "/"); mockServiceContext.setInitParameter("org.eclipse.jetty.servlet.Default.maxCacheSize", "0"); mockServiceContext.setInitParameter("org.eclipse.jetty.servlet.Default.resourceBase", fileSource.getPath()); mockServiceContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false"); mockServiceContext.addServlet(DefaultServlet.class, FILES_URL_MATCH); mockServiceContext.setAttribute(JettyFaultInjectorFactory.class.getName(), new JettyFaultInjectorFactory()); mockServiceContext.setAttribute(StubRequestHandler.class.getName(), stubRequestHandler); mockServiceContext.setAttribute(Notifier.KEY, notifier); ServletHolder servletHolder = mockServiceContext.addServlet(WireMockHandlerDispatchingServlet.class, "/"); servletHolder.setInitParameter(RequestHandler.HANDLER_CLASS_KEY, StubRequestHandler.class.getName()); servletHolder.setInitParameter(FaultInjectorFactory.INJECTOR_CLASS_KEY, JettyFaultInjectorFactory.class.getName()); servletHolder.setInitParameter(WireMockHandlerDispatchingServlet.SHOULD_FORWARD_TO_FILES_CONTEXT, "true"); MimeTypes mimeTypes = new MimeTypes(); mimeTypes.addMimeMapping("json", "application/json"); mimeTypes.addMimeMapping("html", "text/html"); mimeTypes.addMimeMapping("xml", "application/xml"); mimeTypes.addMimeMapping("txt", "text/plain"); mockServiceContext.setMimeTypes(mimeTypes); mockServiceContext.setWelcomeFiles(new String[] { "index.json", "index.html", "index.xml", "index.txt" }); mockServiceContext.addFilter(GzipFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD)); mockServiceContext.addFilter(ContentTypeSettingFilter.class, FILES_URL_MATCH, EnumSet.of(DispatcherType.FORWARD)); mockServiceContext.addFilter(TrailingSlashFilter.class, FILES_URL_MATCH, EnumSet.allOf(DispatcherType.class)); return mockServiceContext; }
From source file:org.ireland.jnetty.webapp.WebApp.java
private void initConstructor() { _beanFactory = new BeanFactory(getClassLoader()); _servletManager = new ServletManager(this); _servletMapper = new ServletMapper(this, this, _servletManager); _filterManager = new FilterManager(this, this); _dispatchFilterMapper = new FilterMapper(this, _filterManager, DispatcherType.REQUEST); _includeFilterMapper = new FilterMapper(this, _filterManager, DispatcherType.INCLUDE); _forwardFilterMapper = new FilterMapper(this, _filterManager, DispatcherType.FORWARD); _errorFilterMapper = new FilterMapper(this, _filterManager, DispatcherType.ERROR); // _errorPageManager = new ErrorPageManager(_server, this); // Use JVM temp dir as ServletContext temp dir. _tempDir = System.getProperty(TEMPDIR); _sessionManager = new SessionManager(this); }
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 { /*/* w w w . j a v a 2 s . c o 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.italiangrid.voms.container.VOMSAppProvider.java
protected ContextHandler configureVOMSES() { String webappResourceDir = this.getClass().getClassLoader().getResource("status-webapp").toExternalForm(); WebAppContext statusContext = new WebAppContext(); statusContext.setContextPath("/"); statusContext.setResourceBase(webappResourceDir); statusContext.setCompactPath(true);// w ww .j a v a 2 s. c o m statusContext.setParentLoaderPriority(true); statusContext.setInitParameter("host", hostname); statusContext.setInitParameter("confdir", configurationDir); statusContext .setConnectorNames(new String[] { Container.HTTP_CONNECTOR_NAME, Container.HTTPS_CONNECTOR_NAME }); VOMSStatusFilter f = new VOMSStatusFilter(deploymentManager, hostname, port); FilterHolder fh = new FilterHolder(f); statusContext.addFilter(fh, "/*", EnumSet.of(DispatcherType.FORWARD, DispatcherType.REQUEST)); statusContext.setThrowUnavailableOnStartupException(true); statusContext.addLifeCycleListener(new VOMSESListener()); return statusContext; }
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 ww w. j a v a 2 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); }
From source file:org.structr.server.Structr.java
/** * Start the structr server with the previously specified configuration. * /* w w w .j av a2 s .c o m*/ * @throws IOException * @throws InterruptedException * @throws Exception */ public Server start(boolean waitForExit, boolean isTest) throws IOException, InterruptedException, Exception { String sourceJarName = app.getProtectionDomain().getCodeSource().getLocation().toString(); if (!isTest && StringUtils.stripEnd(sourceJarName, System.getProperty("file.separator")).endsWith("classes")) { String jarFile = System.getProperty("jarFile"); if (StringUtils.isEmpty(jarFile)) { throw new IllegalArgumentException(app.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; } // 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 File baseDir = new File(basePath); if (!baseDir.exists()) { baseDir.mkdirs(); } configuredServices.add(ModuleService.class); configuredServices.add(NodeService.class); configuredServices.add(AgentService.class); configuredServices.add(CronService.class); configuredServices.add(LogService.class); File confFile = checkStructrConf(basePath, sourceJarName); Properties configuration = getConfiguration(confFile); checkPrerequisites(configuration); Server server = new Server(restPort); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.addHandler(new DefaultHandler()); List<Connector> connectors = new LinkedList<Connector>(); ServletContextHandler servletContext = new ServletContextHandler(server, contextPath, true, true); // create resource collection from base path & source JAR servletContext.setBaseResource(new ResourceCollection(Resource.newResource(basePath), JarResource.newJarResource(Resource.newResource(sourceJarName)))); servletContext.setInitParameter("configfile.path", confFile.getAbsolutePath()); // 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"); if (enableGzipCompression) { FilterHolder gzipFilter = new FilterHolder(GzipFilter.class); gzipFilter.setInitParameter("mimeTypes", "text/html,text/plain,text/css,text/javascript"); servletContext.addFilter(gzipFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD)); } if (enableRewriteFilter) { FilterHolder rewriteFilter = new FilterHolder(UrlRewriteFilter.class); rewriteFilter.setInitParameter("confPath", "/urlrewrite.xml"); servletContext.addFilter(rewriteFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD)); } contexts.addHandler(servletContext); // enable request logging //if ("true".equals(configuration.getProperty("log.requests", "false"))) { if (logRequests) { String etcPath = basePath + "/etc"; File etcDir = new File(etcPath); if (!etcDir.exists()) { etcDir.mkdir(); } String logbackConfFilePath = basePath + "/etc/logback-access.xml"; File logbackConfFile = new File(logbackConfFilePath); if (!logbackConfFile.exists()) { // synthesize a logback accees log config file List<String> config = new LinkedList<String>(); 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>"); logbackConfFile.createNewFile(); FileUtils.writeLines(logbackConfFile, "UTF-8", config); } FilterHolder loggingFilter = new FilterHolder(TeeFilter.class); servletContext.addFilter(loggingFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD)); loggingFilter.setInitParameter("includes", ""); RequestLogHandler requestLogHandler = new RequestLogHandler(); String logPath = basePath + "/logs"; File logDir = new File(logPath); // Create logs directory if not existing if (!logDir.exists()) { logDir.mkdir(); } RequestLogImpl requestLog = new RequestLogImpl(); requestLogHandler.setRequestLog(requestLog); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); server.setHandler(handlers); } else { server.setHandler(contexts); } // add possible resource handler for static resources if (!resourceHandler.isEmpty()) { for (ContextHandler contextHandler : resourceHandler) { contexts.addHandler(contextHandler); } } //contexts.setHandlers(new Handler[] { new DefaultHandler(), contexts }); ResourceProvider resourceProviderInstance = resourceProvider.newInstance(); // configure JSON REST servlet JsonRestServlet structrRestServlet = new JsonRestServlet(resourceProviderInstance, defaultPropertyView, AbstractNode.uuid); ServletHolder structrRestServletHolder = new ServletHolder(structrRestServlet); servletParams.put("PropertyFormat", "FlatNameValue"); servletParams.put("Authenticator", authenticator.getName()); structrRestServletHolder.setInitParameters(servletParams); structrRestServletHolder.setInitOrder(0); // add to servlets servlets.put(restUrl + "/*", structrRestServletHolder); // add servlet elements int position = 1; for (Entry<String, ServletHolder> servlet : servlets.entrySet()) { String path = servlet.getKey(); ServletHolder servletHolder = servlet.getValue(); servletHolder.setInitOrder(position++); logger.log(Level.INFO, "Adding servlet {0} for {1}", new Object[] { servletHolder, path }); servletContext.addServlet(servletHolder, path); } // register structr application context listener servletContext.addEventListener(new ApplicationContextListener()); contexts.addHandler(servletContext); //server.setHandler(contexts); // HTTPs can be disabled if (enableHttps) { if (httpsPort > -1 && keyStorePath != null && !keyStorePath.isEmpty() && keyStorePassword != null) { // setup HTTP connector SslSelectChannelConnector httpsConnector = null; SslContextFactory factory = new SslContextFactory(keyStorePath); factory.setKeyStorePassword(keyStorePassword); httpsConnector = new SslSelectChannelConnector(factory); httpsConnector.setHost(host); httpsConnector.setPort(httpsPort); httpsConnector.setMaxIdleTime(maxIdleTime); httpsConnector.setRequestHeaderSize(requestHeaderSize); connectors.add(httpsConnector); } else { logger.log(Level.WARNING, "Unable to configure SSL, please make sure that application.https.port, application.keystore.path and application.keystore.password are set correctly in structr.conf."); } } if (host != null && !host.isEmpty() && restPort > -1) { SelectChannelConnector httpConnector = new SelectChannelConnector(); httpConnector.setHost(host); httpConnector.setPort(restPort); httpConnector.setMaxIdleTime(maxIdleTime); httpConnector.setRequestHeaderSize(requestHeaderSize); connectors.add(httpConnector); } else { logger.log(Level.WARNING, "Unable to configure REST port, please make sure that application.host, application.rest.port and application.rest.path are set correctly in structr.conf."); } if (!connectors.isEmpty()) { server.setConnectors(connectors.toArray(new Connector[0])); } else { logger.log(Level.SEVERE, "No connectors configured, aborting."); System.exit(0); } server.setGracefulShutdown(1000); server.setStopAtShutdown(true); if (!quiet) { System.out.println(); System.out.println("Starting " + applicationName + " (host=" + host + ":" + restPort + ", maxIdleTime=" + maxIdleTime + ", requestHeaderSize=" + requestHeaderSize + ")"); System.out.println("Base path " + basePath); System.out.println(); System.out.println(applicationName + " started: http://" + host + ":" + restPort + restUrl); System.out.println(); } server.start(); // The jsp directory is created by the container, but we don't need it removeDir(basePath, "jsp"); if (!callbacks.isEmpty()) { for (Callback callback : callbacks) { callback.execute(); } } if (waitForExit) { server.join(); if (!quiet) { System.out.println(); System.out.println(applicationName + " stopped."); System.out.println(); } } return server; }