Java Code Examples for org.eclipse.jetty.server.handler.HandlerCollection#addHandler()

The following examples show how to use org.eclipse.jetty.server.handler.HandlerCollection#addHandler() . 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: ApplicationServer.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
private void finalizeHandlerCollection(HandlerCollection handlers, HandlerCollection wsHandlers) {
  /* DefaultHandler must come last eo ensure all contexts
   * have a chance to handle a request first */
  handlers.addHandler(new DefaultHandler());
  /* Needed for graceful shutdown as per `setStopTimeout` documentation */
  StatisticsHandler statsHandler = new StatisticsHandler();
  statsHandler.setHandler(handlers);

  ContextHandlerCollection contexts = new ContextHandlerCollection();
  contexts.setHandlers(new Handler[]{
      statsHandler,
      wsHandlers
  });

  super.setHandler(wrapWithGzipHandler(contexts));
}
 
Example 2
Source File: WebServer.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
public WebServer(@NotNull SharedContext context, @NotNull Server server, @Nullable URL baseUrl, @NotNull EncryptionFactory tokenFactory) throws URISyntaxException {
  this.context = context;
  this.server = server;
  this.baseUrl = baseUrl == null ? null : baseUrl.toURI();
  this.tokenFactory = tokenFactory;
  final ServletContextHandler contextHandler = new ServletContextHandler();
  contextHandler.setContextPath("/");
  handler = contextHandler.getServletHandler();

  final RequestLogHandler logHandler = new RequestLogHandler();
  logHandler.setRequestLog((request, response) -> {
    final User user = (User) request.getAttribute(User.class.getName());
    final String username = (user == null || user.isAnonymous()) ? "" : user.getUsername();
    log.info("{}:{} - {} - \"{} {}\" {} {}", request.getRemoteHost(), request.getRemotePort(), username, request.getMethod(), request.getHttpURI(), response.getStatus(), response.getReason());
  });

  final HandlerCollection handlers = new HandlerCollection();
  handlers.addHandler(contextHandler);
  handlers.addHandler(logHandler);
  server.setHandler(handlers);
}
 
Example 3
Source File: RegisterExporters.java    From Patterdale with Apache License 2.0 6 votes vote down vote up
/**
 * @param registry Prometheus CollectorRegistry to register the default exporters.
 * @param httpPort The port the Server runs on.
 * @return a Jetty Server with Prometheus' default exporters registered.
 */
public static Server serverWithStatisticsCollection(CollectorRegistry registry, int httpPort) {
    Server server = new Server(httpPort);

    new StandardExports().register(registry);
    new MemoryPoolsExports().register(registry);
    new GarbageCollectorExports().register(registry);
    new ThreadExports().register(registry);
    new ClassLoadingExports().register(registry);
    new VersionInfoExports().register(registry);

    HandlerCollection handlers = new HandlerCollection();
    StatisticsHandler statisticsHandler = new StatisticsHandler();
    statisticsHandler.setServer(server);
    handlers.addHandler(statisticsHandler);

    new JettyStatisticsCollector(statisticsHandler).register(registry);
    server.setHandler(handlers);

    return server;
}
 
Example 4
Source File: JettyServerFactory.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Creates a server which delegates the request handling to both a logging
 * handler and to a web application, in this order.
 * 
 * @return a server
 */
public static Server createMultiHandlerServer() {
    Server server = createBaseServer();

    // Creates the handlers and adds them to the server.
    HandlerCollection handlers = new HandlerCollection();

    String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
    Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH);
    handlers.addHandler(customRequestHandler);

    Handler loggingRequestHandler = new LoggingRequestHandler();
    handlers.addHandler(loggingRequestHandler);

    server.setHandler(handlers);

    return server;
}
 
