Пример #1
0
  @Test
  public void testResourceBase() throws Exception {
    testdir.ensureEmpty();
    File resBase = testdir.getFile("docroot");
    FS.ensureDirExists(resBase);
    File foobar = new File(resBase, "foobar.txt");
    File link = new File(resBase, "link.txt");
    createFile(foobar, "Foo Bar");

    String resBasePath = resBase.getAbsolutePath();

    ServletHolder defholder = context.addServlet(DefaultServlet.class, "/");
    defholder.setInitParameter("resourceBase", resBasePath);
    defholder.setInitParameter("gzip", "false");

    String response;

    response = connector.getResponses("GET /context/foobar.txt HTTP/1.0\r\n\r\n");
    assertResponseContains("Foo Bar", response);

    if (!OS.IS_WINDOWS) {
      Files.createSymbolicLink(link.toPath(), foobar.toPath());
      response = connector.getResponses("GET /context/link.txt HTTP/1.0\r\n\r\n");
      assertResponseContains("404", response);

      context.addAliasCheck(new ContextHandler.ApproveAliases());

      response = connector.getResponses("GET /context/link.txt HTTP/1.0\r\n\r\n");
      assertResponseContains("Foo Bar", response);
    }
  }
 @Override
 public Handler createHandler() throws ConfigurationException {
   // set up jersey servlet
   ResourceConfig config = new ResourceConfig();
   // we package everything into a runnable jar using OneJAR, which provides its own class loader.
   // as the result, Jersey classpath scanning won't work properly for now.
   // hopefully this can be fixed soon. right now we need to specify classes.
   config.register(Echo.class);
   config.register(LogService.class);
   config.register(PageService.class);
   config.register(TaskService.class);
   // binder for HK2 to inject the controller to Jersey resource instances
   config.register(
       new AbstractBinder() {
         @Override
         protected void configure() {
           bind(controller).to(Controller.class);
         }
       });
   ServletContainer container = new ServletContainer(config);
   ServletContextHandler handler = new ServletContextHandler();
   handler.setContextPath("/DownloaderPool");
   handler.addServlet(new ServletHolder(container), "/*");
   return handler;
 }
  public GatewayServer(
      String contextPath,
      String externalServletPath,
      String gatewayServletPath,
      TargetIdRetriever targetIdRetriever) {
    HandlerCollection handlers = new HandlerCollection();
    setHandler(handlers);
    context = new ServletContextHandler(handlers, contextPath, ServletContextHandler.SESSIONS);

    // Setup the gateway
    gateway = createGateway();

    // Setup external servlet
    ExternalServlet externalServlet = new ExternalServlet(gateway, targetIdRetriever);
    externalServletHolder = new ServletHolder(externalServlet);
    context.addServlet(externalServletHolder, externalServletPath + "/*");
    logger.debug("External servlet mapped to {}/*", externalServletPath);

    // Setup gateway servlet
    ConnectorServlet gatewayServlet = new ConnectorServlet(gateway);
    connectorServletHolder = new ServletHolder(gatewayServlet);
    connectorServletHolder.setInitParameter("clientTimeout", "15000");
    context.addServlet(connectorServletHolder, gatewayServletPath + "/*");
    logger.debug("Gateway servlet mapped to {}/*", gatewayServletPath);
  }
