Java Code Examples for org.eclipse.jetty.servlet.ServletContextHandler#setErrorHandler()

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler#setErrorHandler() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PatchLogServer.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
/** Build a ServletContextHandler. */
private static ServletContextHandler buildServletContext(String contextPath) {
    if ( contextPath == null || contextPath.isEmpty() )
        contextPath = "/";
    else if ( !contextPath.startsWith("/") )
        contextPath = "/" + contextPath;
    ServletContextHandler context = new ServletContextHandler();
    context.setDisplayName("PatchLogServer");
    MimeTypes mt = new MimeTypes();
    addMimeType(mt, Lang.TTL);
    addMimeType(mt, Lang.NT);
    addMimeType(mt, Lang.TRIG);
    addMimeType(mt, Lang.NQ);
    addMimeType(mt, Lang.RDFXML);
    context.setMimeTypes(mt);
    ErrorHandler eh = new HttpErrorHandler();
    context.setErrorHandler(eh);
    return context;
}
 
Example 2
Source File: SpringMvcJettyComponentTestServer.java    From backstopper with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler generateServletContextHandler(WebApplicationContext context) {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setErrorHandler(generateErrorHandler());
    contextHandler.setContextPath("/");
    contextHandler.addServlet(new ServletHolder(generateDispatcherServlet(context)), "/*");
    contextHandler.addEventListener(new ContextLoaderListener(context));
    contextHandler.addFilter(
        ExplodingServletFilter.class, "/*", EnumSet.allOf(DispatcherType.class)
    );
    return contextHandler;
}
 
Example 3
Source File: Main.java    From backstopper with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler generateServletContextHandler(WebApplicationContext context) throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setErrorHandler(generateErrorHandler());
    contextHandler.setContextPath("/");
    contextHandler.addServlet(new ServletHolder(generateDispatcherServlet(context)), "/*");
    contextHandler.addEventListener(new ContextLoaderListener(context));
    contextHandler.addFilter(
        ExplodingFilter.class, "/*", EnumSet.allOf(DispatcherType.class)
    );
    return contextHandler;
}
 
Example 4
Source File: ErrorPageServletTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  TemplateHelper templateHelper = new TemplateHelperImpl(new ApplicationVersionSupport()
  {
    @Override
    public String getEdition() {
      return "Test";
    }
  }, new VelocityEngine());

  XFrameOptions xFrameOptions = new XFrameOptions(true);

  ServletContextHandler context = new ServletContextHandler();
  context.addServlet(new ServletHolder(new ErrorPageServlet(templateHelper, xFrameOptions)), "/error.html");
  context.addServlet(new ServletHolder(new BadServlet()), "/bad/*");

  ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
  errorHandler.addErrorPage(GLOBAL_ERROR_PAGE, "/error.html");
  context.setErrorHandler(errorHandler);

  BaseUrlHolder.set("http://127.0.0.1");

  server = new Server(0);
  server.setHandler(context);
  server.start();

  port = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
}
 
Example 5
Source File: HttpServer.java    From heroic with Apache License 2.0 5 votes vote down vote up
private HandlerCollection setupHandler() throws Exception {
    final ResourceConfig resourceConfig = setupResourceConfig();
    final ServletContainer servlet = new ServletContainer(resourceConfig);

    final ServletHolder jerseyServlet = new ServletHolder(servlet);
    // Initialize and register Jersey ServletContainer

    jerseyServlet.setInitOrder(1);

    // statically provide injector to jersey application.
    final ServletContextHandler context =
        new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");

    GzipHandler gzip = new GzipHandler();
    gzip.setIncludedMethods("POST");
    gzip.setMinGzipSize(860);
    gzip.setIncludedMimeTypes("application/json");
    context.setGzipHandler(gzip);

    context.addServlet(jerseyServlet, "/*");
    context.addFilter(new FilterHolder(new ShutdownFilter(stopping, mapper)), "/*", null);
    context.setErrorHandler(new JettyJSONErrorHandler(mapper));

    final RequestLogHandler requestLogHandler = new RequestLogHandler();

    requestLogHandler.setRequestLog(new Slf4jRequestLog());

    final RewriteHandler rewrite = new RewriteHandler();
    makeRewriteRules(rewrite);

    final HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{rewrite, context, requestLogHandler});

    return handlers;
}
 