Example 5
Source File: WebsocketMultipleConnectionTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private static void startGatewayServer() throws Exception {
  /* use default Max threads */
  gatewayServer = new Server(new QueuedThreadPool(254));
  final ServerConnector connector = new ServerConnector(gatewayServer);
  gatewayServer.addConnector(connector);

  /* workaround so we can add our handler later at runtime */
  HandlerCollection handlers = new HandlerCollection(true);

  /* add some initial handlers */
  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  handlers.addHandler(context);

  gatewayServer.setHandler(handlers);

  // Start Server
  gatewayServer.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));

  /* Setup websocket handler */
  setupGatewayConfig(backendServerUri.toString());

  final GatewayWebsocketHandler gatewayWebsocketHandler = new GatewayWebsocketHandler(
      gatewayConfig, services);
  handlers.addHandler(gatewayWebsocketHandler);
  gatewayWebsocketHandler.start();
}
 
Example 6
Source File: ApplicationServer.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
protected final void doStart() throws Exception {
  HandlerCollection handlers = new HandlerCollection();
  HandlerCollection wsHandlers = new HandlerCollection();
  for (Application app : applications.getApplications()) {
    attachMetricsListener(app.getMetrics(), app.getMetricsTags());
    handlers.addHandler(app.configureHandler());
    wsHandlers.addHandler(app.configureWebSocketHandler());
  }
  finalizeHandlerCollection(handlers, wsHandlers);
  // Call super.doStart last to ensure that handlers are ready for incoming requests
  super.doStart();
}
 
Example 7
Source File: AdminWebServer.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
protected void startUp() throws Exception {
  LOGGER.info("Starting the admin web server");

  this.server = new Server(new InetSocketAddress(this.serverUri.getHost(), this.serverUri.getPort()));

  HandlerCollection handlerCollection = new HandlerCollection();

  handlerCollection.addHandler(buildSettingsHandler());
  handlerCollection.addHandler(buildStaticResourceHandler());

  this.server.setHandler(handlerCollection);
  this.server.start();
}
 
Example 8
Source File: WebsocketEchoTestBase.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Start Gateway Server.
 * @throws Exception exception on server start
 */
private static void startGatewayServer() throws Exception {
  gatewayServer = new Server();
  final ServerConnector connector = new ServerConnector(gatewayServer);
  gatewayServer.addConnector(connector);

  /* workaround so we can add our handler later at runtime */
  HandlerCollection handlers = new HandlerCollection(true);

  /* add some initial handlers */
  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  handlers.addHandler(context);

  gatewayServer.setHandler(handlers);

  // Start Server
  gatewayServer.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));

  /* Setup websocket handler */
  setupGatewayConfig(backendServerUri.toString());

  final GatewayWebsocketHandler gatewayWebsocketHandler = new GatewayWebsocketHandler(
      gatewayConfig, services);
  handlers.addHandler(gatewayWebsocketHandler);
  gatewayWebsocketHandler.start();
}
 
Example 9
Source File: BadUrlTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private static void startGatewayServer() throws Exception {
  gatewayServer = new Server();
  final ServerConnector connector = new ServerConnector(gatewayServer);
  gatewayServer.addConnector(connector);

  /* workaround so we can add our handler later at runtime */
  HandlerCollection handlers = new HandlerCollection(true);

  /* add some initial handlers */
  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  handlers.addHandler(context);

  gatewayServer.setHandler(handlers);

  // Start Server
  gatewayServer.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));

  /* Setup websocket handler */
  setupGatewayConfig(BACKEND);

  final GatewayWebsocketHandler gatewayWebsocketHandler = new GatewayWebsocketHandler(
      gatewayConfig, services);
  handlers.addHandler(gatewayWebsocketHandler);
  gatewayWebsocketHandler.start();
}
 
