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

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#addServlet() . 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: ZeppelinServer.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private static void setupRestApiContextHandler(WebAppContext webapp, ZeppelinConfiguration conf) {
  final ServletHolder servletHolder =
      new ServletHolder(new org.glassfish.jersey.servlet.ServletContainer());

  servletHolder.setInitParameter("javax.ws.rs.Application", ZeppelinServer.class.getName());
  servletHolder.setName("rest");
  servletHolder.setForcedPath("rest");
  webapp.setSessionHandler(new SessionHandler());
  webapp.addServlet(servletHolder, "/api/*");

  String shiroIniPath = conf.getShiroPath();
  if (!StringUtils.isBlank(shiroIniPath)) {
    webapp.setInitParameter("shiroConfigLocations", new File(shiroIniPath).toURI().toString());
    webapp
        .addFilter(ShiroFilter.class, "/api/*", EnumSet.allOf(DispatcherType.class))
        .setInitParameter("staticSecurityManagerEnabled", "true");
    webapp.addEventListener(new EnvironmentLoaderListener());
  }
}
 
Example 2
Source File: App.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
private WebAppContext createDeployedApplicationInstance(File workDirectory,
		String deployedApplicationPath) {
	WebAppContext deployedApplication = new WebAppContext();
	deployedApplication.setContextPath(this.getContextPath());
	deployedApplication.setWar(deployedApplicationPath);
	deployedApplication.setAttribute("javax.servlet.context.tempdir",
			workDirectory.getAbsolutePath());
	deployedApplication
			.setAttribute(
					"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
					".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/.*taglibs.*\\.jar$");
	deployedApplication.setAttribute(
			"org.eclipse.jetty.containerInitializers", jspInitializers());
	deployedApplication.setAttribute(InstanceManager.class.getName(),
			new SimpleInstanceManager());
	deployedApplication.addBean(new ServletContainerInitializersStarter(
			deployedApplication), true);
	// webapp.setClassLoader(new URLClassLoader(new
	// URL[0],App.class.getClassLoader()));
	deployedApplication.addServlet(jspServletHolder(), "*.jsp");
	return deployedApplication;
}
 
Example 3
Source File: EngineLifecycleTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpDownWithServlets() throws Exception {
    setUpBus();

    Bus bus = (Bus)applicationContext.getBean("cxf");
    ServerRegistry sr = bus.getExtension(ServerRegistry.class);
    ServerImpl si = (ServerImpl) sr.getServers().get(0);
    JettyHTTPDestination jhd = (JettyHTTPDestination) si.getDestination();
    JettyHTTPServerEngine e = (JettyHTTPServerEngine) jhd.getEngine();
    org.eclipse.jetty.server.Server jettyServer = e.getServer();

    for (Handler h : jettyServer.getChildHandlersByClass(WebAppContext.class)) {
        WebAppContext wac = (WebAppContext) h;
        if ("/jsunit".equals(wac.getContextPath())) {
            wac.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/bloop");
            break;
        }
    }

    try {
        verifyStaticHtml();
        invokeService();
    } finally {
        shutdownService();
    }
}
 
Example 4
Source File: JettyWebServer.java    From oxygen with Apache License 2.0 6 votes vote down vote up
private void configWebapp(WebAppContext webapp, JettyConf jettyConf)
    throws URISyntaxException, IOException {
  webapp.setContextPath(contextPath);
  webapp.setVirtualHosts(jettyConf.getVirtualHosts());
  webapp.setMaxFormContentSize(jettyConf.getMaxFormContentSize());
  webapp.setMaxFormKeys(jettyConf.getMaxFormKeys());
  webapp.setParentLoaderPriority(true);
  webapp.setConfigurationDiscovered(jettyConf.isConfigurationDiscovered());
  webapp.setTempDirectory(new File(FileUtils.tempBaseDir(), "jetty-temp"));
  URL url = getClass().getResource(Strings.SLASH);
  if (url != null) {
    webapp.setResourceBase(url.toURI().toASCIIString());
  } else {
    // run in jar
    File dir = new File(FileUtils.tempBaseDir(), "jetty-jsp");
    webapp.setResourceBase(dir.getAbsolutePath());
    if (dir.exists() || dir.mkdirs()) {
      copyJspFiles(dir);
    }
  }
  webapp.addServlet(new ServletHolder("jsp", JettyJspServlet.class), "*.jsp");
  webapp.setConfigurations(new Configuration[]{new AnnotationConfiguration()});
}
 