Пример #4
0
  private void init() {
    logger.info("Initializing Broker Http Metrics Reporter");

    InetSocketAddress inetSocketAddress = new InetSocketAddress(bindAddress, port);

    server = new Server(inetSocketAddress);

    ServletContextHandler servletContextHandler = new ServletContextHandler();

    servletContextHandler.setContextPath("/");

    servletContextHandler.addEventListener(new MetricsServletContextListener());
    servletContextHandler.addEventListener(new JVMMetricsServletContextListener());
    servletContextHandler.addEventListener(new HealthCheckServletContextListener());

    servletContextHandler.addServlet(new ServletHolder(new HermesServlet()), "/hermes");
    servletContextHandler.addServlet(new ServletHolder(new MetricsServlet()), "/metrics/metrics");
    servletContextHandler.addServlet(
        new ServletHolder(new ThreadDumpServlet()), "/metrics/threads");
    servletContextHandler.addServlet(
        new ServletHolder(new HealthCheckServlet()), "/metrics/healthcheck");
    servletContextHandler.addServlet(new ServletHolder(new PingServlet()), "/metrics/ping");

    server.setHandler(servletContextHandler);
    logger.info("Finished initializing Broker Http Metrics Reporter");
  }
  @Test
  public void testResponseHeadersAreNotRemoved() throws Exception {
    prepareProxy();
    proxyContext.stop();
    final String headerName = "X-Test";
    final String headerValue = "test-value";
    proxyContext.addFilter(
        new FilterHolder(
            new Filter() {
              @Override
              public void init(FilterConfig filterConfig) throws ServletException {}

              @Override
              public void doFilter(
                  ServletRequest request, ServletResponse response, FilterChain chain)
                  throws IOException, ServletException {
                ((HttpServletResponse) response).addHeader(headerName, headerValue);
                chain.doFilter(request, response);
              }

              @Override
              public void destroy() {}
            }),
        "/*",
        EnumSet.of(DispatcherType.REQUEST));
    proxyContext.start();
    prepareServer(new EmptyHttpServlet());

    HttpClient client = prepareClient();
    ContentResponse response =
        client.newRequest("localhost", serverConnector.getLocalPort()).send();

    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals(headerValue, response.getHeaders().get(headerName));
  }
