예제 #1
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();
  }
예제 #2
0
  private void initialize(int port) throws Exception {
    System.out.println("Starting web server...");

    webServer = new Server(port);

    ServletContextHandler requestHandler = new ServletContextHandler();
    requestHandler.setContextPath("/");
    requestHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
    requestHandler.addServlet(new ServletHolder(new RequestServlet()), "/xmlrpc/*");

    ServletContextHandler uploadHandler = new ServletContextHandler();
    uploadHandler.setContextPath("/upload");
    uploadHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
    uploadHandler.addFilter(MultiPartFilter.class, "/", FilterMapping.ALL);
    uploadHandler.addServlet(new ServletHolder(new DesignUploadServlet()), "/");

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(false);
    resourceHandler.setResourceBase("./web");
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});

    HandlerList handlers = new HandlerList();
    handlers.addHandler(requestHandler);
    handlers.addHandler(uploadHandler);
    handlers.addHandler(resourceHandler);

    webServer.setHandler(handlers);
  }
예제 #3
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 testReplaceServletHandlerWithoutServlet() 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.stop();
    ServletHandler srvHnd = new ServletHandler();
    context.setServletHandler(srvHnd);
    context.start();

    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);
  }
  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);
  }
예제 #6
0
파일: App.java 프로젝트: is00hcw/gitwork
  public static void main(String[] args) throws Exception {
    Server server = new Server();

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(7080);
    server.setConnectors(new Connector[] {connector});

    ServletContextHandler webApiContext = new ServletContextHandler();
    webApiContext.setContextPath("/");

    webApiContext.addServlet(new ServletHolder(AppTokenServer.class), "/sts/*");
    webApiContext.addServlet(new ServletHolder(CallbackServer.class), "/callback/*");
    webApiContext.addServlet(new ServletHolder(PostObjectPolicy.class), "/get-post-policy/*");

    //    webApiContext.addServlet(new ServletHolder(STSToken.class), "/2/*");
    //    webApiContext.addServlet(new ServletHolder(CallbackServer.class), "/3/*");
    //    webApiContext.addServlet(new ServletHolder(DownloadApi.class), "/download/*");
    webApiContext.setSessionHandler(new SessionHandler());

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

    server.setHandler(handlers);
    server.start();
    server.join();
  }
예제 #7
0
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer, true);

    // Declare server handler collection
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);

    // Configure context "/" (root) for servlets
    ServletContextHandler root =
        new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
    // Add servlets to root context
    root.addServlet(new ServletHolder(new HelloServlet("Hello")), "/");
    root.addServlet(new ServletHolder(new HelloServlet("Ciao")), "/it/*");
    root.addServlet(new ServletHolder(new HelloServlet("Bonjoir")), "/fr/*");

    // Configure context "/other" for servlets
    ServletContextHandler other =
        new ServletContextHandler(contexts, "/other", ServletContextHandler.SESSIONS);
    // Add servlets to /other context
    other.addServlet(DefaultServlet.class.getCanonicalName(), "/");
    other.addServlet(new ServletHolder(new HelloServlet("YO!")), "*.yo");

    server.start();
    server.join();
  }
예제 #8
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());
  }
  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();
  }
