Example usage for javax.servlet DispatcherType REQUEST

List of usage examples for javax.servlet DispatcherType REQUEST

Introduction

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

Prototype

DispatcherType REQUEST

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

Click Source Link

Usage

From source file:org.pidster.tomcat.websocket.jmx.WebSocketJMXInitializer.java

@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {

    // Allows the path of the Servlet & Filter to be configurable
    // relative to the web application's own path
    String path = System.getProperty("org.pidster.tomcat.websocket.jmx.path", "/jmx");

    log.info("Registering " + WebSocketJMXResourceFilter.class.getName() + ", with paths: " + path);
    FilterRegistration.Dynamic freg = ctx.addFilter(WebSocketJMXResourceFilter.class.getSimpleName(),
            WebSocketJMXResourceFilter.class);
    freg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, path + "/*");
    freg.setInitParameter("path", path);

    String wspath = path + "/connect";

    log.info("Registering " + WebSocketJMXServlet.class.getName() + ", with path: " + wspath);
    ServletRegistration.Dynamic wreg = ctx.addServlet(WebSocketJMXServlet.class.getSimpleName(),
            WebSocketJMXServlet.class);
    wreg.addMapping(wspath);// w  ww. ja va 2  s .  c  o  m
    wreg.setInitParameter("path", path);

}

From source file:org.seedstack.seed.web.internal.DeploymentManagerFactory.java

private DeploymentInfo configureDeploymentInfo(String contextPath) {
    return Servlets.deployment().setClassLoader(UndertowLauncher.class.getClassLoader())
            .setDeploymentName("app.war").setContextPath(contextPath)
            .addFilter(new FilterInfo("guiceFilter", com.google.inject.servlet.GuiceFilter.class))
            .addFilterUrlMapping("guiceFilter", "/*", DispatcherType.REQUEST);
}

From source file:org.siphon.d2js.D2jsRunner.java

public String getServletPath(HttpServletRequest request) {
    // FORWARD,  INCLUDE,  REQUEST,  ASYNC,  ERROR
    if (request.getDispatcherType() == DispatcherType.REQUEST) {
        return request.getServletPath();
    } else if (request.getDispatcherType() == DispatcherType.INCLUDE) {
        return (String) request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);
    } else {//from  ww w . j av a2 s  .  co m
        return request.getServletPath(); // not sure
    }
}

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.j a  va2  s.com*/
    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.
 * /*from w w w.j  a  v  a  2 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;
}

From source file:pt.ua.scaleus.server.JettyServer.java

public static void main(String[] args) {

    int port = 80;
    String baseWebPath = "/scaleus";
    String database = "default";
    String data_import = "resources/";
    boolean hasDataImport = false;

    try {//from   w  w w  . j av  a  2s .c  o m
        Options options = new Options();
        options.addOption("p", "port", true, "Server port");
        options.addOption("d", "database", true, "Database name");
        options.addOption("i", "import", true, "Folder or file location to import");
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("p")) {
            String cmd_port = cmd.getOptionValue("p");
            port = Integer.parseInt(cmd_port);
        }
        if (cmd.hasOption("d") && cmd.hasOption("i")) {
            database = cmd.getOptionValue("d");
            data_import = cmd.getOptionValue("i");
            hasDataImport = true;
        }

    } catch (ParseException ex) {
        log.error("CommandLine parse error", ex);
    }

    Server server = new Server(port);

    // setup the web pages/scripts app
    final URL warUrl = JettyServer.class.getClassLoader().getResource(WEBAPPDIR);
    final String warUrlString = warUrl.toExternalForm();
    ServletContextHandler webpages = new ServletContextHandler();
    webpages.setContextPath(baseWebPath);
    webpages.setResourceBase(warUrlString);
    webpages.addServlet(DefaultServlet.class, "/");
    webpages.addFilter(AppFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    //API init parameters
    Map<String, String> apiInit = new HashMap<>();
    apiInit.put("jersey.config.server.provider.classnames",
            RESTService.class.getCanonicalName() + ";org.glassfish.jersey.media.multipart.MultiPartFeature");
    // for request filtering add also: ;org.glassfish.jersey.filter.LoggingFilter
    //Test init parameters
    //Map<String, String> testInit = new HashMap<>();
    //testInit.put("jersey.config.server.provider.classnames", TestService.class.getCanonicalName());

    Handler[] handlers = new Handler[] {
            JettyUtils.createServletHandler(ServletContainer.class, baseWebPath, "/api/*", apiInit)
                    .getHandler(), // API
            //JettyUtils.createServletHandler(ServletContainer.class, baseWebPath, "/test/*", testInit).getHandler(), 
            webpages, //Web static content
    };
    ((ServletContextHandler) handlers[0]).addFilter(AppFilter.class, "/api/*",
            EnumSet.of(DispatcherType.REQUEST));

    // register the handlers on the server
    ContextHandlerCollection contextHandlers = new ContextHandlerCollection();
    contextHandlers.setHandlers(handlers);
    server.setHandler(contextHandlers);

    try {
        Init.getAPI().getDataset(database);
        if (hasDataImport)
            Init.dataImport(database, data_import);
        server.start();
        log.info("Server started.");
        server.join();
    } catch (Exception e) {
        log.error("Server cannot start", e);
    } finally {
        if (server.isStarted())
            server.destroy();
    }
}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcherTest.java

@Test
public void testGetRoot() throws Exception {
    ServletTester tester = new ServletTester();
    tester.setContextPath("/");

    tester.addFilter(filterWithMapper("/app1/path", "/app1", "/module.webapp"), "/*",
            EnumSet.of(DispatcherType.REQUEST));
    tester.addServlet(DefaultServlet.class, "/*");
    tester.start();/* ww  w.j a va 2  s . c om*/

    HttpTester.Request req = HttpTester.newRequest();
    req.setMethod("GET");
    req.setHeader("HOST", "proxy.host");
    req.setURI("/app1/path");

    HttpTester.Response resp = HttpTester.parseResponse(tester.getResponses(req.generate()));
    assertEquals("Status code not 200!", 200, resp.getStatus());

    ResponseHelper rh = new ResponseHelper(resp.getContent());

    assertEquals("http://proxy.host/app1/path", rh.requestHeaders.get("X-Proxy-Original-Url"));
    assertEquals("/", rh.requestHeaders.get("X-Proxy-Original-Servlet-ContextPath"));
    assertEquals(moduleHostUri + "/module.webapp/path", rh.requestUrl);
}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcherTest.java