Example 5
Source File: VarOneServer.java    From varOne with MIT License 6 votes vote down vote up
private static WebAppContext setupWebAppContext(VarOneConfiguration conf) {
	WebAppContext webApp = new WebAppContext();
    webApp.setContextPath(conf.getServerContextPath());
    File warPath = new File(conf.getString(ConfVars.VARONE_WAR));
    if (warPath.isDirectory()) {
      webApp.setResourceBase(warPath.getPath());
      webApp.setParentLoaderPriority(true);
    } else {
      // use packaged WAR
      webApp.setWar(warPath.getAbsolutePath());
      File warTempDirectory = new File(conf.getRelativeDir(ConfVars.VARONE_WAR_TEMPDIR));
      warTempDirectory.mkdir();
      LOG.info("VarOneServer Webapp path: {}" + warTempDirectory.getPath());
      webApp.setTempDirectory(warTempDirectory);
    }
    // Explicit bind to root
    webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
    return webApp;
}
 
Example 6
Source File: SubmarineServer.java    From submarine with Apache License 2.0 5 votes vote down vote up
private static void setupNotebookServer(WebAppContext webapp,
    SubmarineConfiguration conf, ServiceLocator serviceLocator) {
  String maxTextMessageSize = conf.getWebsocketMaxTextMessageSize();
  final ServletHolder servletHolder =
      new ServletHolder(serviceLocator.getService(NotebookServer.class));
  servletHolder.setInitParameter("maxTextMessageSize", maxTextMessageSize);

  final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  webapp.addServlet(servletHolder, "/ws/*");
}
 
Example 7
Source File: HttpServer2.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private static WebAppContext createWebAppContext(Builder b,
    AccessControlList adminsAcl, final String appDir) {
  WebAppContext ctx = new WebAppContext();
  ctx.setDefaultsDescriptor(null);
  ServletHolder holder = new ServletHolder(new DefaultServlet());
  Map<String, String> params = ImmutableMap.<String, String>builder()
      .put("acceptRanges", "true")
      .put("dirAllowed", "false")
      .put("gzip", "true")
      .put("useFileMappedBuffer", "true")
      .build();
  holder.setInitParameters(params);
  ctx.setWelcomeFiles(new String[] {"index.html"});
  ctx.addServlet(holder, "/");
  ctx.setDisplayName(b.name);
  ctx.setContextPath("/");
  ctx.setWar(appDir + "/" + b.name);
  String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY);
  if (tempDirectory != null && !tempDirectory.isEmpty()) {
    ctx.setTempDirectory(new File(tempDirectory));
    ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory);
  }
  ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf);
  ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
  addNoCacheFilter(ctx);
  return ctx;
}
 
Example 8
Source File: JettyAppServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addRestEasyServlet(WebArchive archive, WebAppContext webAppContext) {
    log.debug("Starting Resteasy deployment");
    boolean addServlet = true;
    ServletHolder resteasyServlet = new ServletHolder("javax.ws.rs.core.Application", new HttpServlet30Dispatcher());

    String jaxrsApplication = getJaxRsApplication(archive);
    Set<Class<?>> pathAnnotatedClasses = getPathAnnotatedClasses(archive);

    if (jaxrsApplication != null) {
        log.debug("App has an Application.class: " + jaxrsApplication);
        resteasyServlet.setInitParameter("javax.ws.rs.Application", jaxrsApplication);
    } else if (!pathAnnotatedClasses.isEmpty()) {
        log.debug("App has @Path annotated classes: " + pathAnnotatedClasses);
        ResteasyDeployment deployment = new ResteasyDeployment();
        deployment.setApplication(new RestSamlApplicationConfig(pathAnnotatedClasses));
        webAppContext.setAttribute(ResteasyDeployment.class.getName(), deployment);
    } else {
        log.debug("An application doesn't have Application.class, nor @Path annotated classes. Skipping Resteasy initialization.");
        addServlet = false;
    }

    if (addServlet) {
        // this should be /* in general. However Jetty 9.2 (this is bug specific to this version),
        // can not merge two instances of javax.ws.rs.Application together (one from web.xml
        // and the other one added here). In 9.1 and 9.4 this works fine.
        // Once we stop supporting 9.2, this should replaced with /* and this comment should be removed.
        webAppContext.addServlet(resteasyServlet, "/");
    }
    log.debug("Finished Resteasy deployment");
}
 