Example 10
Source File: MinimalServletsWithLogging.java    From cs601 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
       // Create a basic jetty server object that will listen on port 8080.  Note that if you set this to port 0
       // then a randomly available port will be assigned that you can either look in the logs for the port,
       // or programmatically obtain it for use in test cases.
       Server server = new Server(8080);
	HandlerCollection handlers = new HandlerCollection();
	server.setHandler(handlers);

       ServletHandler servlet = new ServletHandler();
	servlet.addServletWithMapping(HelloServlet.class, "/*");
	handlers.addHandler(servlet);

	handlers.addHandler(new DefaultHandler()); // must be after servlet it seems

	// log using NCSA (common log format)
	// http://en.wikipedia.org/wiki/Common_Log_Format
	NCSARequestLog requestLog = new NCSARequestLog();
	requestLog.setFilename("/tmp/yyyy_mm_dd.request.log");
	requestLog.setFilenameDateFormat("yyyy_MM_dd");
	requestLog.setRetainDays(90);
	requestLog.setAppend(true);
	requestLog.setExtended(true);
	requestLog.setLogCookies(false);
	requestLog.setLogTimeZone("GMT");
	RequestLogHandler requestLogHandler = new RequestLogHandler();
	requestLogHandler.setRequestLog(requestLog);
	handlers.addHandler(requestLogHandler);

	// Start things up! By using the server.join() the server thread will join with the current thread.
	// See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
	server.start();
	server.join();
}
 
Example 11
Source File: JettyMain.java    From ZStreamingQuote with MIT License 5 votes vote down vote up
/**
 * Main Jetty Server method
 * @param args
 */
public static void main( String[] args ) throws Exception{
	Server server = new Server(ZStreamingConfig.getJettyServerPortNum());
	
	HandlerCollection handlers = new HandlerCollection();
	
	//Add a handler for context "/zstreamingquote/start/"
	//Can be accessed using start(win) or wget(unix)
	//"http://localhost:8080/zstreamingquote/start/?apikey=1234dgfh&userid=DR1234&publictoken=gdhjkckwkljbdew32988yajj"
	handlers.addHandler(new ProcessStartActionHandler());
	
	//Add a handler for context "/zstreamingquote/stop/"
	//Can be accessed using start(win) or wget(unix)
	//"http://localhost:8080/zstreamingquote/stop/"
	handlers.addHandler(new ProcessStopActionHandler());
	
	//Add a handler for context "/zstreamingquote/timerangeohlc/"
	//Can be accessed using start(win) or wget(unix) 
	//"http://localhost:8080/zstreamingquote/timerangeohlc/?format=json&instrument=2342&from=10:00:00&to=14:00:00"
	handlers.addHandler(new TimeRangeOHLCActionHandler());
	
	//Add a handler for context "/zstreamingquote/timerangestreamingquote/"
	//Can be accessed using start(win) or wget(unix)
	//"http://localhost:8080/zstreamingquote/timerangestreamingquote/?format=json&instrument=2342&from=10:00:00&to=14:00:00"
	handlers.addHandler(new TimeRangeStreamingQuoteActionHandler());
	
	server.setHandler(handlers);

	// Start the server
	server.start();
	server.join();
}
 
Example 12
Source File: PullHttpChangeIngestorCommonTest.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
public static void init() {
    QueuedThreadPool queuedThreadPool = new QueuedThreadPool();
    queuedThreadPool.setDaemon(true);
    jetty = new Server(queuedThreadPool);

    HandlerCollection handlerCollection = new HandlerCollection(true);
    handlerCollection.addHandler(new JettyHandler(RESPONSE_STRING, PATH_RESPONSE_STRING));
    jetty.setHandler(handlerCollection);
}
 