Example 6
Source File: AbstractServerBootstrapper.java    From nem.deploy with MIT License 5 votes vote down vote up
private Handler createHandlers() {
	final ServletContextHandler servletContext = new ServletContextHandler();

	// Special Listener to set-up the environment for Spring
	servletContext.addEventListener(this.getCustomServletListener());
	servletContext.addEventListener(new ContextLoaderListener());
	servletContext.setErrorHandler(new JsonErrorHandler(CommonStarter.TIME_PROVIDER));

	final HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new org.eclipse.jetty.server.Handler[] { servletContext });
	return handlers;
}
 
Example 7
Source File: HttpTransportConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Bean
public ServletContextHandler servletContextHandler(){
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    return context;
}
 
Example 8
Source File: ChassisEurekaTestConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Order(0)
@Bean(initMethod="start", destroyMethod="stop")
public Server httpServer(
        @Value("${http.hostname}") String hostname,
        @Value("${http.port}") int port,
        ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(webApplicationContext);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[]{ connector });
    server.setHandler(servlets);

    return server;
}
 
Example 9
Source File: TestSpringWebApp.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "stop", name = "httpServer")
@Order(0)
public Server httpServer(ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[]{"/"});

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(webApplicationContext);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = new InetSocketAddress(SocketUtils.findAvailableTcpPort());

    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[]{connector});
    server.setHandler(servlets);
    server.setStopAtShutdown(true);

    return server;
}
 
Example 10
Source File: GitBridgeServer.java    From writelatex-git-bridge with MIT License 5 votes vote down vote up
private Handler initGitHandler(
        Config config,
        RepoStore repoStore,
        SnapshotApi snapshotApi
) throws ServletException {
    final ServletContextHandler servletContextHandler =
            new ServletContextHandler(ServletContextHandler.SESSIONS);
    if (config.isUsingOauth2()) {
        Filter filter = new Oauth2Filter(snapshotApi, config.getOauth2());
        servletContextHandler.addFilter(
                new FilterHolder(filter),
                "/*",
                EnumSet.of(DispatcherType.REQUEST)
        );
    }
    servletContextHandler.setContextPath("/");
    servletContextHandler.addServlet(
            new ServletHolder(
                    new WLGitServlet(
                            servletContextHandler,
                            repoStore,
                            bridge
                    )
            ),
            "/*"
    );
    ProductionErrorHandler errorHandler = new ProductionErrorHandler();
    servletContextHandler.setErrorHandler(errorHandler);
    return servletContextHandler;
}
 
Example 11
Source File: MetricsResourceMethodApplicationListenerIntegrationTest.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
@Override
protected void configurePostResourceHandling(ServletContextHandler context) {
  context.setErrorHandler(new ErrorHandler() {
    @Override
    public void handle(
        String target,
        Request baseRequest,
        HttpServletRequest request,
        HttpServletResponse response
    ) throws IOException, ServletException {
      handledException = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
      super.handle(target, baseRequest, request, response);
    }
  });
}
 
Example 12
Source File: InterAccountSNSPermissionTest.java    From spring-integration-aws with MIT License 5 votes vote down vote up
private ServletContextHandler getServletContextHandler() throws Exception {

		context = new XmlWebApplicationContext();
		context.setConfigLocation("src/main/webapp/WEB-INF/InterAccountSNSPermissionFlow.xml");
		context.registerShutdownHook();

		ServletContextHandler contextHandler = new ServletContextHandler();
		contextHandler.setErrorHandler(null);
		contextHandler.setResourceBase(".");
		ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(
				context));
		contextHandler.addServlet(servletHolder, "/*");

		return contextHandler;
	}
 