Пример #6
0
  public void start(Injector injector) throws Exception {
    ResourceHandler resHandler = new ResourceHandler();
    resHandler.setDirectoriesListed(false);
    resHandler.setWelcomeFiles(new String[] {"index.html"});
    resHandler.setResourceBase(args.get("jetty.resourcebase", "./src/main/webapp"));

    server = new Server();
    // getSessionHandler and getSecurityHandler should always return null
    ServletContextHandler servHandler =
        new ServletContextHandler(
            ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
    servHandler.setContextPath("/");

    servHandler.addServlet(new ServletHolder(new InvalidRequestServlet()), "/*");

    FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
    servHandler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

    SelectChannelConnector connector0 = new SelectChannelConnector();
    int httpPort = args.getInt("jetty.port", 8989);
    String host = args.get("jetty.host", "");
    connector0.setPort(httpPort);
    if (!host.isEmpty()) connector0.setHost(host);

    server.addConnector(connector0);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resHandler, servHandler});
    server.setHandler(handlers);
    server.start();
    logger.info("Started server at HTTP " + host + ":" + httpPort);
  }
  @Before
  public void init() throws Exception {
    server = new Server();

    connector = new LocalConnector(server);
    connector
        .getConnectionFactory(HttpConfiguration.ConnectionFactory.class)
        .getHttpConfiguration()
        .setSendServerVersion(false);

    context = new ServletContextHandler();
    context.setContextPath("/context");
    context.setWelcomeFiles(new String[] {"index.html", "index.jsp", "index.htm"});

    server.setHandler(context);
    server.addConnector(connector);

    testdir.ensureEmpty();
    File resBase = testdir.getFile("docroot");
    FS.ensureDirExists(resBase);
    File data = new File(resBase, "data.txt");
    createFile(data, DATA);
    String resBasePath = resBase.getAbsolutePath();

    ServletHolder defholder = context.addServlet(DefaultServlet.class, "/");
    defholder.setInitParameter("acceptRanges", "true");
    defholder.setInitParameter("resourceBase", resBasePath);

    server.start();
  }
  @Test
  public void testFallThrough() throws Exception {
    HandlerList list = new HandlerList();
    _server.setHandler(list);

    ServletContextHandler root =
        new ServletContextHandler(list, "/", ServletContextHandler.SESSIONS);

    ServletHandler servlet = root.getServletHandler();
    servlet.setEnsureDefaultServlet(false);
    servlet.addServletWithMapping(HelloServlet.class, "/hello/*");

    list.addHandler(
        new AbstractHandler() {
          @Override
          public void handle(
              String target,
              Request baseRequest,
              HttpServletRequest request,
              HttpServletResponse response)
              throws IOException, ServletException {
            response.sendError(404, "Fell Through");
          }
        });

    _server.start();

    String response = _connector.getResponses("GET /hello HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.containsString("200 OK"));

    response = _connector.getResponses("GET /other HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.containsString("404 Fell Through"));
  }
  public static void main(String[] args) {
    int port = 8889;

    JettyImageServerServlet service = new JettyImageServerServlet();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(new ServletHolder(service), "/*");
    Collection<String> sharedDisplayables = new ArrayList<String>();
    String base = "/Users/niko/TileSources/displayables/";
    String[] disps =
        new String[] {
          "tpg-plan-centre-9-decembre-12-4-1.disp",
          "tpg-plan-peripherique-9-decembre-12-2.disp",
          "tpg-plan-schematique-9-decembre-12-3.disp"
        };
    for (String d : disps) {
      sharedDisplayables.add(base + d);
    }
    service.setSharedDisplayables(sharedDisplayables);
    Server server = new Server(port);
    server.setHandler(context);
    try {
      server.start();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(-1);
    }
  }
  @BeforeClass
  public static void startServer() throws Exception {
    server = new Server();

    ServerConnector connector = new ServerConnector(server);
    connector.setIdleTimeout(30000);
    server.addConnector(connector);

    ServletContextHandler context = new ServletContextHandler(server, "/");

    // CometD servlet
    ServletHolder cometdServletHolder = new ServletHolder(CometDServlet.class);
    cometdServletHolder.setInitParameter("timeout", "10000");
    cometdServletHolder.setInitParameter("multiSessionInterval", "2000");
    cometdServletHolder.setInitOrder(1);

    String cometdServletPath = "/cometd";
    context.addServlet(cometdServletHolder, cometdServletPath + "/*");

    server.start();
    int port = connector.getLocalPort();
    cometdURL = "http://localhost:" + port + cometdServletPath;

    httpClient = new HttpClient();
    httpClient.start();
  }
Пример #11
0
  /**
   * Creates a new environment.
   *
   * @param name the name of the application
   * @param objectMapper the {@link ObjectMapper} for the application
   */
  public Environment(
      String name,
      ObjectMapper objectMapper,
      Validator validator,
      MetricRegistry metricRegistry,
      ClassLoader classLoader) {
    this.name = name;
    this.objectMapper = objectMapper;
    this.metricRegistry = metricRegistry;
    this.healthCheckRegistry = new HealthCheckRegistry();
    this.validator = validator;

    this.servletContext = new ServletContextHandler();
    servletContext.setClassLoader(classLoader);
    this.servletEnvironment = new ServletEnvironment(servletContext);

    this.adminContext = new ServletContextHandler();
    adminContext.setClassLoader(classLoader);
    this.adminEnvironment = new AdminEnvironment(adminContext, healthCheckRegistry);

    this.lifecycleEnvironment = new LifecycleEnvironment();

    final DropwizardResourceConfig jerseyConfig = new DropwizardResourceConfig(metricRegistry);
    this.jerseyServletContainer = new JerseyContainerHolder(new ServletContainer(jerseyConfig));
    this.jerseyEnvironment = new JerseyEnvironment(jerseyServletContainer, jerseyConfig);
  }
  @BeforeClass
  public static void startServer() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(0);
    server.addConnector(connector);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    ServerContainer container = WebSocketServerContainerInitializer.configureContext(context);
    container.addEndpoint(CaptureHeadersSocket.class);
    container.addEndpoint(EmptySocket.class);
    container.addEndpoint(NoExtensionsSocket.class);

    server.start();
    String host = connector.getHost();
    if (host == null) {
      host = "localhost";
    }
    int port = connector.getLocalPort();
    baseServerUri = new URI(String.format("ws://%s:%d/", host, port));
    LOG.debug("Server started on {}", baseServerUri);
  }
Пример #13
0
  public static void main(String[] args) throws Exception {

    Server server = new Server(Integer.valueOf(System.getenv("PORT")));
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    context.addServlet(
        new ServletHolder(
            new HttpServlet() {
              protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                  throws ServletException, IOException {
                resp.getWriter()
                    .print(
                        "<h1>umlet-github web service</h1>"
                            + "<p>"
                            + "<a href=\"https://github.com/CalumJEadie/umlet-github/\">"
                            + "https://github.com/CalumJEadie/umlet-github/"
                            + "</a>"
                            + "</p>");
              }
            }),
        "/");

    context.addServlet(new ServletHolder(new UmletGithub()), "/convert/uxf/svg/");

    server.start();
    server.join();
  }
Пример #14
0
 public void endServer() {
   if (updateTask != null) {
     updateTask.cancel();
   }
   if (context != null) {
     try {
       context.stop();
       if (!context.isStopped()) {
         hcw.getDataBukkit().writeError("Context failed to stop.");
       }
     } catch (Exception e) {
       hcw.getDataBukkit().writeError(e);
     }
   }
   if (server != null) {
     try {
       server.stop();
       if (!server.isStopped()) {
         hcw.getDataBukkit().writeError("Server failed to stop.");
       }
     } catch (Exception e) {
       hcw.getDataBukkit().writeError(e);
     }
   }
 }
Пример #15
0
  public static void main(String[] args) throws Exception {
    if (args.length < 1) {
      throw new RuntimeException("Expected >=1 command line arguments");
    }
    String sourceDir = args[0];
    logger.log(Level.INFO, "Source directory: " + sourceDir);

    int port = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
    Server server = new Server(port);

    ServletContextHandler servletHandler =
        new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletHandler.setContextPath("/");
    servletHandler.addServlet(ProxyingServlet.class, "/mirror");
    servletHandler.addServlet(AwtThumbnailServlet.class, "/thumb");
    servletHandler.addServlet(OAuthServlet.class, "/oauth");

    final ResourceHandler fileServlet = new ResourceHandler();
    fileServlet.setResourceBase(sourceDir);
    fileServlet.setDirectoriesListed(true);
    // Don't let the corp proxy cache content served out of the filesystem,
    // since we expect this may be used by a developer who's modifying it.
    fileServlet.setCacheControl("no-cache");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(
        new Handler[] {
          fileServlet, servletHandler, new DartHandler(sourceDir), new DefaultHandler()
        });
    server.setHandler(handlers);

    System.out.println("Sample dart apps served at:\n" + "http://localhost:" + port + "/samples/");
    server.start();
    server.join();
  }
Пример #16
0
  private Server createServer(final DummyServlet servlet) throws Exception {
    int port;
    try (ServerSocket socket = new ServerSocket()) {
      socket.bind(new InetSocketAddress(0));
      port = socket.getLocalPort();
    }
    baseUri = new URI("http", null, "127.0.0.1", port, null, null, null);

    HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setSendServerVersion(false);
    httpConfiguration.setSendXPoweredBy(false);

    server = new Server();

    ServerConnector httpConnector =
        new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));
    httpConnector.setPort(port);
    httpConnector.setName("http");
    server.addConnector(httpConnector);

    ServletHolder servletHolder = new ServletHolder(servlet);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.addServlet(servletHolder, "/*");
    HandlerCollection handlers = new HandlerCollection();
    handlers.addHandler(context);
    server.setHandler(handlers);
    return server;
  }