Example 13
Source File: RestChangeIngestor.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(Properties properties, ConfigurationFileHolder configurationFileHolder, ConfigurationChangeNotifier configurationChangeNotifier) {
    logger.info("Initializing");

    final String differentiatorName = properties.getProperty(DIFFERENTIATOR_KEY);

    if (differentiatorName != null && !differentiatorName.isEmpty()) {
        Supplier<Differentiator<InputStream>> differentiatorSupplier = DIFFERENTIATOR_CONSTRUCTOR_MAP.get(differentiatorName);
        if (differentiatorSupplier == null) {
            throw new IllegalArgumentException("Property, " + DIFFERENTIATOR_KEY + ", has value " + differentiatorName + " which does not " +
                    "correspond to any in the PullHttpChangeIngestor Map:" + DIFFERENTIATOR_CONSTRUCTOR_MAP.keySet());
        }
        differentiator = differentiatorSupplier.get();
    } else {
        differentiator = WholeConfigDifferentiator.getInputStreamDifferentiator();
    }
    differentiator.initialize(properties, configurationFileHolder);

    // create the secure connector if keystore location is specified
    if (properties.getProperty(KEYSTORE_LOCATION_KEY) != null) {
        createSecureConnector(properties);
    } else {
        // create the unsecure connector otherwise
        createConnector(properties);
    }

    this.configurationChangeNotifier = configurationChangeNotifier;

    HandlerCollection handlerCollection = new HandlerCollection(true);
    handlerCollection.addHandler(new JettyHandler());
    jetty.setHandler(handlerCollection);
}
 
Example 14
Source File: GatewayServer.java    From knox with Apache License 2.0 4 votes vote down vote up
private static HandlerCollection createHandlers(
    final GatewayConfig config,
    final GatewayServices services,
    final ContextHandlerCollection contexts,
    final Map<String, Integer> topologyPortMap) {

  final Map<String, Handler> contextToHandlerMap = new HashMap<>();
  if(contexts.getHandlers() != null) {
    Arrays.asList(contexts.getHandlers()).stream()
        .filter(h -> h instanceof WebAppContext)
        .forEach(h -> contextToHandlerMap
            .put(((WebAppContext) h).getContextPath(), h));
  }

  HandlerCollection handlers = new HandlerCollection();
  RequestLogHandler logHandler = new RequestLogHandler();

  logHandler.setRequestLog( new AccessHandler() );

  TraceHandler traceHandler = new TraceHandler();
  traceHandler.setHandler( contexts );
  traceHandler.setTracedBodyFilter( System.getProperty( "org.apache.knox.gateway.trace.body.status.filter" ) );

  CorrelationHandler correlationHandler = new CorrelationHandler();
  correlationHandler.setHandler( traceHandler );

  // Used to correct the {target} part of request with Topology Port Mapping feature
  final PortMappingHelperHandler portMappingHandler = new PortMappingHelperHandler(config);
  portMappingHandler.setHandler(correlationHandler);

   // If topology to port mapping feature is enabled then we add new Handler {RequestForwardHandler}
   // to the chain, this handler listens on the configured port (in gateway-site.xml)
   // and simply forwards requests to the correct context path.

   //  The reason for adding ContextHandler is so that we can add a connector
   // to it on which the handler listens (exclusively).


  if (config.isGatewayPortMappingEnabled()) {

    /* Do the virtual host bindings for all the defined topology port mapped
    *  contexts except for the one that has gateway port to prevent issues
    *  with context deployment */
    topologyPortMap
        .entrySet()
        .stream()
        .filter(e -> !e.getValue().equals(config.getGatewayPort()))
        .forEach( entry ->  {
          log.createJettyHandler(entry.getKey());
          final Handler context = contextToHandlerMap
              .get("/" + config.getGatewayPath() + "/" + entry.getKey());

          if(context !=  null) {
            ((WebAppContext) context).setVirtualHosts(
                new String[] { "@" + entry.getKey().toLowerCase(Locale.ROOT) });
          } else {
            // no topology found for mapping entry.getKey()
            log.noMappedTopologyFound(entry.getKey());
          }
        });
  }

  handlers.addHandler(logHandler);

  if (config.isWebsocketEnabled()) {
    final GatewayWebsocketHandler websocketHandler = new GatewayWebsocketHandler(
        config, services);
    websocketHandler.setHandler(portMappingHandler);

    handlers.addHandler(websocketHandler);

  } else {
    handlers.addHandler(portMappingHandler);
  }

  return handlers;
}
 
