Java Code Examples for org.eclipse.jetty.server.handler.ResourceHandler#setWelcomeFiles()

The following examples show how to use org.eclipse.jetty.server.handler.ResourceHandler#setWelcomeFiles() . 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: ConfigurationServerDriver.java    From candybean with GNU Affero General Public License v3.0 7 votes vote down vote up
public static void main (String args[]) throws Exception{
	logger.info("Starting JETTY server");
    Server server = new Server(8080);
    
       ResourceHandler resourceHandler = new ResourceHandler();
       resourceHandler.setDirectoriesListed(true);
       resourceHandler.setWelcomeFiles(new String[]{ "resources/html/configure.html" });
       resourceHandler.setResourceBase(".");
       
       ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
       resourceHandler.setWelcomeFiles(new String[]{ "resources/html/configure.html" });
       resourceHandler.setResourceBase(".");
       context.addServlet(new ServletHolder(new ConfigurationServlet()),"/cfg");
       context.addServlet(new ServletHolder(new SaveConfigurationServlet()),"/cfg/save");
       context.addServlet(new ServletHolder(new LoadConfigurationServlet()),"/cfg/load");
       
       HandlerList handlers = new HandlerList();
       handlers.setHandlers(new Handler[] { resourceHandler, context });
       server.setHandler(handlers);

       server.start();
	logger.info("Configuration server started at: http://localhost:8080/cfg");
       server.join();
}
 
Example 2
Source File: GraphQlServer.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  // Embedded Jetty server
  Server server = new Server(HTTP_PORT);
  ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setWelcomeFiles(new String[] {"index.html"});
  resourceHandler.setDirectoriesListed(true);
  // resource base is relative to the WORKSPACE file
  resourceHandler.setResourceBase("./src/main/resources");
  HandlerList handlerList = new HandlerList();
  handlerList.setHandlers(
      new Handler[] {resourceHandler, new GraphQlHandler(), new DefaultHandler()});
  server.setHandler(handlerList);
  server.start();
  logger.info("Server running on port " + HTTP_PORT);
  server.join();
}
 
Example 3
Source File: HttpMain.java    From graphql-java-http-example with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    //
    // This example uses Jetty as an embedded HTTP server
    Server server = new Server(PORT);
    //
    // In Jetty, handlers are how your get called backed on a request
    HttpMain main_handler = new HttpMain();

    // this allows us to server our index.html and GraphIQL JS code
    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(false);
    resource_handler.setWelcomeFiles(new String[]{"index.html"});
    resource_handler.setResourceBase("./src/main/resources/httpmain");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler, main_handler});
    server.setHandler(handlers);

    server.start();

    server.join();
}
 
Example 4
Source File: JettyAppServer.java    From selenium with Apache License 2.0 6 votes vote down vote up
protected ServletContextHandler addResourceHandler(String contextPath, Path resourceBase) {
  ServletContextHandler context = new ServletContextHandler();

  ResourceHandler staticResource = new ResourceHandler();
  staticResource.setDirectoriesListed(true);
  staticResource.setWelcomeFiles(new String[] { "index.html" });
  staticResource.setResourceBase(resourceBase.toAbsolutePath().toString());
  MimeTypes mimeTypes = new MimeTypes();
  mimeTypes.addMimeMapping("appcache", "text/cache-manifest");
  staticResource.setMimeTypes(mimeTypes);

  context.setContextPath(contextPath);
  context.setAliasChecks(Arrays.asList(new ApproveAliases(), new AllowSymLinkAliasChecker()));

  HandlerList allHandlers = new HandlerList();
  allHandlers.addHandler(staticResource);
  allHandlers.addHandler(context.getHandler());
  context.setHandler(allHandlers);

  handlers.addHandler(context);

  return context;
}
 
Example 5
Source File: Application.java    From vk-java-sdk with MIT License 6 votes vote down vote up
private static void initServer(Properties properties) throws Exception {
    Integer port = Integer.valueOf(properties.getProperty("server.port"));
    String host = properties.getProperty("server.host");

    Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
    String clientSecret = properties.getProperty("client.secret");

    HandlerCollection handlers = new HandlerCollection();

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());

    VkApiClient vk = new VkApiClient(new HttpTransportClient());
    handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});

    Server server = new Server(port);
    server.setHandler(handlers);

    server.start();
    server.join();
}
 
