org.eclipse.jetty.server.handler.ErrorHandler Java Examples

The following examples show how to use org.eclipse.jetty.server.handler.ErrorHandler. 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: JettyUtil.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
public static Server getJettyServer(List<ServletContextHandler> handlers, int port) {
  Server server = new Server(port);
  ErrorHandler errorHandler = new ErrorHandler();
  errorHandler.setShowStacks(true);
  errorHandler.setServer(server);
  server.addBean(errorHandler);

  ContextHandlerCollection collection = new ContextHandlerCollection();
  ServletContextHandler[] sch = new ServletContextHandler[handlers.size()];
  for (int i = 0; i < handlers.size(); i++) {
    sch[i] = handlers.get(i);
  }
  collection.setHandlers(sch);
  server.setHandler(collection);
  return server;
}
 
Example #2
Source File: DremioServer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
protected void addHandlers() {
  // root handler with request logging
  final RequestLogHandler rootHandler = new RequestLogHandler();
  embeddedJetty.insertHandler(rootHandler);
  RequestLogImpl_Jetty_Fix requestLogger = new RequestLogImpl_Jetty_Fix();
  requestLogger.setResource("/logback-access.xml");
  rootHandler.setRequestLog(requestLogger);

  // gzip handler.
  final GzipHandler gzipHandler = new GzipHandler();
  // gzip handler interferes with ChunkedOutput, so exclude the job download path
  gzipHandler.addExcludedPaths("/apiv2/job/*");
  rootHandler.setHandler(gzipHandler);

  // servlet handler for everything (to manage path mapping)
  servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  servletContextHandler.setContextPath("/");
  gzipHandler.setHandler(servletContextHandler);

  // error handler
  final ErrorHandler errorHandler = new ErrorHandler();
  errorHandler.setShowStacks(true);
  errorHandler.setShowMessageInTitle(true);
  embeddedJetty.setErrorHandler(errorHandler);
}
 
Example #3
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 #4
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 #5
Source File: JdbcBridge.java    From clickhouse-jdbc-bridge with Apache License 2.0 4 votes vote down vote up
@Override
@SneakyThrows
public void run() {
    log.info("Starting jdbc-bridge");

    JdbcDriverLoader.load(config.getDriverPath());

    BridgeConnectionManager manager = new BridgeConnectionManager();
    if (null != config.getConnectionFile()) {
        manager.load(config.getConnectionFile());
    }

    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(new ServletHolder(new QueryHandlerServlet(manager)), "/");
    handler.addServletWithMapping(new ServletHolder(new ColumnsInfoServlet(manager, new ClickHouseConverter())), "/columns_info");
    handler.addServletWithMapping(new ServletHolder(new IdentifierQuoteServlet(manager)), "/identifier_quote");
    handler.addServletWithMapping(new ServletHolder(new PingHandlerServlet()), "/ping");
    handler.addFilterWithMapping(RequestLogger.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    InetSocketAddress address = new InetSocketAddress(config.getListenHost(), config.getHttpPort());
    log.info("Will bind to {}", address);

    // this tricks are don in order to get good thread name in logs :(
    QueuedThreadPool pool = new QueuedThreadPool(1024, 10); // @todo make configurable?
    pool.setName("HTTP Handler");
    Server jettyServer = new Server(pool);
    ServerConnector connector = new ServerConnector(jettyServer);

    // @todo a temporary solution for dealing with too long URI for some endpoints
    HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setRequestHeaderSize(24 * 1024);
    HttpConnectionFactory factory = new HttpConnectionFactory(httpConfiguration);
    connector.setConnectionFactories(Collections.singleton(factory));

    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    jettyServer.setConnectors(new Connector[]{connector});

    jettyServer.setHandler(handler);
    jettyServer.setErrorHandler(new ErrorHandler() {
        @Override
        protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
            writer.write(message);
        }
    });

    try {
        log.info("Starting server");
        jettyServer.start();
        log.info("Server is ready to accept connections");
        jettyServer.join();
    } finally {
        jettyServer.destroy();
    }
}
 
Example #6
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 #7
Source File: SpringMvcJettyComponentTestServer.java    From backstopper with Apache License 2.0 4 votes vote down vote up
private static ErrorHandler generateErrorHandler() {
    ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
    errorHandler.addErrorPage(Throwable.class, "/error");
    return errorHandler;
}
 