Example 13
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private Server createServer(Collection<HttpPort<?>> ports)
{
    LOGGER.debug("Starting up web server on {}", ports);

    _jettyServerExecutor = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory("Jetty-Server-Thread"));
    Server server = new Server(new ExecutorThreadPool(_jettyServerExecutor));
    int lastPort = -1;
    for (HttpPort<?> port : ports)
    {
        ServerConnector connector = createConnector(port, server);
        connector.addBean(new ConnectionTrackingListener());
        server.addConnector(connector);
        _portConnectorMap.put(port, connector);
        lastPort = port.getPort();
    }

    ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);
    root.setContextPath("/");
    root.setCompactPath(true);
    server.setHandler(root);

    final ErrorHandler errorHandler = new ErrorHandler()
    {
        @Override
        protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
                throws IOException
        {
            String uri= request.getRequestURI();

            writeErrorPageMessage(request,writer,code,message,uri);

            for (int i= 0; i < 20; i++)
                writer.write("<br/>                                                \n");
        }
    };
    root.setErrorHandler(errorHandler);

    // set servlet context attributes for broker and configuration
    root.getServletContext().setAttribute(HttpManagementUtil.ATTR_BROKER, getBroker());
    root.getServletContext().setAttribute(HttpManagementUtil.ATTR_MANAGEMENT_CONFIGURATION, this);

    root.addFilter(new FilterHolder(new ExceptionHandlingFilter()), "/*", EnumSet.allOf(DispatcherType.class));

    FilterHolder corsFilter = new FilterHolder(new CrossOriginFilter());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, getCorsAllowOrigins());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, Joiner.on(",").join(getCorsAllowMethods()));
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, getCorsAllowHeaders());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, String.valueOf(getCorsAllowCredentials()));
    root.addFilter(corsFilter, "/*", EnumSet.of(DispatcherType.REQUEST));

    root.addFilter(new FilterHolder(new ForbiddingTraceFilter()), "/*", EnumSet.of(DispatcherType.REQUEST));

    addFiltersAndServletsForRest(root);
    if (!Boolean.TRUE.equals(getContextValue(Boolean.class, DISABLE_UI_CONTEXT_NAME)))
    {
        addFiltersAndServletsForUserInterfaces(root);
    }

    root.getSessionHandler().getSessionCookieConfig().setName(JSESSIONID_COOKIE_PREFIX + lastPort);
    root.getSessionHandler().getSessionCookieConfig().setHttpOnly(true);
    root.getSessionHandler().setMaxInactiveInterval(getSessionTimeout());

    return server;
}
 
Example 14
Source File: PatchLogServer.java    From rdf-delta with Apache License 2.0 4 votes vote down vote up
PatchLogServer(String jettyConfig, int port, DeltaLink dLink) {
        DPS.init();

        // Either ... or ...
        this.jettyConfigFile = jettyConfig;

        if ( jettyConfigFile != null ) {
            server = jettyServer(jettyConfigFile);
            this.port = ((ServerConnector)server.getConnectors()[0]).getPort();
        } else {
            server = jettyServer(port, false);
            this.port = port;
        }

        this.deltaLink = dLink;
        ServletContextHandler handler = buildServletContext("/");

        HttpServlet servletRDFPatchLog = new S_Log(dLink);
        HttpServlet servletPing = new S_Ping();
        //HttpServlet servlet404 = new ServletHandler.Default404Servlet();

        // Filter - this catches RDF Patch Log requests.
        addFilter(handler, "/*", new F_PatchFilter(dLink,
                                                   (req, resp)->servletRDFPatchLog.service(req, resp),
                                                   (req, resp)->servletPing.service(req, resp)
                                                   ));

        // Other
        addServlet(handler, "/"+DeltaConst.EP_RPC, new S_DRPC(this.deltaLink));
        //addServlet(handler, "/restart", new S_Restart());

        addServlet(handler, "/"+DeltaConst.EP_Ping, new S_Ping());  //-- See also the "ping" DRPC.

        // Initial data. "/init-data?datasource=..."
        addServlet(handler, "/"+DeltaConst.EP_InitData, new S_Data(this.deltaLink));


        // ---- A default servlet at the end of the chain.
//        // -- Jetty default, including static content.
//        DefaultServlet servletContent = new DefaultServlet();
//        ServletHolder servletHolder = new ServletHolder(servletContent);
//        //servletHolder.setInitParameter("resourceBase", "somewhere");
//        handler.addServlet(servletHolder, "/*");

        // -- 404 catch all.
        HttpServlet servlet404 = new Servlet404();
        addServlet(handler, "/*", servlet404);
        // One line error message
        handler.setErrorHandler(new FusekiErrorHandler1());
        // Wire up.
        server.setHandler(handler);
    }
 