Пример #17
0
  protected Server startServer(int port) throws Exception {
    Server server = new Server();
    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    server.addConnector(connector);

    String contextPath = "";
    ServletContextHandler context = new ServletContextHandler(server, contextPath);

    // CometD servlet
    ServletHolder cometdServletHolder = new ServletHolder(CometdServlet.class);
    cometdServletHolder.setInitParameter("timeout", "10000");
    cometdServletHolder.setInitParameter("transports", WebSocketTransport.class.getName());
    if (Boolean.getBoolean("debugTests")) cometdServletHolder.setInitParameter("logLevel", "3");
    cometdServletHolder.setInitOrder(1);

    String cometdServletPath = "/cometd";
    context.addServlet(cometdServletHolder, cometdServletPath + "/*");

    server.start();
    String url = "http://localhost:" + connector.getLocalPort() + contextPath + cometdServletPath;
    server.setAttribute(OortConfigServlet.OORT_URL_PARAM, url);
    BayeuxServer bayeux =
        (BayeuxServer) context.getServletContext().getAttribute(BayeuxServer.ATTRIBUTE);
    server.setAttribute(BayeuxServer.ATTRIBUTE, bayeux);

    servers.add(server);

    return server;
  }
Пример #18
0
  public Server startServer(boolean ssl, boolean needClientAuth) throws Exception {
    Server ret = null;

    Connector connector = null;
    if (ssl) {
      SslContextFactory sslContextFactory = new SslContextFactory(SERVER_KEYSTORE_FILE);
      sslContextFactory.setKeyStorePassword(SERVER_KEYSTORE_PASS);
      sslContextFactory.setTrustStore(SERVER_TRUSTSTORE_FILE);
      sslContextFactory.setTrustStorePassword(SERVER_TRUSTSTORE_PASS);
      sslContextFactory.setNeedClientAuth(needClientAuth);

      connector = new SslSocketConnector(sslContextFactory);
      connector.setPort(8443);
    } else {
      connector = new SelectChannelConnector();
      connector.setPort(8080);
    }

    ret = new Server();
    ret.setConnectors(new Connector[] {connector});

    ServletContextHandler servletContext = new ServletContextHandler(ret, "/");
    servletContext.addServlet(HelloWorldServlet.class, "/");

    LOG.debug(String.format("*****Server***** - Starting"));
    ret.start();
    // server.join();

    return ret;
  }
  @Test
  public void testAddServletAfterStart() throws Exception {
    ServletContextHandler context = new ServletContextHandler();
    context.addServlet(TestServlet.class, "/test");
    context.setContextPath("/");
    _server.setHandler(context);
    _server.start();

    StringBuffer request = new StringBuffer();
    request.append("GET /test HTTP/1.0\n");
    request.append("Host: localhost\n");
    request.append("\n");

    String response = _connector.getResponses(request.toString());
    assertResponseContains("Test", response);

    context.addServlet(HelloServlet.class, "/hello");

    request = new StringBuffer();
    request.append("GET /hello HTTP/1.0\n");
    request.append("Host: localhost\n");
    request.append("\n");

    response = _connector.getResponses(request.toString());
    assertResponseContains("Hello World", response);
  }
