Java Code Examples for org.eclipse.jetty.webapp.WebAppContext#addFilter()

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#addFilter() . 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: WebServerComponent.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private WebAppContext deployWar(String url, String warFile, Path warDirectory) throws IOException {
   WebAppContext webapp = new WebAppContext();
   if (url.startsWith("/")) {
      webapp.setContextPath(url);
   } else {
      webapp.setContextPath("/" + url);
   }
   //add the filters needed for audit logging
   webapp.addFilter(new FilterHolder(JolokiaFilter.class), "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
   webapp.addFilter(new FilterHolder(AuthenticationFilter.class), "/auth/login/*", EnumSet.of(DispatcherType.REQUEST));

   webapp.setWar(warDirectory.resolve(warFile).toString());

   webapp.setAttribute("org.eclipse.jetty.webapp.basetempdir", temporaryWarDir.toFile().getAbsolutePath());

   handlers.addHandler(webapp);
   return webapp;
}
 
Example 2
Source File: JettyPlusIT.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * onAppStart
 * 
 * @param args
 */
public void onAppStart(Object... args) {

    WebAppContext sc = getWebAppContext(args);

    if (sc == null) {
        return;
    }

    InterceptSupport iSupport = InterceptSupport.instance();
    InterceptContext context = iSupport.createInterceptContext(Event.WEBCONTAINER_STARTED);
    context.put(InterceptConstants.WEBAPPLOADER, sc.getClassLoader());
    context.put(InterceptConstants.WEBWORKDIR, sc.getServletContext().getRealPath(""));
    context.put(InterceptConstants.CONTEXTPATH, sc.getContextPath());
    context.put(InterceptConstants.APPNAME, sc.getDisplayName());

    ServletContext sContext = sc.getServletContext();

    context.put(InterceptConstants.SERVLET_CONTEXT, sContext);

    getBasePath(context, sContext);

    iSupport.doIntercept(context);

    // GlobalFilter
    sc.addFilter("com.creditease.monitor.jee.filters.GlobalFilter", "/*", EnumSet.of(DispatcherType.REQUEST));
}
 
Example 3
Source File: ZeppelinServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static WebAppContext setupWebAppContext(
    ContextHandlerCollection contexts, ZeppelinConfiguration conf, String warPath, String contextPath) {
  WebAppContext webApp = new WebAppContext();
  webApp.setContextPath(contextPath);
  LOG.info("warPath is: {}", warPath);
  File warFile = new File(warPath);
  if (warFile.isDirectory()) {
    // Development mode, read from FS
    // webApp.setDescriptor(warPath+"/WEB-INF/web.xml");
    webApp.setResourceBase(warFile.getPath());
    webApp.setParentLoaderPriority(true);
  } else {
    // use packaged WAR
    webApp.setWar(warFile.getAbsolutePath());
    webApp.setExtractWAR(false);
    File warTempDirectory = new File(conf.getRelativeDir(ConfVars.ZEPPELIN_WAR_TEMPDIR) + contextPath);
    warTempDirectory.mkdir();
    LOG.info("ZeppelinServer Webapp path: {}", warTempDirectory.getPath());
    webApp.setTempDirectory(warTempDirectory);
  }
  // Explicit bind to root
  webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
  contexts.addHandler(webApp);

  webApp.addFilter(new FilterHolder(CorsFilter.class), "/*", EnumSet.allOf(DispatcherType.class));

  webApp.setInitParameter(
      "org.eclipse.jetty.servlet.Default.dirAllowed",
      Boolean.toString(conf.getBoolean(ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED)));
  return webApp;
}
 
Example 4
Source File: JettyServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void performInjectionForComponentUis(final Collection<WebAppContext> componentUiExtensionWebContexts,
                                             final NiFiWebConfigurationContext configurationContext, final FilterHolder securityFilter) {
    if (CollectionUtils.isNotEmpty(componentUiExtensionWebContexts)) {
        for (final WebAppContext customUiContext : componentUiExtensionWebContexts) {
            // set the NiFi context in each custom ui servlet context
            final ServletContext customUiServletContext = customUiContext.getServletHandler().getServletContext();
            customUiServletContext.setAttribute("nifi-web-configuration-context", configurationContext);

            // add the security filter to any ui extensions wars
            if (securityFilter != null) {
                customUiContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class));
            }
        }
    }
}
 
Example 5
Source File: JettyServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void performInjectionForContentViewerUis(final Collection<WebAppContext> contentViewerWebContexts,
                                                 final FilterHolder securityFilter) {
    if (CollectionUtils.isNotEmpty(contentViewerWebContexts)) {
        for (final WebAppContext contentViewerContext : contentViewerWebContexts) {
            // add the security filter to any content viewer  wars
            if (securityFilter != null) {
                contentViewerContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class));
            }
        }
    }
}
 