Example 6
Source File: JettyServer.java    From jbake with MIT License 5 votes vote down vote up
/**
 * Run Jetty web server serving out supplied path on supplied port
 *
 * @param path Base directory for resourced to be served
 * @param port Required server port
 */
public void run(String path, String port) {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(Integer.parseInt(port));
    server.addConnector(connector);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[]{"index.html"});

    resource_handler.setResourceBase(path);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler, new DefaultHandler()});
    server.setHandler(handlers);

    LOGGER.info("Serving out contents of: [{}] on http://localhost:{}/", path, port);
    LOGGER.info("(To stop server hit CTRL-C)");

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        LOGGER.error("unable to start server", e);
    }
}
 
Example 7
Source File: TestServer.java    From healenium-web with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(ExtensionContext context) {
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newClassPathResource(folder));
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    resourceHandler.setDirectoriesListed(true);
    server = new Server(port);
    HandlerList handlers = new HandlerList(resourceHandler, new DefaultHandler());
    server.setHandler(handlers);
    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: RemoteRepositoryConnectivityCheckTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
protected Server buildStaticServer( Path path )
{
    Server repoServer = new Server(  );

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed( true );
    resourceHandler.setWelcomeFiles( new String[]{ "index.html" } );
    resourceHandler.setResourceBase( path.toAbsolutePath().toString() );

    HandlerList handlers = new HandlerList();
    handlers.setHandlers( new Handler[]{ resourceHandler, new DefaultHandler() } );
    repoServer.setHandler( handlers );

    return repoServer;
}
 
Example 9
Source File: RunnerRun.java    From stagen with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final File baseDir) throws IOException, ExecutorException {
    // Generate site:
    clean.run(baseDir);
    gen.run(baseDir);
    
    // Start monitoring service:
    startMonitoring(baseDir);
    
    // Start server:
    try {
        LOG.log(Level.INFO, "Starting HTTP server at port: {0}", cmd.port);
        Server server = new Server(cmd.port);
        
        ResourceHandler rh = new ResourceHandler();
        rh.setDirectoriesListed(true);
        rh.setWelcomeFiles(new String[]{"index.html"});
        rh.setResourceBase(Constants.getOutDir(baseDir).getPath());
        
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[]{rh, new DefaultHandler()});
        server.setHandler(handlers);
        
        server.start();
        server.join();
    }
    catch(Exception ex) {
        throw new ExecutorException(ex);
    }
}
 
Example 10
Source File: GerritRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
public String startJetty(Class<? extends HttpServlet> loginServletClass) throws Exception {
    Server server = new Server(0);

    ResourceHandler resourceHandler = new ResourceHandler();
    MimeTypes mimeTypes = new MimeTypes();
    mimeTypes.addMimeMapping("json", "application/json");
    resourceHandler.setMimeTypes(mimeTypes);
    URL url = this.getClass().getResource(".");
    resourceHandler.setBaseResource(new FileResource(url));
    resourceHandler.setWelcomeFiles(new String[] {"changes.json", "projects.json", "account.json"});

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.addServlet(loginServletClass, "/login/");

    ServletContextHandler basicAuthContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
    basicAuthContextHandler.setSecurityHandler(basicAuth("foo", "bar", "Gerrit Auth"));
    basicAuthContextHandler.setContextPath("/a");

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {
        servletContextHandler,
        resourceHandler,
        basicAuthContextHandler
    });
    server.setHandler(handlers);

    server.start();

    Connector connector = server.getConnectors()[0];
    String host = "localhost";
    int port = connector.getLocalPort();
    return String.format("http://%s:%s", host, port);
}
 