Example 15
Source File: Activator.java    From slr-toolkit with Eclipse Public License 1.0 4 votes vote down vote up
public void start(BundleContext context) throws Exception {
	super.start(context);

	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	String webappRoot = workspace.getRoot().getLocation().toString().concat("/webapp");
	new File(webappRoot).mkdirs();

	Activator.WEB_APP_WORKSPACE = webappRoot;

	// create the server on a free port
	Server server = new Server(0);

	// Configure the ResourceHandler. Setting the resource base indicates where the
	// files should be served out of.
	ResourceHandler resource_handler = new ResourceHandler();
	resource_handler.setDirectoriesListed(true);
	resource_handler.setResourceBase(webappRoot);

	// Add the ResourceHandler to the server.
	HandlerCollection handlers = new HandlerCollection(true);
	handlers.addHandler(resource_handler);

	server.setHandler(handlers);

	// Start server up.
	try {
		server.start();
	} catch (Exception e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	// Get the URI of the server and set it global for the
	// diagram handlers to access
	if (null != server && null != server.getURI()) {
		String localhost = server.getURI().toString();
		Activator.URL = localhost;
	}

	writeVegaFiles();

	plugin = this;
}
 
Example 16
Source File: JettyServer.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"resource", "boxing"})
public static Server newServer(int jettyPort, String jettyWebAppDir, JettyServiceSetting jettyServiceSetting) throws Exception {

    if (jettyPort == 0 || jettyWebAppDir == null) {
        throw new IllegalArgumentException("Jetty port and resource dir may not be empty");
    }

    // server setup
    Server server = new Server();
    server.addBean(new ScheduledExecutorScheduler());
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);


    // http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html#d0e19050
    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);


    //setup handlers according to the jetty settings
    HandlerCollection handlerCollection = new HandlerCollection();

    if (jettyServiceSetting == JettyServiceSetting.ARTIFACTORY || jettyServiceSetting == JettyServiceSetting.BOTH) {

        // The WebAppContext is the entity that controls the environment in
        // which a web application lives and breathes. In this example the
        // context path is being set to "/" so it is suitable for serving root
        // context requests and then we see it setting the location of the war.
        // A whole host of other configurations are available, ranging from
        // configuring to support annotation scanning in the webapp (through
        // PlusConfiguration) to choosing where the webapp will unpack itself.
        WebAppContext webapp = new WebAppContext();
        File warFile = new File(jettyWebAppDir + File.separator + "artifactory.war");
        webapp.setContextPath("/artifactory");
        webapp.setWar(warFile.getAbsolutePath());

        // A WebAppContext is a ContextHandler as well so it needs to be set to
        // the server so it is aware of where to send the appropriate requests.
        handlerCollection.addHandler(webapp);

    }

    if (jettyServiceSetting == JettyServiceSetting.VIP || jettyServiceSetting == JettyServiceSetting.BOTH) {

        // Serve resource files which reside in the jettyWebAppDir
        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);
        resourceHandler.setResourceBase(jettyWebAppDir);

        handlerCollection.addHandler(resourceHandler);
    }

    server.setHandler(handlerCollection);


    // http configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSendServerVersion(true);

    // HTTP connector
    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(jettyPort);
    server.addConnector(http);

    // start server
    server.start();

    LOG.info("Started jetty server on port: {}, resource dir: {} ", jettyPort, jettyWebAppDir);
    return server;
}
 