Example 6
Source File: AbstractServiceInterfaceTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    // starts the server with a random port
    jettyServer = new Server(0);

    WebAppContext bpCtrlWebapp = new WebAppContext();
    bpCtrlWebapp.setResourceBase("./src/main/java");
    bpCtrlWebapp.setParentLoaderPriority(true);

    bpCtrlWebapp.addFilter(GuiceFilter.class, "/*", null);
    bpCtrlWebapp.addEventListener(new GuiceServletContextListener() {

        private Injector injector;

        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            injector = Guice.createInjector(getServletTestModule());
            super.contextInitialized(servletContextEvent);
        }

        @Override
        protected Injector getInjector() {
            return injector;
        }
    });

    jettyServer.setHandler(bpCtrlWebapp);

    jettyServer.start();

    int port = ((ServerConnector) jettyServer.getConnectors()[0]).getLocalPort();
    serverUrl = String.format("http://localhost:%d", port);
}
 
Example 7
Source File: WebDriverTestCase.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the web server delivering response from the provided connection.
 * @param mockConnection the sources for responses
 * @param serverCharset the {@link Charset} at the server side
 * @throws Exception if a problem occurs
 */
protected void startWebServer(final MockWebConnection mockConnection, final Charset serverCharset)
        throws Exception {
    if (Boolean.FALSE.equals(LAST_TEST_UsesMockWebConnection_)) {
        stopWebServers();
    }

    LAST_TEST_UsesMockWebConnection_ = Boolean.TRUE;
    if (STATIC_SERVER_ == null) {
        final Server server = buildServer(PORT);

        final WebAppContext context = new WebAppContext();
        context.setContextPath("/");
        context.setResourceBase("./");

        if (isBasicAuthentication()) {
            final Constraint constraint = new Constraint();
            constraint.setName(Constraint.__BASIC_AUTH);
            constraint.setRoles(new String[]{"user"});
            constraint.setAuthenticate(true);

            final ConstraintMapping constraintMapping = new ConstraintMapping();
            constraintMapping.setConstraint(constraint);
            constraintMapping.setPathSpec("/*");

            final ConstraintSecurityHandler handler = (ConstraintSecurityHandler) context.getSecurityHandler();
            handler.setLoginService(new HashLoginService("MyRealm", "./src/test/resources/realm.properties"));
            handler.setConstraintMappings(new ConstraintMapping[]{constraintMapping});
        }

        context.addServlet(MockWebConnectionServlet.class, "/*");
        if (serverCharset != null) {
            AsciiEncodingFilter.CHARSET_ = serverCharset;
            context.addFilter(AsciiEncodingFilter.class, "/*",
                    EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
        }
        server.setHandler(context);
        WebServerTestCase.tryStart(PORT, server);

        STATIC_SERVER_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServerStarter"));
        STATIC_SERVER_ = server;
    }
    MockWebConnectionServlet.MockConnection_ = mockConnection;

    if (STATIC_SERVER2_ == null && needThreeConnections()) {
        final Server server2 = buildServer(PORT2);
        final WebAppContext context2 = new WebAppContext();
        context2.setContextPath("/");
        context2.setResourceBase("./");
        context2.addServlet(MockWebConnectionServlet.class, "/*");
        server2.setHandler(context2);
        WebServerTestCase.tryStart(PORT2, server2);

        STATIC_SERVER2_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServer2Starter"));
        STATIC_SERVER2_ = server2;

        final Server server3 = buildServer(PORT3);
        final WebAppContext context3 = new WebAppContext();
        context3.setContextPath("/");
        context3.setResourceBase("./");
        context3.addServlet(MockWebConnectionServlet.class, "/*");
        server3.setHandler(context3);
        WebServerTestCase.tryStart(PORT3, server3);

        STATIC_SERVER3_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServer3Starter"));
        STATIC_SERVER3_ = server3;
        /*
         * The mock connection servlet call sit under both servers, so long as tests
         * keep the URLs distinct.
         */
    }
}
 
Example 8
Source File: WebServerTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Server start(WebServer webServer) throws Exception {

		/**
		 * 更新x_desktop的center指向
		 */
		updateCenterConfigJson();
		/**
		 * 更新 favicon.ico
		 */
		updateFavicon();
		/**
		 * 创建index.html
		 */
		createIndexPage();

		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMinThreads(WEBSERVER_THREAD_POOL_SIZE_MIN);
		threadPool.setMaxThreads(WEBSERVER_THREAD_POOL_SIZE_MAX);
		Server server = new Server(threadPool);
		if (webServer.getSslEnable()) {
			addHttpsConnector(server, webServer.getPort());
		} else {
			addHttpConnector(server, webServer.getPort());
		}
		WebAppContext context = new WebAppContext();
		context.setContextPath("/");
		context.setBaseResource(Resource.newResource(new File(Config.base(), "servers/webServer")));
		// context.setResourceBase(".");
		context.setParentLoaderPriority(true);
		context.setExtractWAR(false);
		// context.setDefaultsDescriptor(new File(Config.base(),
		// "commons/webdefault_w.xml").getAbsolutePath());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "" + webServer.getDirAllowed());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
		if (webServer.getCacheControlMaxAge() > 0) {
			context.setInitParameter("org.eclipse.jetty.servlet.Default.cacheControl",
					"max-age=" + webServer.getCacheControlMaxAge());
		}
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCacheSize", "256000000");
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCachedFileSize", "200000000");
		context.setWelcomeFiles(new String[] { "default.html", "index.html" });
		context.setGzipHandler(new GzipHandler());
		context.setParentLoaderPriority(true);
		context.getMimeTypes().addMimeMapping("wcss", "application/json");
		/* stat */
		if (webServer.getStatEnable()) {
			FilterHolder statFilterHolder = new FilterHolder(new WebStatFilter());
			statFilterHolder.setInitParameter("exclusions", webServer.getStatExclusions());
			context.addFilter(statFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
			ServletHolder statServletHolder = new ServletHolder(StatViewServlet.class);
			statServletHolder.setInitParameter("sessionStatEnable", "false");
			context.addServlet(statServletHolder, "/druid/*");
		}
		/* stat end */
		server.setHandler(context);
		server.setDumpAfterStart(false);
		server.setDumpBeforeStop(false);
		server.setStopAtShutdown(true);
		server.start();

		context.setMimeTypes(Config.mimeTypes());
		System.out.println("****************************************");
		System.out.println("* web server start completed.");
		System.out.println("* port: " + webServer.getPort() + ".");
		System.out.println("****************************************");
		return server;
	}
 
Example 9
Source File: JettyServer.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
private void addFilters(Class<? extends Filter> clazz, String path, WebAppContext webappContext) {
    FilterHolder holder = new FilterHolder(clazz);
    holder.setName(clazz.getSimpleName());
    webappContext.addFilter(holder, path, EnumSet.allOf(DispatcherType.class));
}
 
Example 10
Source File: JettyServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void addFilters(Class<? extends Filter> clazz, String path, WebAppContext webappContext) {
    FilterHolder holder = new FilterHolder(clazz);
    holder.setName(clazz.getSimpleName());
    webappContext.addFilter(holder, path, EnumSet.allOf(DispatcherType.class));
}
 
Example 11
Source File: FakeGoServer.java    From gocd with Apache License 2.0 4 votes vote down vote up
private void addDefaultServlet(WebAppContext wac) {
    wac.addFilter(BreakpointFriendlyFilter.class, "*", EnumSet.of(DispatcherType.REQUEST));
}
 
Example 12
Source File: ServerRpcProvider.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
public void startWebSocketServer(final Injector injector) {
  httpServer = new Server();

  List<Connector> connectors = getSelectChannelConnectors(httpAddresses);
  if (connectors.isEmpty()) {
    LOG.severe("No valid http end point address provided!");
  }
  for (Connector connector : connectors) {
    httpServer.addConnector(connector);
  }
  final WebAppContext context = new WebAppContext();

  context.setParentLoaderPriority(true);

  if (jettySessionManager != null) {
    // This disables JSessionIDs in URLs redirects
    // see: http://stackoverflow.com/questions/7727534/how-do-you-disable-jsessionid-for-jetty-running-with-the-eclipse-jetty-maven-plu
    // and: http://jira.codehaus.org/browse/JETTY-467?focusedCommentId=114884&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-114884
    jettySessionManager.setSessionIdPathParameterName(null);

    context.getSessionHandler().setSessionManager(jettySessionManager);
  }
  final ResourceCollection resources = new ResourceCollection(resourceBases);
  context.setBaseResource(resources);

  addWebSocketServlets();

  try {

    final ServletModule servletModule = getServletModule();

    ServletContextListener contextListener = new GuiceServletContextListener() {

      private final Injector childInjector = injector.createChildInjector(servletModule);

      @Override
      protected Injector getInjector() {
        return childInjector;
      }
    };

    context.addEventListener(contextListener);
    context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    context.addFilter(GzipFilter.class, "/webclient/*", EnumSet.allOf(DispatcherType.class));
    httpServer.setHandler(context);

    httpServer.start();
    restoreSessions();

  } catch (Exception e) { // yes, .start() throws "Exception"
    LOG.severe("Fatal error starting http server.", e);
    return;
  }
  LOG.fine("WebSocket server running.");
}