Example #8
Source File: Main.java    From backstopper with Apache License 2.0 4 votes vote down vote up
private static ErrorHandler generateErrorHandler() {
    ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
    errorHandler.addErrorPage(Throwable.class, "/error");
    return errorHandler;
}
 
Example #9
Source File: SlackAppServer.java    From java-slack-sdk with MIT License 4 votes vote down vote up
public ErrorHandler getErrorHandler() {
    return errorHandler;
}
 
Example #10
Source File: SlackAppServer.java    From java-slack-sdk with MIT License 4 votes vote down vote up
public void setErrorHandler(ErrorHandler errorHandler) {
    this.errorHandler = errorHandler;
}
 
Example #11
Source File: WebContextWithExtraConfigurations.java    From logsniffer with GNU Lesser General Public License v3.0 4 votes vote down vote up
public WebContextWithExtraConfigurations(final SessionHandler sessionHandler, final SecurityHandler securityHandler,
		final ServletHandler servletHandler, final ErrorHandler errorHandler) {
	super(sessionHandler, securityHandler, servletHandler, errorHandler);
}
 
Example #12
Source File: AbstractJettyMixin.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public final void startJetty()
    throws Exception
{
    // Configure Server
    configureServer( server, configuration() );

    // Set up HTTP
    HttpConfiguration httpConfig = new HttpConfiguration();
    configureHttp( httpConfig, configuration() );
    httpConfig = specializeHttp( httpConfig );

    // Set up connector
    ServerConnector connector = buildConnector( server, httpConfig );
    configureConnector( connector, configuration() );

    // Bind Connector to Server
    server.addConnector( connector );
    if( mBeanServer != null )
    {
        server.addEventListener( new MBeanContainer( mBeanServer ) );
    }

    // Prepare ServletContext
    ServletContextHandler root = new ServletContextHandler( server,
                                                            "/",
                                                            new SessionHandler(),
                                                            buildSecurityHandler(),
                                                            new ServletHandler(),
                                                            new ErrorHandler() );
    root.setDisplayName( identity.toString() );
    configureContext( root, configuration() );

    // Register ContextListeners, Servlets and Filters
    addContextListeners( root, contextListeners );
    addServlets( root, servlets );
    addFilters( root, filters );

    // Start
    server.start();
}
 
Example #13
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.");
}
 
Example #14
Source File: JettyHttpTransport.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void initialiseStaticJettyConfig() throws Exception {
        server.initialiseConnectors();

        ErrorHandler errorHandler = new CougarErrorHandler();
        wsdlStaticHandler = new StaticContentServiceHandler(
                wsdlContextPath,
                wsdlRegex,
                wsdlMediaType,
                uuidHeader,
                uuidParentsHeader,
                deserializer,
                geoIPLocator,
                requestLogger,
                true);
        wsdlStaticHandler.setUnknownCipherKeyLength(unknownCipherKeyLength);

        htmlStaticHandler = new StaticContentServiceHandler(
                htmlContextPath,
                htmlRegex,
                htmlMediaType,
                uuidHeader,
                uuidParentsHeader,
                deserializer,
                geoIPLocator,
                requestLogger,
                suppressCommasInAccessLogForStaticHtml);
        htmlStaticHandler.setUnknownCipherKeyLength(unknownCipherKeyLength);

        StatisticsHandler statisticsHandler = new StatisticsHandler();
        statisticsHandler.setServer(server.getJettyServer());

        handlerCollection.setServer(server.getJettyServer());

        JettyHandler defaultJettyServiceHandler = new AliasHandler(defaultCommandProcessor, suppressCommasInAccessLogForCalls, pathAliases);
        ContextHandler context = new ContextHandler();
        context.setContextPath("");
        context.setResourceBase(".");
        context.setHandler(defaultJettyServiceHandler);
        handlerCollection.addHandler(context);

        handlerCollection.addHandler(wsdlStaticHandler);
        handlerCollection.addHandler(htmlStaticHandler);
//        handlerCollection.addHandler(aliasHandler);
        statisticsHandler.setHandler(handlerCollection);

        // Register the errorhandler with the server itself
        server.addBean(errorHandler);
        server.setHandler(statisticsHandler);
    }