Example 17
Source File: JettyServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
private Handler loadInitialWars(final Set<Bundle> bundles) {

        // load WARs
        final Map<File, Bundle> warToBundleLookup = findWars(bundles);

        // locate each war being deployed
        File webUiWar = null;
        File webApiWar = null;
        File webErrorWar = null;
        File webDocsWar = null;
        File webContentViewerWar = null;
        Map<File, Bundle> otherWars = new HashMap<>();
        for (Map.Entry<File,Bundle> warBundleEntry : warToBundleLookup.entrySet()) {
            final File war = warBundleEntry.getKey();
            final Bundle warBundle = warBundleEntry.getValue();

            if (war.getName().toLowerCase().startsWith("nifi-web-api")) {
                webApiWar = war;
            } else if (war.getName().toLowerCase().startsWith("nifi-web-error")) {
                webErrorWar = war;
            } else if (war.getName().toLowerCase().startsWith("nifi-web-docs")) {
                webDocsWar = war;
            } else if (war.getName().toLowerCase().startsWith("nifi-web-content-viewer")) {
                webContentViewerWar = war;
            } else if (war.getName().toLowerCase().startsWith("nifi-web")) {
                webUiWar = war;
            } else {
                otherWars.put(war, warBundle);
            }
        }

        // ensure the required wars were found
        if (webUiWar == null) {
            throw new RuntimeException("Unable to load nifi-web WAR");
        } else if (webApiWar == null) {
            throw new RuntimeException("Unable to load nifi-web-api WAR");
        } else if (webDocsWar == null) {
            throw new RuntimeException("Unable to load nifi-web-docs WAR");
        } else if (webErrorWar == null) {
            throw new RuntimeException("Unable to load nifi-web-error WAR");
        } else if (webContentViewerWar == null) {
            throw new RuntimeException("Unable to load nifi-web-content-viewer WAR");
        }

        // handlers for each war and init params for the web api
        final ExtensionUiInfo extensionUiInfo = loadWars(otherWars);
        componentUiExtensionWebContexts = new ArrayList<>(extensionUiInfo.getComponentUiExtensionWebContexts());
        contentViewerWebContexts = new ArrayList<>(extensionUiInfo.getContentViewerWebContexts());
        componentUiExtensions = new UiExtensionMapping(extensionUiInfo.getComponentUiExtensionsByType());

        final HandlerCollection webAppContextHandlers = new HandlerCollection();
        final Collection<WebAppContext> extensionUiContexts = extensionUiInfo.getWebAppContexts();
        extensionUiContexts.stream().forEach(c -> webAppContextHandlers.addHandler(c));

        final ClassLoader frameworkClassLoader = getClass().getClassLoader();

        // load the web ui app
        final WebAppContext webUiContext = loadWar(webUiWar, "/nifi", frameworkClassLoader);
        webUiContext.getInitParams().put("oidc-supported", String.valueOf(props.isOidcEnabled()));
        webUiContext.getInitParams().put("knox-supported", String.valueOf(props.isKnoxSsoEnabled()));
        webUiContext.getInitParams().put("allowedContextPaths", props.getAllowedContextPaths());
        webAppContextHandlers.addHandler(webUiContext);

        // load the web api app
        webApiContext = loadWar(webApiWar, "/nifi-api", frameworkClassLoader);
        webAppContextHandlers.addHandler(webApiContext);

        // load the content viewer app
        webContentViewerContext = loadWar(webContentViewerWar, "/nifi-content-viewer", frameworkClassLoader);
        webContentViewerContext.getInitParams().putAll(extensionUiInfo.getMimeMappings());
        webAppContextHandlers.addHandler(webContentViewerContext);

        // create a web app for the docs
        final String docsContextPath = "/nifi-docs";

        // load the documentation war
        webDocsContext = loadWar(webDocsWar, docsContextPath, frameworkClassLoader);

        // add the servlets which serve the HTML documentation within the documentation web app
        addDocsServlets(webDocsContext);

        webAppContextHandlers.addHandler(webDocsContext);

        // load the web error app
        final WebAppContext webErrorContext = loadWar(webErrorWar, "/", frameworkClassLoader);
        webErrorContext.getInitParams().put("allowedContextPaths", props.getAllowedContextPaths());
        webAppContextHandlers.addHandler(webErrorContext);

        // deploy the web apps
        return gzip(webAppContextHandlers);
    }
 