Example 11
Source File: AdminWebServer.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private ResourceHandler buildStaticResourceHandler() {
  ResourceHandler staticResourceHandler = new ResourceHandler();
  staticResourceHandler.setDirectoriesListed(true);
  staticResourceHandler.setWelcomeFiles(new String[] { "index.html" });

  String staticDir = getClass().getClassLoader().getResource("static").toExternalForm();

  staticResourceHandler.setResourceBase(staticDir);
  return staticResourceHandler;
}
 
Example 12
Source File: ReportOpen.java    From allure1 with Apache License 2.0 5 votes vote down vote up
/**
 * Set up server for report directory.
 */
private Server setUpServer() {
    Server server = new Server(port);
    ResourceHandler handler = new ResourceHandler();
    handler.setDirectoriesListed(true);
    handler.setWelcomeFiles(new String[]{"index.html"});
    handler.setResourceBase(getReportDirectoryPath().toAbsolutePath().toString());
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});
    server.setStopAtShutdown(true);
    server.setHandler(handlers);
    return server;
}
 
Example 13
Source File: WebServer.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Server setupServer() throws Exception {
    // String webDir = "target/classes/webui";
    // String webDir = "src/main/resources/webui";
    String webDir = WebServer.class.getClassLoader().getResource("webui").toExternalForm();
    log.info("Base webdir is {}", webDir);

    int httpPort = ConfigFactory.load().getInt("resource-reporting.visualization.webui-port");
    log.info("Resource reporting web ui port is ", httpPort);

    // Create Jetty server
    Server server = new Server(httpPort);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] { "filter.html" });
    resource_handler.setResourceBase(webDir);

    WebSocketHandler wsHandler = new WebSocketHandler.Simple(PubSubProxyWebSocket.class);

    ContextHandler context = new ContextHandler();
    context.setContextPath("/ws");
    context.setHandler(wsHandler);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { context, resource_handler, new DefaultHandler() });

    server.setHandler(handlers);

    ClusterResources.subscribeToAll(callback);

    return server;
}
 
Example 14
Source File: PhrasalService.java    From phrasal with GNU General Public License v3.0 4 votes vote down vote up
/**
   * Start the service.
   * 
   * @param args
   */
  public static void main(String[] args) {
    Properties options = StringUtils.argsToProperties(args, optionArgDefs());
    int port = PropertiesUtils.getInt(options, "p", DEFAULT_HTTP_PORT);
    boolean loadMockServlet = PropertiesUtils.getBool(options, "m", false);
    boolean localHost = PropertiesUtils.getBool(options, "l", false);
    String uiFile = options.getProperty("u", "debug.html");
    String resourcePath = options.getProperty("r", ".");

    // Parse arguments
    String argList = options.getProperty("",null);
    String[] parsedArgs = argList == null ? null : argList.split("\\s+");
    if (parsedArgs == null || parsedArgs.length != 1) {
      System.out.println(usage());
      System.exit(-1);
    }
    String phrasalIniFile = parsedArgs[0];
    
    // Setup the jetty server
    Server server = new Server();

    // Jetty 8 way of configuring the server
//    Connector connector = new SelectChannelConnector();
//    connector.setPort(port);
//    server.addConnector(connector);

//  Jetty9 way of configuring the server
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    server.addConnector(connector);

    if (localHost) {
      connector.setHost(DEBUG_URL);
    }
    
    // Setup the servlet context
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
 
    // Add Phrasal servlet
    PhrasalServlet servlet = loadMockServlet ? new PhrasalServlet() : new PhrasalServlet(phrasalIniFile);
    context.addServlet(new ServletHolder(servlet), SERVLET_ROOT);

    // TODO(spenceg): gzip compression causes an encoding problem for unicode characters
    // on the client. Not sure if the compression or decompression is the problem.
//    EnumSet<DispatcherType> dispatches = EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC);
//    context.addFilter(new FilterHolder(new IncludableGzipFilter()), "/t", dispatches);

    // Add debugging web-page
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setWelcomeFiles(new String[]{ uiFile });
    resourceHandler.setResourceBase(resourcePath);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { resourceHandler, context });
    server.setHandler(handlers);
    
    // Start the service
    try {
      logger.info("Starting PhrasalService on port: " + String.valueOf(port));
      server.start();
      server.join();
    } catch (Exception e) {
      logger.error("Servlet crashed. Service shutting down.");
      e.printStackTrace();
    }
  }
 