Example 9
Source File: WebServerTestCase.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the web server on the default {@link #PORT}.
 * The given resourceBase is used to be the ROOT directory that serves the default context.
 * <p><b>Don't forget to stop the returned HttpServer after the test</b>
 *
 * @param resourceBase the base of resources for the default context
 * @param classpath additional classpath entries to add (may be null)
 * @param servlets map of {String, Class} pairs: String is the path spec, while class is the class
 * @throws Exception if the test fails
 */
protected void startWebServer(final String resourceBase, final String[] classpath,
        final Map<String, Class<? extends Servlet>> servlets) throws Exception {
    if (server_ != null) {
        throw new IllegalStateException("startWebServer() can not be called twice");
    }
    final Server server = buildServer(PORT);

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

    for (final Map.Entry<String, Class<? extends Servlet>> entry : servlets.entrySet()) {
        final String pathSpec = entry.getKey();
        final Class<? extends Servlet> servlet = entry.getValue();
        context.addServlet(servlet, pathSpec);
    }
    final WebAppClassLoader loader = new WebAppClassLoader(context);
    if (classpath != null) {
        for (final String path : classpath) {
            loader.addClassPath(path);
        }
    }
    context.setClassLoader(loader);
    server.setHandler(context);

    tryStart(PORT, server);
    server_ = server;
}
 
Example 10
Source File: SubmarineServer.java    From submarine with Apache License 2.0 5 votes vote down vote up
private static void setupRestApiContextHandler(WebAppContext webapp, SubmarineConfiguration conf) {
  final ServletHolder servletHolder =
      new ServletHolder(new org.glassfish.jersey.servlet.ServletContainer());

  servletHolder.setInitParameter("javax.ws.rs.Application", SubmarineServer.class.getName());
  servletHolder.setName("rest");
  servletHolder.setForcedPath("rest");
  webapp.setSessionHandler(new SessionHandler());
  webapp.addServlet(servletHolder, "/api/*");
}
 
Example 11
Source File: FakeGoServer.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void start() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    server.addConnector(connector);

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setCertAlias("cruise");
    sslContextFactory.setKeyStoreResource(Resource.newClassPathResource("testdata/fake-server-keystore"));
    sslContextFactory.setKeyStorePassword("serverKeystorepa55w0rd");

    ServerConnector secureConnnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(new HttpConfiguration())
    );
    server.addConnector(secureConnnector);

    WebAppContext wac = new WebAppContext(".", "/go");
    ServletHolder holder = new ServletHolder();
    holder.setServlet(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            resp.getOutputStream().println("Hello");
        }
    });
    wac.addServlet(holder, "/hello");
    addFakeAgentBinaryServlet(wac, "/admin/agent", TEST_AGENT, this);
    addFakeAgentBinaryServlet(wac, "/admin/agent-launcher.jar", TEST_AGENT_LAUNCHER, this);
    addFakeAgentBinaryServlet(wac, "/admin/agent-plugins.zip", TEST_AGENT_PLUGINS, this);
    addFakeAgentBinaryServlet(wac, "/admin/tfs-impl.jar", TEST_TFS_IMPL, this);
    addlatestAgentStatusCall(wac);
    addDefaultServlet(wac);
    server.setHandler(wac);
    server.setStopAtShutdown(true);
    server.start();

    port = connector.getLocalPort();
    securePort = secureConnnector.getLocalPort();
}
 