Example 18
Source File: EsigateServer.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * Create and start server.
 * 
 * @throws Exception
 *             when server cannot be started.
 */
public static void start() throws Exception {
    MetricRegistry registry = new MetricRegistry();

    QueuedThreadPool threadPool = new InstrumentedQueuedThreadPool(registry);
    threadPool.setName("esigate");
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);

    srv = new Server(threadPool);
    srv.setStopAtShutdown(true);
    srv.setStopTimeout(5000);

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setOutputBufferSize(outputBufferSize);
    httpConfig.setSendServerVersion(false);
    Timer processTime = registry.timer("processTime");

    try (ServerConnector connector =
            new InstrumentedServerConnector("main", EsigateServer.port, srv, registry,
                    new InstrumentedConnectionFactory(new HttpConnectionFactory(httpConfig), processTime));
            ServerConnector controlConnector = new ServerConnector(srv)) {

        // Main connector
        connector.setIdleTimeout(EsigateServer.idleTimeout);
        connector.setSoLingerTime(-1);
        connector.setName("main");
        connector.setAcceptQueueSize(200);

        // Control connector
        controlConnector.setHost("127.0.0.1");
        controlConnector.setPort(EsigateServer.controlPort);
        controlConnector.setName("control");

        srv.setConnectors(new Connector[] {connector, controlConnector});
        // War
        ProtectionDomain protectionDomain = EsigateServer.class.getProtectionDomain();
        String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();
        String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent();

        File workDir = resetTempDirectory(currentDir);

        WebAppContext context = new WebAppContext(warFile, EsigateServer.contextPath);
        context.setServer(srv);
        context.setTempDirectory(workDir);
        if (StringUtils.isNoneEmpty(sessionCookieName)) {
            context.getSessionHandler().getSessionCookieConfig().setName(sessionCookieName);
        }
        // Add extra classpath (allows to add extensions).
        if (EsigateServer.extraClasspath != null) {
            context.setExtraClasspath(EsigateServer.extraClasspath);
        }

        // Add the handlers
        HandlerCollection handlers = new HandlerList();
        // control handler must be the first one.
        // Work in progress, currently disabled.
        handlers.addHandler(new ControlHandler(registry));
        InstrumentedHandler ih = new InstrumentedHandler(registry);
        ih.setName("main");
        ih.setHandler(context);
        handlers.addHandler(ih);

        srv.setHandler(handlers);
        srv.start();
        srv.join();

    }

}
 
Example 19
Source File: ManagerApiMicroService.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * Configure the web application(s).
 * @param handlers
 * @throws Exception
 */