Example 15
Source File: AdminTransportConfiguration.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Bean(initMethod="start", destroyMethod="stop")
@Order(0)
public Server adminServer(
           @Value("${admin.hostname}") String hostname,
           @Value("${admin.port}") int port) {

       // set up servlets
       ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
	context.setErrorHandler(null);
	context.setWelcomeFiles(new String[] { "/" });
	
	// enable gzip
	context.addFilter(GzipFilter.class, "/*", null);
	
	// add common admin servlets
	context.addServlet(new ServletHolder(new HealthServlet(healthCheckRegistry)), "/healthcheck");
	context.addServlet(new ServletHolder(new ClasspathResourceServlet("com/kixeye/chassis/transport/admin", "/admin/", "index.html")), "/admin/*");
	context.addServlet(new ServletHolder(new PropertiesServlet()), "/admin/properties");
	context.addServlet(new ServletHolder(new ClasspathDumpServlet()), "/admin/classpath");

       // add websocket servlets if WebSockets have been initialized
       if (mappingRegistry != null && messageRegistry != null) {
           context.addServlet(new ServletHolder(new ProtobufMessagesDocumentationServlet(appName, mappingRegistry, messageRegistry)), "/schema/messages/protobuf");
           context.addServlet(new ServletHolder(new ProtobufEnvelopeDocumentationServlet()), "/schema/envelope/protobuf");
       }
	
       // add metric servlets if Metric has been initialized
       if (metricRegistry != null && healthCheckRegistry != null) {
           context.getServletContext().setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
           context.getServletContext().setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry);
           
           ServletHolder holder = new ServletHolder(new AdminServlet());
           holder.setInitParameter("service-name", System.getProperty("app.name"));
           context.addServlet(holder, "/metrics/*");
       }

       // create the server
   	InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
   	
   	Server server = new Server();

   	JettyConnectorRegistry.registerHttpConnector(server, address);
       server.setHandler(context);
   
	return server;
}
 