Example 12
Source File: HttpServer2.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static WebAppContext createWebAppContext(Builder b,
                                                 AccessControlList adminsAcl, final String appDir) {
  WebAppContext ctx = new WebAppContext();
  ctx.setDefaultsDescriptor(null);
  ServletHolder holder = new ServletHolder(new DefaultServlet());
  Map<String, String> params = ImmutableMap. <String, String> builder()
      .put("acceptRanges", "true")
      .put("dirAllowed", "false")
      .put("gzip", "true")
      .put("useFileMappedBuffer", "true")
      .build();
  holder.setInitParameters(params);
  ctx.setWelcomeFiles(new String[] {"index.html"});
  ctx.addServlet(holder, "/");
  ctx.setDisplayName(b.name);
  ctx.setContextPath("/");
  ctx.setWar(appDir + "/" + b.name);
  String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY);
  if (tempDirectory != null && !tempDirectory.isEmpty()) {
    ctx.setTempDirectory(new File(tempDirectory));
    ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory);
  }
  ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf);
  ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
  addNoCacheFilter(ctx);
  return ctx;
}
 
Example 13
Source File: JettyServer.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private void addDocsServlets(WebAppContext docsContext) {
    try {
        // Load the nifi-registry/docs directory
        final File docsDir = getDocsDir(docsLocation);

        // Create the servlet which will serve the static resources
        ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
        defaultHolder.setInitParameter("dirAllowed", "false");

        ServletHolder docs = new ServletHolder("docs", DefaultServlet.class);
        docs.setInitParameter("resourceBase", docsDir.getPath());
        docs.setInitParameter("dirAllowed", "false");

        docsContext.addServlet(docs, "/html/*");
        docsContext.addServlet(defaultHolder, "/");

        // load the rest documentation
        final File webApiDocsDir = new File(webApiContext.getTempDirectory(), "webapp/docs");
        if (!webApiDocsDir.exists()) {
            final boolean made = webApiDocsDir.mkdirs();
            if (!made) {
                throw new RuntimeException(webApiDocsDir.getAbsolutePath() + " could not be created");
            }
        }

        ServletHolder apiDocs = new ServletHolder("apiDocs", DefaultServlet.class);
        apiDocs.setInitParameter("resourceBase", webApiDocsDir.getPath());
        apiDocs.setInitParameter("dirAllowed", "false");

        docsContext.addServlet(apiDocs, "/rest-api/*");

        logger.info("Loading documents web app with context path set to " + docsContext.getContextPath());

    } catch (Exception ex) {
        logger.error("Unhandled Exception in createDocsWebApp: " + ex.getMessage());
        startUpFailure(ex);
    }
}
 
Example 14
Source File: EnterpriseJettyComponent.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void configureWebAppContext(WebAppContext webAppContext)
{
	super.configureWebAppContext(webAppContext);

    // the tenant servlet with alfresco managed authentication
    ServletHolder servletHolder = new ServletHolder(CmisAtomPubServlet.class);
    servletHolder.setInitParameter("callContextHandler", "org.apache.chemistry.opencmis.server.shared.BasicAuthCallContextHandler");
    webAppContext.addServlet(servletHolder, "/cmisatom/*");
}
 
Example 15
Source File: IdentityServer.java    From vipps-developers with MIT License 4 votes vote down vote up
private void addOpenIdConnectServlet(WebAppContext webAppContext, String pathSpec, String providerName, String openIdIssuerUrl) throws IOException {
    OpenIdConnectServlet servlet = new OpenIdConnectServlet();
    webAppContext.addServlet(new ServletHolder(servlet), pathSpec);
}
 
Example 16
Source File: HMaster.java    From hbase with Apache License 2.0 4 votes vote down vote up
private int putUpJettyServer() throws IOException {
  if (!conf.getBoolean("hbase.master.infoserver.redirect", true)) {
    return -1;
  }
  final int infoPort = conf.getInt("hbase.master.info.port.orig",
    HConstants.DEFAULT_MASTER_INFOPORT);
  // -1 is for disabling info server, so no redirecting
  if (infoPort < 0 || infoServer == null) {
    return -1;
  }
  if(infoPort == infoServer.getPort()) {
    return infoPort;
  }
  final String addr = conf.get("hbase.master.info.bindAddress", "0.0.0.0");
  if (!Addressing.isLocalAddress(InetAddress.getByName(addr))) {
    String msg =
        "Failed to start redirecting jetty server. Address " + addr
            + " does not belong to this host. Correct configuration parameter: "
            + "hbase.master.info.bindAddress";
    LOG.error(msg);
    throw new IOException(msg);
  }

  // TODO I'm pretty sure we could just add another binding to the InfoServer run by
  // the RegionServer and have it run the RedirectServlet instead of standing up
  // a second entire stack here.
  masterJettyServer = new Server();
  final ServerConnector connector = new ServerConnector(masterJettyServer);
  connector.setHost(addr);
  connector.setPort(infoPort);
  masterJettyServer.addConnector(connector);
  masterJettyServer.setStopAtShutdown(true);

  final String redirectHostname =
      StringUtils.isBlank(useThisHostnameInstead) ? null : useThisHostnameInstead;

  final RedirectServlet redirect = new RedirectServlet(infoServer, redirectHostname);
  final WebAppContext context = new WebAppContext(null, "/", null, null, null, null, WebAppContext.NO_SESSIONS);
  context.addServlet(new ServletHolder(redirect), "/*");
  context.setServer(masterJettyServer);

  try {
    masterJettyServer.start();
  } catch (Exception e) {
    throw new IOException("Failed to start redirecting jetty server", e);
  }
  return connector.getLocalPort();
}
 