protected void addModulesToJetty(HandlerCollection handlers) throws Exception {
	/* *************
     * Manager API
     * ************* */
    ServletContextHandler apiManServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
    addSecurityHandler(apiManServer);
    apiManServer.setContextPath("/apiman");
    apiManServer.addEventListener(new Listener());
    apiManServer.addEventListener(new BeanManagerResourceBindingListener());
    apiManServer.addEventListener(new ResteasyBootstrap());
    apiManServer.addFilter(LocaleFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    apiManServer.addFilter(ApimanCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    apiManServer.addFilter(DisableCachingFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    addAuthFilter(apiManServer);
    apiManServer.addFilter(DefaultSecurityContextFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    apiManServer.addFilter(RootResourceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    apiManServer.addFilter(ManagerApiMicroServiceTxWatchdogFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    ServletHolder resteasyServlet = new ServletHolder(new HttpServletDispatcher());
    resteasyServlet.setInitParameter("javax.ws.rs.Application", ManagerApiMicroServiceApplication.class.getName());
    apiManServer.addServlet(resteasyServlet, "/*");

    apiManServer.setInitParameter("resteasy.injector.factory", "org.jboss.resteasy.cdi.CdiInjectorFactory");
    apiManServer.setInitParameter("resteasy.scan", "true");
    apiManServer.setInitParameter("resteasy.servlet.mapping.prefix", "");

    handlers.addHandler(apiManServer);

    /* ********** *
     * Manager UI *
     * ********** */
    ResourceHandler apimanUiServer = new ResourceHandler() {
        /**
         * @see org.eclipse.jetty.server.handler.ResourceHandler#getResource(java.lang.String)
         */
        @Override
        public Resource getResource(String path) {
            Resource resource = null;

            if (path == null || path.equals("/") || path.equals("/index.html")) {
                path = "/index.html";
            }
            if (path.startsWith("/apimanui/api-manager") || path.equals("/apimanui") || path.equals("/apimanui/")) {
                path = "/apimanui/index.html";
            }
            if (path.equals("/apimanui/apiman/config.js")) {
                resource = getConfigResource(path);
            }
            if (path.equals("/apimanui/apiman/translations.js")) {
                resource = getTranslationsResource(path);
            }

            if (resource == null) {
                URL url = getClass().getResource(path);
                if (url != null) {
                    resource = new ApimanResource(url);
                }
            }

            return resource;
        }
    };
    apimanUiServer.setResourceBase("/apimanui/");
    apimanUiServer.setWelcomeFiles(new String[] { "index.html" });
    handlers.addHandler(apimanUiServer);
}
 
Example 20
Source File: JettyServer.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
private void loadWars() throws IOException {
    final File warDirectory = properties.getWarLibDirectory();
    final File[] wars = warDirectory.listFiles(WAR_FILTER);

    if (wars == null) {
        throw new RuntimeException("Unable to access war lib directory: " + warDirectory);
    }

    File webUiWar = null;
    File webApiWar = null;
    File webDocsWar = null;
    for (final File war : wars) {
        if (war.getName().startsWith("nifi-registry-web-ui")) {
            webUiWar = war;
        } else if (war.getName().startsWith("nifi-registry-web-api")) {
            webApiWar = war;
        } else if (war.getName().startsWith("nifi-registry-web-docs")) {
            webDocsWar = war;
        }
    }

    if (webUiWar == null) {
        throw new IllegalStateException("Unable to locate NiFi Registry Web UI");
    } else if (webApiWar == null) {
        throw new IllegalStateException("Unable to locate NiFi Registry Web API");
    } else if (webDocsWar == null) {
        throw new IllegalStateException("Unable to locate NiFi Registry Web Docs");
    }

    webUiContext = loadWar(webUiWar, "/nifi-registry");

    webApiContext = loadWar(webApiWar, "/nifi-registry-api", getWebApiAdditionalClasspath());
    logger.info("Adding {} object to ServletContext with key 'nifi-registry.properties'", properties.getClass().getSimpleName());
    webApiContext.setAttribute("nifi-registry.properties", properties);
    logger.info("Adding {} object to ServletContext with key 'nifi-registry.key'", masterKeyProvider.getClass().getSimpleName());
    webApiContext.setAttribute("nifi-registry.key", masterKeyProvider);

    // there is an issue scanning the asm repackaged jar so narrow down what we are scanning
    webApiContext.setAttribute("org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern", ".*/spring-[^/]*\\.jar$");

    final String docsContextPath = "/nifi-registry-docs";
    webDocsContext = loadWar(webDocsWar, docsContextPath);
    addDocsServlets(webDocsContext);

    final HandlerCollection handlers = new HandlerCollection();
    handlers.addHandler(webUiContext);
    handlers.addHandler(webApiContext);
    handlers.addHandler(webDocsContext);
    server.setHandler(handlers);
}