Example 16
Source File: GPhoto2Server.java    From gp2srv with GNU Lesser General Public License v3.0 4 votes vote down vote up
public GPhoto2Server(String contextPath, Integer port, final LogLevel logLevel, final boolean mockMode, final String[] requireAuthCredentials,
		String imageDldPath) {
	this.logger = makeLogger(logLevel);

	logger.info("Initializing...");

	try {
		if (contextPath == null) {
			contextPath = DEFAULT_CONTEXT_PATH;
		}
		if (port == null) {
			port = DEFAULT_PORT;
		}

		this.templateEngine = makeTemplateEngine();
		this.velocityContextService = new VelocityContextService();

		this.server = new Server(port);
		this.server.setStopAtShutdown(true);

		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		context.setContextPath(contextPath);
		userHome = new File(System.getProperty("user.home"));
		appHomeFolder = new File(userHome, ".gp2srv");
		appHomeFolder.mkdir();
		if (imageDldPath == null || imageDldPath.trim().isEmpty()) {
			imageDldPath = new File(userHome, "gp2srv_images").getAbsolutePath();
		}
		File imageDldFolder = new File(imageDldPath);
		System.out.println("Images download folder: " + imageDldFolder.getCanonicalPath());
		if (!imageDldFolder.exists()) {
			imageDldFolder.mkdirs();
		} else if (!imageDldFolder.isDirectory()) {
			throw new RuntimeException("Not a directory: " + imageDldFolder);
		}

		// imagesFolder = new File(appHomeFolder, "img");
		// imagesFolder.mkdirs();
		scriptsFolder = new File(appHomeFolder, "scripts");
		scriptsFolder.mkdirs();
		favouredCamConfSettingsFile = new File(appHomeFolder, "favouredConfs.properties");
		if (!favouredCamConfSettingsFile.exists()) {
			favouredCamConfSettingsFile.createNewFile();
		}
		favouredCamConfSettings = new FileBackedProperties(favouredCamConfSettingsFile);
		velocityContextService.getGlobalContext().put("favouredCamConfSettings", favouredCamConfSettings);

		context.setErrorHandler(new ErrorHandler() {
			private final AbstractErrorHandlingServlet eh = new AbstractErrorHandlingServlet(GPhoto2Server.this, GPhoto2Server.this.getLogger()) {
				private static final long serialVersionUID = -30520483617261093L;
			};

			@Override
			protected void handleErrorPage(final HttpServletRequest request, final Writer writer, final int code, final String message) {
				eh.serveGenericErrorPage(request, writer, code, message);
			}
		});

		if (requireAuthCredentials != null && requireAuthCredentials.length > 1 && requireAuthCredentials[0] != null && requireAuthCredentials[1] != null
				&& !requireAuthCredentials[0].trim().isEmpty() && !requireAuthCredentials[1].trim().isEmpty()) {
			context.addFilter(new FilterHolder(new BasicAuthFilter(requireAuthCredentials[0], requireAuthCredentials[1])), "/*",
					EnumSet.of(DispatcherType.REQUEST));
		}
		final CameraService cameraService = mockMode ? new MockCameraServiceImpl() : new CameraServiceImpl(this);
		final CameraProvider camProvider = cameraService.getCameraProvider();

		context.addFilter(new FilterHolder(new CameraChoiceFilter(camProvider, velocityContextService, this, logger)), "/*",
				EnumSet.of(DispatcherType.REQUEST));

		AtomicBoolean scriptDumpVars = new AtomicBoolean(true);
		scriptManagementService = new ScriptsManagementServiceImpl(scriptsFolder, logger);
		scriptExecService = new ScriptExecutionServiceImpl(logger);
		scriptExecWebSocketNotifier = new ScriptExecWebSocketNotifier(logger, scriptDumpVars);

		context.addServlet(new ServletHolder(new ScriptExecutionReportingWebSocketServlet(scriptExecService, logger)), "/scriptws");
		context.addServlet(new ServletHolder(new ScriptingServlet(cameraService, scriptManagementService, scriptExecService, scriptExecWebSocketNotifier,
				scriptDumpVars, velocityContextService, this, imageDldFolder, logger)), "/scripts/*");

		// context.addServlet(new ServletHolder(new ImagesServlet(this, imagesFolder, logger)), "/img/*");
		context.addServlet(new ServletHolder(new StaticsResourcesServlet(this, logger)), "/static/*");
		context.addServlet(
				new ServletHolder(new CameraControlServlet(cameraService, favouredCamConfSettings, velocityContextService, this, imageDldFolder, logger)),
				"/");
		context.addServlet(new ServletHolder(new DevModeServlet(this)), "/devmode/*");
		context.addServlet(new ServletHolder(new LiveViewServlet(cameraService)), "/stream.mjpeg");

		server.setHandler(context);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	logger.info("Initializing: done.");
}