Example 15
Source File: ServerLauncher.java    From xtext-web with Eclipse Public License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	Server server = new Server(new InetSocketAddress("localhost", 8080));
	RewriteHandler rewriteHandler = new RewriteHandler();
	server.setHandler(rewriteHandler);
	RewriteRegexRule rule = new RewriteRegexRule();
	rule.setRegex("/xtext/@xtext-version-placeholder@/(.*)");
	rule.setReplacement("/xtext/$1");
	rule.setTerminating(false);
	rewriteHandler.addRule(rule);
	HandlerList handlerList = new HandlerList();
	ResourceHandler resourceHandler1 = new ResourceHandler();
	resourceHandler1.setResourceBase("src/main/webapp");
	resourceHandler1.setWelcomeFiles(new String[] { "index.html" });
	ResourceHandler resourceHandler2 = new ResourceHandler();
	resourceHandler2.setResourceBase("../org.eclipse.xtext.web/src/main/css");
	WebAppContext webAppContext = new WebAppContext();
	webAppContext.setResourceBase("../org.eclipse.xtext.web/src/main/js");
	webAppContext.setContextPath("/");
	webAppContext.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebXmlConfiguration(),
			new WebInfConfiguration(), new MetaInfConfiguration() });
	webAppContext.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN,
			".*/org\\.eclipse\\.xtext\\.web.*,.*/org.webjars.*");

	handlerList.setHandlers(new Handler[] { resourceHandler1, resourceHandler2, webAppContext });
	rewriteHandler.setHandler(handlerList);
	Slf4jLog log = new Slf4jLog(ServerLauncher.class.getName());
	try {
		server.start();
		log.info("Server started " + server.getURI() + "...");
		new Thread() {

			public void run() {
				try {
					log.info("Press enter to stop the server...");
					int key = System.in.read();
					if (key != -1) {
						server.stop();
					} else {
						log.warn(
								"Console input is not available. In order to stop the server, you need to cancel process manually.");
					}
				} catch (Exception e) {
					log.warn(e);
				}
			}

		}.start();
		server.join();
	} catch (Exception exception) {
		log.warn(exception.getMessage());
		System.exit(1);
	}
}
 
Example 16
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 17
Source File: DemoApp.java    From bromium with MIT License 4 votes vote down vote up
public void runOnSeparateThread() throws Exception {
    for (String resource: resourcesToBeExtractedInDirectory) {
        InputStream resourceAsStream = this.getClass().getResourceAsStream("/" + resource);
        File outputFile = Paths.get(baseOutputDirectory.getAbsolutePath(), resource).toFile();
        FileOutputStream fileOutputStream =  FileUtils.openOutputStream(outputFile);
        IOUtils.copy(resourceAsStream, fileOutputStream);
    }

    ResourceConfig config = new ResourceConfig();
    config.packages("com.hribol.bromium.demo.app");
    ServletHolder servlet = new ServletHolder(new ServletContainer(config));

    server = new Server(0);

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase(baseOutputDirectory.getAbsolutePath());
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] {
            "index.html"
    });

    ServletContextHandler context = new ServletContextHandler(server, "/*");
    context.addServlet(servlet, "/*");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {
            resourceHandler,
            context
    });
    server.setHandler(handlers);

    server.start();
    this.port = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
    logger.info("Server started on port " + port);

    new Thread(() -> {
        try {
            server.join();
        } catch (InterruptedException e) {
            logger.info("Interrupted!", e);
        }
    }).start();
}
 