Пример #20
0
  @Before
  public void setUp() throws Exception {
    super.setUp();

    final TestRepository<FileRepository> src = createTestRepository();
    final String srcName = src.getRepository().getDirectory().getName();

    ServletContextHandler app = server.addContext("/git");
    GitServlet gs = new GitServlet();
    gs.setRepositoryResolver(
        new RepositoryResolver<HttpServletRequest>() {
          public Repository open(HttpServletRequest req, String name)
              throws RepositoryNotFoundException, ServiceNotEnabledException {
            if (!name.equals(srcName)) throw new RepositoryNotFoundException(name);

            final Repository db = src.getRepository();
            db.incrementOpen();
            return db;
          }
        });
    app.addServlet(new ServletHolder(gs), "/*");

    server.setUp();

    remoteRepository = src.getRepository();
    remoteURI = toURIish(app, srcName);

    FileBasedConfig cfg = remoteRepository.getConfig();
    cfg.setBoolean("http", null, "receivepack", true);
    cfg.save();

    a_blob = src.blob("a");
  }
  @Before
  public void setUp() throws Exception {
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setOutputBufferSize(4096);
    _connector = new ServerConnector(_server, new HttpConnectionFactory(http_config));

    _server.setConnectors(new Connector[] {_connector});
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/ctx");
    _server.setHandler(context);
    _servletHandler = context.getServletHandler();

    ServletHolder holder = new ServletHolder(_servlet0);
    holder.setAsyncSupported(true);
    _servletHandler.addServletWithMapping(holder, "/path/*");

    ServletHolder holder2 = new ServletHolder(_servlet2);
    holder.setAsyncSupported(true);
    _servletHandler.addServletWithMapping(holder2, "/path2/*");

    _server.start();
    _port = _connector.getLocalPort();

    _owp.set(0);
    _oda.set(0);
    _read.set(0);
  }