Example 17
Source File: JettyLauncher.java    From JobX with Apache License 2.0 4 votes vote down vote up
@Override
public void start(boolean devMode, int port) throws Exception {

    Server server = new Server(new QueuedThreadPool(Constants.WEB_THREADPOOL_SIZE));

    WebAppContext appContext = new WebAppContext();
    String resourceBasePath = "";
    //开发者模式
    if (devMode) {
        String artifact = MavenUtils.get(Thread.currentThread().getContextClassLoader()).getArtifactId();
        resourceBasePath = artifact + "/src/main/webapp";
    }
    appContext.setDescriptor(resourceBasePath + "WEB-INF/web.xml");
    appContext.setResourceBase(resourceBasePath);
    appContext.setExtractWAR(true);

    //init param
    appContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    if (CommonUtils.isWindows()) {
        appContext.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
    }

    //for jsp support
    appContext.addBean(new JettyJspParser(appContext));
    appContext.addServlet(JettyJspServlet.class, "*.jsp");

    appContext.setContextPath("/");
    appContext.getServletContext().setExtendedListenerTypes(true);
    appContext.setParentLoaderPriority(true);
    appContext.setThrowUnavailableOnStartupException(true);
    appContext.setConfigurationDiscovered(true);
    appContext.setClassLoader(Thread.currentThread().getContextClassLoader());


    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);

    server.setConnectors(new Connector[]{connector});
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1024 * 1024 * 1024);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);
    server.setHandler(appContext);
    logger.info("[JobX] JettyLauncher starting...");
    server.start();
}
 
Example 18
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 19
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 20
Source File: JettyServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void addDocsServlets(WebAppContext docsContext) {
    try {
        // Load the nifi/docs directory
        final File docsDir = getDocsDir("docs");

        // load the component documentation working directory
        final File componentDocsDirPath = props.getComponentDocumentationWorkingDirectory();
        final File workingDocsDirectory = getWorkingDocsDirectory(componentDocsDirPath);

        // Load the API docs
        final File webApiDocsDir = getWebApiDocsDir();

        // Create the servlet which will serve the static resources
        ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
        defaultHolder.setInitParameter("dirAllowed", "false");

        ServletHolder docs = new ServletHolder("docs", DefaultServlet.class);
        docs.setInitParameter("resourceBase", docsDir.getPath());
        docs.setInitParameter("dirAllowed", "false");

        ServletHolder components = new ServletHolder("components", DefaultServlet.class);
        components.setInitParameter("resourceBase", workingDocsDirectory.getPath());
        components.setInitParameter("dirAllowed", "false");

        ServletHolder restApi = new ServletHolder("rest-api", DefaultServlet.class);
        restApi.setInitParameter("resourceBase", webApiDocsDir.getPath());
        restApi.setInitParameter("dirAllowed", "false");

        docsContext.addServlet(docs, "/html/*");
        docsContext.addServlet(components, "/components/*");
        docsContext.addServlet(restApi, "/rest-api/*");

        docsContext.addServlet(defaultHolder, "/");

        logger.info("Loading documents web app with context path set to " + docsContext.getContextPath());

    } catch (Exception ex) {
        logger.error("Unhandled Exception in createDocsWebApp: " + ex.getMessage());
        startUpFailure(ex);
    }
}