예제 #10
0
  @Before
  public void init() throws Exception {
    _server = new Server();
    _connector = new LocalConnector(_server);
    ServletContextHandler context =
        new ServletContextHandler(
            ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    _server.addConnector(_connector);
    _server.setHandler(context);

    context.setContextPath("/");

    context.addServlet(DefaultServlet.class, "/");
    context.addServlet(FailServlet.class, "/fail/*");
    context.addServlet(ErrorServlet.class, "/error/*");

    ErrorPageErrorHandler error = new ErrorPageErrorHandler();
    context.setErrorHandler(error);
    error.addErrorPage(599, "/error/599");
    error.addErrorPage(IllegalStateException.class.getCanonicalName(), "/error/TestException");
    error.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, "/error/GlobalErrorPage");

    _server.start();
    ((StdErrLog) Log.getLogger(ServletHandler.class)).setHideStacks(true);
  }
  public static void main(String[] args) {
    GTFSDB.InitializeDB();
    Datasource ds = Datasource.getInstance();
    ds.getConnection();

    Server server = new Server(8080);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.setResourceBase(BASE_RESOURCE);

    server.setHandler(context);

    context.addServlet(GetFeedJSON.class, "/getFeed");
    context.addServlet(DefaultServlet.class, "/");

    ServletHolder jerseyServlet =
        context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/api/*");
    jerseyServlet.setInitOrder(1);
    jerseyServlet.setInitParameter(
        "jersey.config.server.provider.classnames",
        "org.glassfish.jersey.moxy.json.MoxyJsonFeature");
    jerseyServlet.setInitParameter(
        "jersey.config.server.provider.packages", "edu.usf.cutr.gtfsrtvalidator.api.resource");

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #12
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();
  }
예제 #13
0
  void initializeWebServer(Builder b) {
    // Create the thread pool for the web server to handle HTTP requests
    QueuedThreadPool threadPool = new QueuedThreadPool();
    if (b.maxThreads > 0) {
      threadPool.setMaxThreads(b.maxThreads);
    }
    threadPool.setDaemon(true);
    threadPool.setName(b.name + "-web");
    webServer.setThreadPool(threadPool);

    // Create the channel connector for the web server
    Connector connector = createChannelConnector(threadPool.getMaxThreads(), b);
    connector.setHost(b.host);
    connector.setPort(b.port);
    webServer.addConnector(connector);

    RewriteHandler rwHandler = new RewriteHandler();
    rwHandler.setRewriteRequestURI(true);
    rwHandler.setRewritePathInfo(false);

    RewriteRegexRule rootRule = new RewriteRegexRule();
    rootRule.setRegex("^/$");
    rootRule.setReplacement(b.contextRootRewriteTarget);
    rootRule.setTerminating(true);

    rwHandler.addRule(rootRule);
    rwHandler.setHandler(webAppContext);

    // Configure web application contexts for the web server
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.addHandler(rwHandler);
    webServer.setHandler(contexts);

    addServlet("jmx", "/jmx", JMXJsonServlet.class);
    addServlet("conf", "/conf", ConfServlet.class);
    addServlet("stacks", "/stacks", StackServlet.class);

    for (Pair<String, Class<? extends HttpServlet>> p : b.servlets) {
      addServlet(p.getFirst(), "/" + p.getFirst(), p.getSecond());
    }

    ServletContextHandler staticCtx = new ServletContextHandler(contexts, "/static");
    staticCtx.setResourceBase(appDir + "/static");
    staticCtx.addServlet(DefaultServlet.class, "/*");
    staticCtx.setDisplayName("static");

    String logDir = getLogDir(b.conf);
    if (logDir != null) {
      ServletContextHandler logCtx = new ServletContextHandler(contexts, "/logs");
      setContextAttributes(logCtx.getServletContext(), b.contextAttrs);
      logCtx.addServlet(AdminAuthorizedServlet.class, "/*");
      logCtx.setResourceBase(logDir);
      logCtx.setDisplayName("logs");
    }
  }
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

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

    context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class, "/");
    context.addServlet(new ServletHolder(new DumpServlet()), "/dump/*");

    server.start();
    server.join();
  }
예제 #15
0
 public static void main(String[] args) throws Exception {
     String port = System.getenv("PORT");
     if(port==null)
         port ="8000";
     Server server = new Server(Integer.valueOf(port));
     ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
     context.setContextPath("/");
     server.setHandler(context);
     context.addServlet(new ServletHolder(new basicWait()),"/basic_wait");
     context.addServlet(new ServletHolder(new delayedWait()),"/delayed_wait");
     server.start();
     server.join();
 }
예제 #16
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 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);
  }
  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);
    }
  }
예제 #19
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();
    //		}
  }
  @Test
  public void testReplaceHandler() throws Exception {
    ServletContextHandler servletContextHandler = new ServletContextHandler();
    ServletHolder sh = new ServletHolder(new TestServlet());
    servletContextHandler.addServlet(sh, "/foo");
    final AtomicBoolean contextInit = new AtomicBoolean(false);
    final AtomicBoolean contextDestroy = new AtomicBoolean(false);

    servletContextHandler.addEventListener(
        new ServletContextListener() {

          @Override
          public void contextInitialized(ServletContextEvent sce) {
            if (sce.getServletContext() != null) contextInit.set(true);
          }

          @Override
          public void contextDestroyed(ServletContextEvent sce) {
            if (sce.getServletContext() != null) contextDestroy.set(true);
          }
        });
    ServletHandler shandler = servletContextHandler.getServletHandler();

    ResourceHandler rh = new ResourceHandler();

    servletContextHandler.insertHandler(rh);
    assertEquals(shandler, servletContextHandler.getServletHandler());
    assertEquals(rh, servletContextHandler.getHandler());
    assertEquals(rh.getHandler(), shandler);
    _server.setHandler(servletContextHandler);
    _server.start();
    assertTrue(contextInit.get());
    _server.stop();
    assertTrue(contextDestroy.get());
  }
예제 #21
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);
  }
예제 #22
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;
  }
  @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();
  }
예제 #24
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);
    }
  }
예제 #25
0
  @Test
  public void testGzip() throws Exception {
    testdir.ensureEmpty();
    File resBase = testdir.getFile("docroot");
    FS.ensureDirExists(resBase);
    File file0 = new File(resBase, "data0.txt");
    createFile(file0, "Hello Text 0");
    File file0gz = new File(resBase, "data0.txt.gz");
    createFile(file0gz, "fake gzip");

    String resBasePath = resBase.getAbsolutePath();

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

    String response =
        connector.getResponses("GET /context/data0.txt HTTP/1.0\r\nHost:localhost:8080\r\n\r\n");
    assertResponseContains("Content-Length: 12", response);
    assertResponseContains("Hello Text 0", response);
    assertResponseContains("Vary: Accept-Encoding", response);
    assertResponseNotContains("Content-Encoding: gzip", response);

    response =
        connector.getResponses(
            "GET /context/data0.txt HTTP/1.0\r\nHost:localhost:8080\r\nAccept-Encoding:gzip\r\n\r\n");
    assertResponseContains("Content-Length: 9", response);
    assertResponseContains("fake gzip", response);
    assertResponseContains("Vary: Accept-Encoding", response);
    assertResponseContains("Content-Encoding: gzip", response);
  }
예제 #26
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;
  }
예제 #27
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);
  }
예제 #28
0
  @Test
  public void testListingWithSession() throws Exception {
    ServletHolder defholder = context.addServlet(DefaultServlet.class, "/*");
    defholder.setInitParameter("dirAllowed", "true");
    defholder.setInitParameter("redirectWelcome", "false");
    defholder.setInitParameter("gzip", "false");

    testdir.ensureEmpty();

    /* create some content in the docroot */
    File resBase = testdir.getFile("docroot");
    assertTrue(resBase.mkdirs());
    assertTrue(new File(resBase, "one").mkdir());
    assertTrue(new File(resBase, "two").mkdir());
    assertTrue(new File(resBase, "three").mkdir());

    String resBasePath = resBase.getAbsolutePath();
    defholder.setInitParameter("resourceBase", resBasePath);

    StringBuffer req1 = new StringBuffer();
    req1.append("GET /context/;JSESSIONID=1234567890 HTTP/1.0\n\n");

    String response = connector.getResponses(req1.toString());

    assertResponseContains("/one/;JSESSIONID=1234567890", response);
    assertResponseContains("/two/;JSESSIONID=1234567890", response);
    assertResponseContains("/three/;JSESSIONID=1234567890", response);

    assertResponseNotContains("<script>", 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;
 }
예제 #30
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");
  }