Пример #22
0
  @Before
  public void setUp() throws Exception {
    super.setUp();

    final TestRepository<Repository> src = createTestRepository();
    final String srcName = src.getRepository().getDirectory().getName();

    ServletContextHandler app = server.addContext("/git");
    GitServlet gs = new GitServlet();
    gs.setRepositoryResolver(
        new RepositoryResolver<HttpServletRequest>() {
          public Repository open(HttpServletRequest req, String name)
              throws RepositoryNotFoundException, ServiceNotEnabledException {
            if (!name.equals(srcName)) throw new RepositoryNotFoundException(name);

            final Repository db = src.getRepository();
            db.incrementOpen();
            return db;
          }
        });
    app.addServlet(new ServletHolder(gs), "/*");

    server.setUp();

    remoteRepository = src.getRepository();
    remoteURI = toURIish(app, srcName);

    A_txt = src.blob("A");
    A = src.commit().add("A_txt", A_txt).create();
    B = src.commit().parent(A).add("A_txt", "C").add("B", "B").create();
    src.update(master, B);
  }
  public RestTransportServer(RestContact contact, final AppServerHandler appServerHandler) {
    this.contact = contact;

    server = new Server(contact.getPort());
    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/");

    // servletContextHandler.addServlet(new ServletHolder(new
    // RestTransportServlet(appServerHandler)), "/*");
    servletContextHandler.addServlet(new ServletHolder(new NotFoundServlet()), "/*");

    final Injector injector =
        Guice.createInjector(
            new ReefyServletModule(),
            new AbstractModule() {
              @Override
              protected void configure() {
                binder().requireExplicitBindings();
                bind(GuiceFilter.class);
                bind(new TypeLiteral<AppServerHandler<RestContact>>() {})
                    .toInstance(appServerHandler);
              }
            });

    final FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
    servletContextHandler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

    server.setHandler(servletContextHandler);
  }
Пример #24
0
 public String decodeUrl(final String path) throws Exception {
   ServerSocket serverSocket = new ServerSocket(0);
   final int port = serverSocket.getLocalPort();
   serverSocket.close();
   Server server = new Server(port);
   server.setStopAtShutdown(true);
   ServletContextHandler ctx = new ServletContextHandler(server, "/", true, false);
   ctx.addServlet(new ServletHolder(new DecodeServlet()), "/*");
   server.start();
   ThreadUtils.sleep(500);
   new Thread() {
     @Override
     public void run() {
       try {
         ThreadUtils.sleep(500);
         InputStream is = new URL("http://localhost:" + port + path).openStream();
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
     }
   }.start();
   synchronized (this) {
     wait();
   }
   return this.decodedPath;
 }
  public static void main(String[] args) throws Exception {
    int port = 8080;
    if (args.length == 1) {
      String portString = args[0];
      port = Integer.valueOf(portString);
    }

    System.out.append("Starting at port: ").append(String.valueOf(port)).append('\n');

    AccountService accountService = new AccountService();

    Servlet frontend = new Frontend();
    Servlet auth = new AuthServlet(accountService);
    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(frontend), "/api/v1/auth/signin");
    context.addServlet(new ServletHolder(auth), "/auth/*");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setResourceBase("public_html");

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

    server.start();
    server.join();
  }