@Test
public void testGet() throws Exception {
    ServletTester tester = new ServletTester();
    tester.setContextPath("/webapp1");

    tester.addFilter(filterWithMapper("/app1/path", "/app1", "/module.webapp"), "/*",
            EnumSet.of(DispatcherType.REQUEST));
    tester.addServlet(DefaultServlet.class, "/*");
    tester.start();//from ww  w  . j av  a  2  s  .c  o  m

    HttpTester.Request req = HttpTester.newRequest();
    req.setMethod("GET");
    req.setHeader("HOST", "proxy.host");
    req.setURI("/webapp1/app1/path");

    HttpTester.Response resp = HttpTester.parseResponse(tester.getResponses(req.generate()));
    assertEquals("Status code not 200!", 200, resp.getStatus());

    ResponseHelper rh = new ResponseHelper(resp.getContent());

    assertEquals("http://proxy.host/webapp1/app1/path", rh.requestHeaders.get("X-Proxy-Original-Url"));
    assertEquals("/webapp1", rh.requestHeaders.get("X-Proxy-Original-Servlet-ContextPath"));
    assertEquals(moduleHostUri + "/module.webapp/path", rh.requestUrl);
}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcherTest.java

@Test
public void testGetAditionalHeaders() throws Exception {
    ServletTester tester = new ServletTester();
    tester.setContextPath("/webapp1");

    FilterHolder filterHolder = filterWithMapper("/app1/path", "/app1", "/module.webapp");
    ((ProxyFilter) filterHolder.getFilter()).setHeaderProvider(headerProvider);
    ImmutableMap<String, String> headers = ImmutableMap.of("X-Header1", "headerValue1");
    when(headerProvider.getHeaders(any(HttpServletRequest.class))).thenReturn(headers);

    tester.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    tester.addServlet(DefaultServlet.class, "/*");
    tester.start();/*from   w ww.  j  a  v  a 2  s.c  o m*/

    HttpTester.Request req = HttpTester.newRequest();
    req.setMethod("GET");
    req.setHeader("HOST", "proxy.host");
    req.setURI("/webapp1/app1/path");

    HttpTester.Response resp = HttpTester.parseResponse(tester.getResponses(req.generate()));
    assertEquals("Status code not 200!", 200, resp.getStatus());

    ResponseHelper rh = new ResponseHelper(resp.getContent());

    assertEquals("http://proxy.host/webapp1/app1/path", rh.requestHeaders.get("X-Proxy-Original-Url"));
    assertEquals("/webapp1", rh.requestHeaders.get("X-Proxy-Original-Servlet-ContextPath"));
    assertEquals("headerValue1", rh.requestHeaders.get("X-Header1"));
    assertEquals(moduleHostUri + "/module.webapp/path", rh.requestUrl);
}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcherTest.java

@Test
public void testPost() throws Exception {
    ServletTester tester = new ServletTester();
    tester.setContextPath("/webapp1");

    tester.addFilter(filterWithMapper("/app1/path", "/app1", "/module.webapp"), "/*",
            EnumSet.of(DispatcherType.REQUEST));
    tester.addServlet(DefaultServlet.class, "/*");
    tester.start();//from w ww  .  j av a 2 s  .  co m

    HttpTester.Request req = HttpTester.newRequest();
    req.setMethod("POST");
    req.setContent("This is some content!!");
    req.setHeader("HOST", "proxy.host");
    req.setURI("/webapp1/app1/path");

    HttpTester.Response resp = HttpTester.parseResponse(tester.getResponses(req.generate()));

    ResponseHelper rh = new ResponseHelper(resp.getContent());

    assertEquals("Unexpected X-Proxy-Original-Url", "http://proxy.host/webapp1/app1/path",
            rh.requestHeaders.get("X-Proxy-Original-Url"));
    assertEquals("Unexpected X-Proxy-Original-Servlet-ContextPath", "/webapp1",
            rh.requestHeaders.get("X-Proxy-Original-Servlet-ContextPath"));
    assertEquals("Unexpected Request URL", moduleHostUri + "/module.webapp/path", rh.requestUrl);
    assertEquals("This is some content!!", rh.requestContent);
}