Example 18
Source File: SentryWebServer.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
public SentryWebServer(List<EventListener> listeners, int port, Configuration conf) {
  this.port = port;
  server = new Server(port);
  ServletContextHandler servletContextHandler = new ServletContextHandler();
  ServletHolder servletHolder = new ServletHolder(AdminServlet.class);
  servletContextHandler.addServlet(servletHolder, "/*");

  for(EventListener listener:listeners) {
    servletContextHandler.addEventListener(listener);
  }

  ServletHolder confServletHolder = new ServletHolder(ConfServlet.class);
  servletContextHandler.addServlet(confServletHolder, "/conf");
  servletContextHandler.getServletContext()
      .setAttribute(ConfServlet.CONF_CONTEXT_ATTRIBUTE, conf);

  ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setDirectoriesListed(true);
  URL url = this.getClass().getResource(RESOURCE_DIR);
  try {
    resourceHandler.setBaseResource(Resource.newResource(url.toString()));
  } catch (IOException e) {
    LOGGER.error("Got exception while setBaseResource for Sentry Service web UI", e);
  }
  resourceHandler.setWelcomeFiles(new String[]{WELCOME_PAGE});
  ContextHandler contextHandler= new ContextHandler();
  contextHandler.setHandler(resourceHandler);

  ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
  contextHandlerCollection.setHandlers(new Handler[]{contextHandler, servletContextHandler});

  String authMethod = conf.get(ServerConfig.SENTRY_WEB_SECURITY_TYPE);
  if (!ServerConfig.SENTRY_WEB_SECURITY_TYPE_NONE.equals(authMethod)) {
    /**
     * SentryAuthFilter is a subclass of AuthenticationFilter and
     * AuthenticationFilter tagged as private and unstable interface:
     * While there are not guarantees that this interface will not change,
     * it is fairly stable and used by other projects (ie - Oozie)
     */
    FilterHolder filterHolder = servletContextHandler.addFilter(SentryAuthFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    filterHolder.setInitParameters(loadWebAuthenticationConf(conf));
  }

  server.setHandler(contextHandlerCollection);
}
 
Example 19
Source File: VertxPluginRegistryTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * Build and start a fake local Maven Repository server based on Jetty
 *
 * @throws Exception
 */
@BeforeClass
public static void BuildLocalMavenRepo() throws Exception {
    //This function create a Localhost fake Maven Repository, hosting a single Test Plugin

    //Get Test plugin file
    File sourcePlugin = new File("src/test/resources/io/apiman/gateway/platforms/vertx3/engine/plugin-with-policyDefs.war");
    if (!sourcePlugin.exists()) {
        throw new Exception("Failed to find test plugin war at: " + sourcePlugin.getAbsolutePath());
    }

    //Create Local Maven Repository folder
    File repoFolder = Files.createTempDirectory("MockedMavenRepo").toFile();

    //Define Test plugin coordinates
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(testPluginCoordinates);

    //Build Test Plugin path in local Maven Repository folder
    File PluginFile = new File(repoFolder, PluginUtils.getMavenPath(coordinates));
    PluginFile.getParentFile().mkdirs();

    //Copy Test Plugin war into repository
    FileUtils.copyFile(sourcePlugin, PluginFile);

    //Create local Maven Repository Web Server
    mavenServer = new Server();
    ServerConnector connector = new ServerConnector(mavenServer);
    // auto-bind to available port
    connector.setPort(0);
    connector.setHost("0.0.0.0");
    mavenServer.addConnector(connector);

    //Add classic ressource handler
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    PathResource pathResource = new PathResource(repoFolder);
    resourceHandler.setBaseResource(pathResource);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resourceHandler, new DefaultHandler()});
    mavenServer.setHandler(handlers);

    //Start local Maven Repository Server
    mavenServer.start();

    // Determine Base URI for Server
    String host = connector.getHost();
    if (host == null || host == "0.0.0.0") host = "127.0.0.1";
    int port = connector.getLocalPort();
    mavenServerUri = new URI(String.format("http://%s:%d/", host, port));
}
 
Example 20
Source File: DashBoardServer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 3 votes vote down vote up
ContextHandler getResourceHandler() {
    ContextHandler root = new ContextHandler();
    root.setContextPath("/*");

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);

    resourceHandler.setWelcomeFiles(new String[]{HOME});
    resourceHandler.setResourceBase(R_BASE);

    root.setHandler(resourceHandler);

    return root;

}