Пример #26
0
  private void addServletToContext(ServletContextHandler context, ServletSpec spec)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException, Exception {
    if (context == null) {
      logger.log(Level.INFO, "Can not add servlet to null context: " + spec.getName());
      return;
    }

    //		boolean restartContext = context.isRunning();
    //		if (restartContext) {
    //			context.stop();
    //		}

    logger.log(
        Level.INFO,
        "Adding servlet to context: "
            + spec.getName()
            + ". context: "
            + context.getContextPath()
            + " spec: "
            + spec.getPath());

    ServletHolder servletHolder =
        new ServletHolder(ObjectUtility.getClass(Servlet.class, spec.getClassname()));
    context.addServlet(servletHolder, spec.getPath());
    servletHolder.setInitParameters(spec.getProperties());

    //		Class<Servlet> servletClass = ObjectUtility.getClass(Servlet.class, spec.getClassname());
    //		Dynamic servletRegistration = context.addServlet(servletClass, spec.getPath());
    //		servletRegistration.setInitParameters(spec.getProperties());

    //		if (restartContext) {
    //			context.start();
    //		}
  }
Пример #27
0
  @Before
  public void setup() throws Exception {
    try (ServerSocket serverSocket = new ServerSocket(0)) {
      googlePort = serverSocket.getLocalPort();
    }
    googleServer = new Server(googlePort);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    googleServer.setHandler(context);
    context.addServlet(new ServletHolder(userinfoServlet), "/oauth2/v2/userinfo");
    context.addServlet(new ServletHolder(tokenServlet), "/o/oauth2/token");
    googleServer.start();

    // Allow attributes to be set and got from a session.
    final Map<String, Object> attributes = Maps.newHashMap();
    Answer<Void> setAttributeAnswer =
        new Answer<Void>() {
          @Override
          public Void answer(InvocationOnMock invocation) throws Throwable {
            attributes.put((String) invocation.getArguments()[0], invocation.getArguments()[1]);
            return null;
          }
        };
    Answer<Object> getAttributeAnswer =
        new Answer<Object>() {
          @Override
          public Object answer(InvocationOnMock invocation) throws Throwable {
            return attributes.get((String) invocation.getArguments()[0]);
          }
        };
    when(session.getAttribute(anyString())).thenAnswer(getAttributeAnswer);
    when(session.getId()).thenReturn("sessionID");
    doAnswer(setAttributeAnswer).when(session).setAttribute(anyString(), anyObject());
  }
Пример #28
0
 public static Server createTestServer() {
   ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
   handler.addServlet(new ServletHolder(new CamelHttpTransportServlet()), "/camel/*");
   handler.setContextPath("/");
   Server server = new Server(TestConfig.getPort());
   server.setHandler(handler);
   return server;
 }
Пример #29
0
 public static void server(int port, String mapping, String routes, Object api) throws Exception {
   ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
   handler.setContextPath("/");
   handler.setAttribute("api", api);
   ServletHolder holder = new ServletHolder(new Servlet());
   holder.setInitParameter("routes", routes);
   handler.addServlet(holder, mapping);
   server(port, handler);
 }
Пример #30
0
 public static void main(String[] args) throws Exception {
   Server server = new Server(Integer.valueOf(System.getenv("PORT")));
   ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
   context.setContextPath("/");
   server.setHandler(context);
   context.addServlet(new ServletHolder(new Homepage()), "/*");
   server.start();
   server.join();
 }