Ejemplo n.º 1
0
  public void run() throws Exception {
    server.start();
    this.localPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
    System.out.println("Test website has successfully started on port " + this.localPort);

    server.join();
  }
  @Before
  public void setUp() throws Exception {
    File docRoot = new File("target/test-output/docroot/");
    docRoot.mkdirs();
    docRoot.deleteOnExit();

    System.setProperty("org.mortbay.jetty.util.DEBUG", "");
    _server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    _server.addConnector(connector);

    _handler = new TestHandler();
    _server.setHandler(_handler);

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    mBeanContainer.addBean(Log.getLog());

    _counter = _handler.getRequestCounter();
    mBeanContainer.addBean(_counter);

    _server.addBean(mBeanContainer);
    _server.getContainer().addEventListener(mBeanContainer);
    _server.start();

    startClient(null);

    _monitor = new JMXMonitor();

    int port = _server.getConnectors()[0].getLocalPort();
    _requestUrl = "http://localhost:" + port + "/";
  }
Ejemplo n.º 3
0
  /**
   * Checks that the only connector configured for the current jetty instance and returns it.
   *
   * @return Connector instance.
   * @throws GridException If no or more than one connectors found.
   */
  private AbstractNetworkConnector getJettyConnector() throws GridException {
    if (httpSrv.getConnectors().length == 1) {
      Connector connector = httpSrv.getConnectors()[0];

      if (!(connector instanceof AbstractNetworkConnector))
        throw new GridException(
            "Error in jetty configuration. Jetty connector should extend "
                + "AbstractNetworkConnector class.");

      return (AbstractNetworkConnector) connector;
    } else
      throw new GridException(
          "Error in jetty configuration [connectorsFound="
              + httpSrv.getConnectors().length
              + "connectorsExpected=1]");
  }
Ejemplo n.º 4
0
 /** Returns the socket the WebSocket server is listening on. */
 public SocketAddress getWebSocketAddress() {
   if (httpServer == null) {
     return null;
   } else {
     ServerConnector c = (ServerConnector) httpServer.getConnectors()[0];
     return new InetSocketAddress(c.getHost(), c.getLocalPort());
   }
 }
Ejemplo n.º 5
0
  @Test
  public void createServer() {
    Server server = JettyFactory.createServerInSource(1978, "/test");

    assertEquals(1978, server.getConnectors()[0].getPort());
    assertEquals("/test", ((WebAppContext) server.getHandler()).getContextPath());
    assertEquals("src/main/webapp", ((WebAppContext) server.getHandler()).getWar());
  }
Ejemplo n.º 6
0
  protected int getPort() {
    for (final Connector connector : server.getConnectors()) {
      if (connector instanceof ServerConnector) {
        return ((ServerConnector) connector).getLocalPort();
      }
    }

    throw new IllegalStateException("Server is not listening on any ports");
  }
  @Test
  public void testHttpInputModule() throws Exception {

    final List<String> receivedMessages = new ArrayList<String>();
    Handler handler =
        new AbstractHandler() {
          @Override
          public void handle(
              String string, Request rq, HttpServletRequest request, HttpServletResponse response)
              throws IOException, ServletException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), bos);
            receivedMessages.add(new String(bos.toByteArray()));
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getOutputStream().println("Hello");
            response.getOutputStream().println("World,");
            response.getOutputStream().println("Big");
            response.getOutputStream().println("Data!");
            response.getOutputStream().flush();

            ((Request) request).setHandled(true);
          }
        };

    Server server = new Server(0);
    server.setHandler(handler);
    server.start();

    String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext";

    final HttpLinesInputOperator operator = new HttpLinesInputOperator();
    CollectorTestSink<String> sink =
        TestUtils.setSink(operator.outputPort, new CollectorTestSink<String>());
    operator.setUrl(new URI(url));

    operator.setup(null);
    operator.activate(null);

    int timeoutMillis = 3000;
    while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) {
      operator.emitTuples();
      timeoutMillis -= 20;
      Thread.sleep(20);
    }

    Assert.assertTrue("tuple emitted", sink.collectedTuples.size() > 0);

    Assert.assertEquals("", sink.collectedTuples.get(0), "Hello");
    Assert.assertEquals("", sink.collectedTuples.get(1), "World,");
    Assert.assertEquals("", sink.collectedTuples.get(2), "Big");
    Assert.assertEquals("", sink.collectedTuples.get(3), "Data!");

    operator.deactivate();
    operator.teardown();
    server.stop();
  }
Ejemplo n.º 8
0
 /**
  * Starts a test jetty doc server at /docs. Blocks until the server is terminated.
  *
  * @param port the port to which the server will connect.
  * @throws Exception if the server couldn't be started.
  */
 public void startupServer(int port) throws Exception {
   jettyServer = new Server(port);
   ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
   context.setContextPath("/");
   jettyServer.setHandler(context);
   context.addServlet(new ServletHolder(this), SERVER_CONTEXT_LOC);
   jettyServer.start();
   jettyPort = jettyServer.getConnectors()[0].getLocalPort();
   jettyServer.join();
 }
Ejemplo n.º 9
0
  public void startServletContainer(Configuration conf) throws Exception {
    if (server != null) {
      LOG.error("ServletContainer already running");
      return;
    }

    // Inject the conf for the test by being first to make singleton
    RESTServlet.getInstance(conf, UserProvider.instantiate(conf));

    // set up the Jersey servlet container for Jetty
    ResourceConfig app =
        new ResourceConfig()
            .packages("org.apache.hadoop.hbase.rest")
            .register(Jackson1Feature.class);
    ServletHolder sh = new ServletHolder(new ServletContainer(app));

    // set up Jetty and run the embedded server
    server = new Server(0);
    LOG.info("configured " + ServletContainer.class.getName());

    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSendDateHeader(false);
    httpConfig.setSendServerVersion(false);
    ServerConnector serverConnector =
        new ServerConnector(server, new HttpConnectionFactory(httpConfig));
    serverConnector.setPort(testServletPort);

    server.addConnector(serverConnector);

    // set up context
    ServletContextHandler ctxHandler =
        new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    ctxHandler.addServlet(sh, "/*");
    // Load filters specified from configuration.
    String[] filterClasses =
        conf.getStrings(Constants.FILTER_CLASSES, ArrayUtils.EMPTY_STRING_ARRAY);
    for (String filter : filterClasses) {
      filter = filter.trim();
      ctxHandler.addFilter(filter, "/*", EnumSet.of(DispatcherType.REQUEST));
    }
    LOG.info("Loaded filter classes :" + filterClasses);

    conf.set(RESTServer.REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY, ".*");
    RESTServer.addCSRFFilter(ctxHandler, conf);

    HttpServerUtil.constrainHttpMethods(ctxHandler);

    // start the server
    server.start();
    // get the port
    testServletPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();

    LOG.info("started " + server.getClass().getName() + " on port " + testServletPort);
  }
Ejemplo n.º 10
0
  /**
   * {@inheritDoc}
   *
   * @see net.sourceforge.eclipsejetty.starter.common.ServerAdapter#getSecurePorts()
   */
  @Override
  public Collection<Integer> getSecurePorts() {
    Collection<Integer> results = new LinkedHashSet<Integer>();
    Connector[] connectors = server.getConnectors();

    if (connectors != null) {
      for (Connector connector : connectors) {
        if (connector.getClass().getSimpleName().toLowerCase().contains("ssl")) {
          results.add(connector.getPort());
        }
      }
    }

    return results;
  }
Ejemplo n.º 11
0
  @Test
  public void testTwoComets() throws Exception {
    Server server1 = startServer(0);
    int groupPort = ((NetworkConnector) server1.getConnectors()[0]).getLocalPort();
    Oort oort1 = startOort(server1);
    startConfigurer(oort1, groupPort);

    Server server2 = startServer(0);
    Oort oort2 = startOort(server2);
    startConfigurer(oort2, groupPort);

    // Give some time to advertise
    Thread.sleep(1000);

    Assert.assertEquals(1, oort1.getKnownComets().size());
    Assert.assertEquals(1, oort2.getKnownComets().size());
  }
  @Override
  public void setUp() {
    try {
      helper.setUp();

      ModelFactory.setInstance(new ServerModelFactory());

      try {
        ObjectifyService.register(UserImpl.class);
        ObjectifyService.register(InterestImpl.class);
        ObjectifyService.register(C2DMConfig.class);
      } catch (IllegalArgumentException e) {
      }

      /*
       * Viene utilizzato Jetty v7.5.4 come Servlet Container
       * http://www.eclipse.org/jetty/
       */
      server = new Server(0);
      ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
      context.setContextPath("/");
      server.setHandler(context);
      context.addFilter(new FilterHolder(new FilterForTesting()), "/*", 0);
      context.addFilter(new FilterHolder(new ServletFilter()), "/*", 0);
      context.addServlet(new ServletHolder(new MockServlet()), "/*");

      server.start();
      port = server.getConnectors()[0].getLocalPort();

      // User utilizzato col solo scopo di ottenere un X-AccessToken valido per effettuare le
      // richieste
      UserImpl user1 =
          (UserImpl) ModelFactory.getInstance().createUser(12345, "Michele Piccirillo", null);
      fbAccessToken = "accessToken";
      user1.setAuthToken(fbAccessToken);
      ObjectifyService.begin().put(user1);

      Thread.sleep(
          15); // Ulizzato per assicurare che il tempo necessario per la persistenza sul Datatore
               // sia passato

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @BeforeClass(groups = "Integration")
  public void setUp() throws Exception {
    WebAppContext context;

    // running in source mode; need to use special classpath
    context = new WebAppContext("src/test/webapp", "/");
    context.setExtraClasspath("./target/test-rest-server/");
    context.setAttribute(
        BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, getManagementContext());

    Server server =
        BrooklynRestApiLauncher.launcher()
            .managementContext(manager)
            .customContext(context)
            .start();

    api = new BrooklynApi("http://localhost:" + server.getConnectors()[0].getPort() + "/");
  }
Ejemplo n.º 14
0
 private Connector[] getAllConnectors() {
   try {
     BundleContext context = Platform.getBundle(Activator.PLUGIN_ID).getBundleContext();
     ServiceReference[] refs =
         context.getAllServiceReferences(
             Server.class.getName(), "(managedServerName=defaultJettyServer)");
     for (ServiceReference ref : refs) {
       Server server = (Server) context.getService(ref);
       return server.getConnectors();
     }
   } catch (InvalidSyntaxException e) {
     IStatus status =
         new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Can not find jetty server.", e);
     Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
     Platform.getLog(bundle).log(status);
     throw new RuntimeException("Can not find jetty server.", e);
   }
   throw new RuntimeException("Can not find jetty server.");
 }
Ejemplo n.º 15
0
  @Test
  public void testThreeComets() throws Exception {
    Server server1 = startServer(0);
    int groupPort = ((NetworkConnector) server1.getConnectors()[0]).getLocalPort();
    Oort oort1 = startOort(server1);
    startConfigurer(oort1, groupPort);

    Server server2 = startServer(0);
    Oort oort2 = startOort(server2);
    final OortMulticastConfigurer configurer2 = startConfigurer(oort2, groupPort);

    // Give some time to advertise
    Thread.sleep(1000);

    Assert.assertEquals(1, oort1.getKnownComets().size());
    Assert.assertEquals(1, oort2.getKnownComets().size());

    // Create another comet
    Server server3 = startServer(0);
    Oort oort3 = startOort(server3);
    startConfigurer(oort3, groupPort);

    // Give some time to advertise
    Thread.sleep(1000);

    Assert.assertEquals(2, oort1.getKnownComets().size());
    Assert.assertEquals(2, oort2.getKnownComets().size());
    Assert.assertEquals(2, oort3.getKnownComets().size());

    stopConfigurer(configurer2);
    stopOort(oort2);
    stopServer(server2);

    // Give some time to advertise
    Thread.sleep(1000);

    Assert.assertEquals(1, oort1.getKnownComets().size());
    Assert.assertEquals(oort3.getURL(), oort1.getKnownComets().iterator().next());
    Assert.assertEquals(1, oort3.getKnownComets().size());
    Assert.assertEquals(oort1.getURL(), oort3.getKnownComets().iterator().next());
  }
  @Test
  public void testApplication() throws Exception {
    Configuration conf = new Configuration(false);
    conf.addResource("dt-site-monitoring.xml");
    Server server = new Server(0);
    Servlet servlet = new SamplePubSubWebSocketServlet();
    ServletHolder sh = new ServletHolder(servlet);
    ServletContextHandler contextHandler =
        new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    contextHandler.addServlet(sh, "/pubsub");
    contextHandler.addServlet(sh, "/*");
    server.start();
    Connector connector[] = server.getConnectors();
    conf.set("dt.attr.GATEWAY_CONNECT_ADDRESS", "localhost:" + connector[0].getLocalPort());

    MRMonitoringApplication application = new MRMonitoringApplication();
    LocalMode lma = LocalMode.newInstance();
    lma.prepareDAG(application, conf);
    LocalMode.Controller lc = lma.getController();
    lc.run(10000);
    server.stop();
  }
Ejemplo n.º 17
0
  /**
   * @throws GridException If failed.
   * @return {@code True} if Jetty started.
   */
  @SuppressWarnings("IfMayBeConditional")
  private boolean startJetty() throws GridException {
    try {
      httpSrv.start();

      if (httpSrv.isStarted()) {
        for (Connector con : httpSrv.getConnectors()) {
          int connPort = ((NetworkConnector) con).getPort();

          if (connPort > 0) ctx.ports().registerPort(connPort, TCP, getClass());
        }

        return true;
      }

      return false;
    } catch (SocketException ignore) {
      if (log.isDebugEnabled()) log.debug("Failed to bind HTTP server to configured port.");

      stopJetty();

      return false;
    } catch (MultiException e) {
      if (log.isDebugEnabled()) log.debug("Caught multi exception: " + e);

      for (Object obj : e.getThrowables())
        if (!(obj instanceof SocketException))
          throw new GridException("Failed to start Jetty HTTP server.", e);

      if (log.isDebugEnabled()) log.debug("Failed to bind HTTP server to configured port.");

      stopJetty();

      return false;
    } catch (Exception e) {
      throw new GridException("Failed to start Jetty HTTP server.", e);
    }
  }
  private void logAdminConsolePorts() {
    // Log what ports the admin console is running on.
    String listening = LocaleUtils.getLocalizedString("admin.console.listening");
    String hostname =
        getBindInterface() == null
            ? XMPPServer.getInstance().getServerInfo().getXMPPDomain()
            : getBindInterface();
    boolean isPlainStarted = false;
    boolean isSecureStarted = false;
    for (Connector connector : adminServer.getConnectors()) {
      if (connector.getPort() == adminPort) {
        isPlainStarted = true;
      } else if (connector.getPort() == adminSecurePort) {
        isSecureStarted = true;
      }
    }

    if (isPlainStarted && isSecureStarted) {
      log(
          listening
              + ":"
              + System.getProperty("line.separator")
              + "  http://"
              + hostname
              + ":"
              + adminPort
              + System.getProperty("line.separator")
              + "  https://"
              + hostname
              + ":"
              + adminSecurePort);
    } else if (isSecureStarted) {
      log(listening + " https://" + hostname + ":" + adminSecurePort);
    } else if (isPlainStarted) {
      log(listening + " http://" + hostname + ":" + adminPort);
    }
  }
Ejemplo n.º 19
0
  public void runServletContainer() throws Exception {
    // setup the executor for the servlet
    logger.debug("Starting Servlet Container...");
    executor =
        new ThreadPoolExecutor(
            serverData.getAsynchServletCorePoolSize(),
            serverData.getAsynchServletMaxPoolSize(),
            50000L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(serverData.getAsynchServletMaxWorkInQueue()));
    Server server = new Server(Integer.parseInt(serverData.getWebServerPort()));
    server.getConnectors()[0].setRequestHeaderSize(serverData.getHeaderBufferSize());

    ServletHolder sh = new ServletHolder(ServletContainer.class);
    sh.setInitParameter(
        "com.sun.jersey.config.property.resourceConfigClass",
        "com.sun.jersey.api.core.PackagesResourceConfig");
    // sh.setInitParameter("com.sun.jersey.config.property.packages",
    // serverData.getJerseyPackage());
    sh.setAsyncSupported(true);
    // un-comment these to enable tracing of requests and responses
    // sh.setInitParameter("com.sun.jersey.config.feature.Debug", "true");
    // sh.setInitParameter("com.sun.jersey.config.feature.Trace", "true");//
    // sh.setInitParameter("com.sun.jersey.spi.container.ContainerRequestFilters",
    // "com.sun.jersey.api.container.filter.LoggingFilter");
    // sh.setInitParameter("com.sun.jersey.spi.container.ContainerResponseFilters",
    // "com.sun.jersey.api.container.filter.LoggingFilter");
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(sh, "/*");
    context.addServlet("semplest.server.ESB.AsyncServlet", "/*");
    server.setHandler(context);
    logger.debug("Servlet Container Start...");
    server.start();
    server.join();
  }
 @BeforeClass
 public static void startJetty() throws Exception {
   server = new Server(0);
   server.setHandler(
       new AbstractHandler() {
         @Override
         public void handle(
             String target,
             Request baseRequest,
             HttpServletRequest request,
             HttpServletResponse response)
             throws IOException, ServletException {
           try {
             if (request.getRequestURI().endsWith(".jar")) {
               // get simulated timeout value from ... version fragment
               String[] split = request.getRequestURI().split("[-.]");
               String versionWhichIsTimeout = split[split.length - 2];
               try {
                 Thread.sleep(Integer.parseInt(versionWhichIsTimeout));
               } catch (InterruptedException e) {
                 Thread.currentThread().interrupt();
                 return;
               }
               response.setStatus(HttpServletResponse.SC_OK);
               response.getOutputStream().write(0x42);
             } else {
               response.setStatus(HttpServletResponse.SC_NOT_FOUND);
             }
           } finally {
             baseRequest.setHandled(true);
           }
         }
       });
   server.start();
   port = server.getConnectors()[0].getLocalPort();
 }
 private int getServerPort(Server server) {
   return ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
 }
Ejemplo n.º 22
0
 private Integer getStartedServerPort(Server server) {
   return server.getConnectors()[0].getLocalPort();
 }
Ejemplo n.º 23
0
 /**
  * Gets the actual tcp port for the first server connector
  *
  * @return the actual port available only after start.
  */
 public int getLocalPort() {
   return ((ServerConnector) server.getConnectors()[0]).getLocalPort();
 }
  @Test
  public void testGracefulShutdown() throws Exception {
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    MetricRegistry metricRegistry = new MetricRegistry();
    Environment environment =
        new Environment(
            "test", objectMapper, validator, metricRegistry, ClassLoader.getSystemClassLoader());

    CountDownLatch requestReceived = new CountDownLatch(1);
    CountDownLatch shutdownInvoked = new CountDownLatch(1);

    environment.jersey().register(new TestResource(requestReceived, shutdownInvoked));

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
    final Server server = http.build(environment);

    ((AbstractNetworkConnector) server.getConnectors()[0]).setPort(0);

    ScheduledFuture<Void> cleanup =
        executor.schedule(
            new Callable<Void>() {
              @Override
              public Void call() throws Exception {
                if (!server.isStopped()) {
                  server.stop();
                }
                executor.shutdownNow();
                return null;
              }
            },
            5,
            TimeUnit.SECONDS);

    server.start();

    final int port = ((AbstractNetworkConnector) server.getConnectors()[0]).getLocalPort();

    Future<String> futureResult =
        executor.submit(
            new Callable<String>() {
              @Override
              public String call() throws Exception {
                URL url = new URL("http://localhost:" + port + "/app/test");
                URLConnection connection = url.openConnection();
                connection.connect();
                return CharStreams.toString(new InputStreamReader(connection.getInputStream()));
              }
            });

    requestReceived.await();

    Future<Void> serverStopped =
        executor.submit(
            new Callable<Void>() {
              @Override
              public Void call() throws Exception {
                server.stop();
                return null;
              }
            });

    Connector[] connectors = server.getConnectors();
    assertThat(connectors).isNotEmpty();
    assertThat(connectors[0]).isInstanceOf(NetworkConnector.class);
    NetworkConnector connector = (NetworkConnector) connectors[0];

    // wait for server to close the connectors
    while (true) {
      if (!connector.isOpen()) {
        shutdownInvoked.countDown();
        break;
      }
      Thread.sleep(5);
    }

    String result = futureResult.get();
    assertThat(result).isEqualTo("test");

    serverStopped.get();

    // cancel the cleanup future since everything succeeded
    cleanup.cancel(false);
    executor.shutdownNow();
  }
  private Map<String, String> testUpload(
      String path,
      final byte[] contents,
      String location,
      String profile,
      String version,
      boolean hasLocationHeader)
      throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(
        new AbstractHandler() {
          @Override
          public void handle(
              String target,
              Request baseRequest,
              HttpServletRequest request,
              HttpServletResponse response)
              throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
          }
        });
    server.start();

    try {
      int localPort = server.getConnectors()[0].getLocalPort();
      List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
      RuntimeProperties props = new MockRuntimeProperties();
      MavenUploadProxyServlet servlet =
          new MavenUploadProxyServlet(
              props,
              "target/tmp",
              remoteRepos,
              false,
              "always",
              "warn",
              "http",
              "localhost",
              localPort,
              "fuse",
              "fuse",
              null,
              projectDeployer);

      HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
      EasyMock.expect(request.getPathInfo()).andReturn(path);
      EasyMock.expect(request.getInputStream())
          .andReturn(
              new ServletInputStream() {
                private int i;

                @Override
                public int read() throws IOException {
                  if (i >= contents.length) {
                    return -1;
                  }
                  return (contents[i++] & 0xFF);
                }
              });
      EasyMock.expect(request.getHeader("X-Location")).andReturn(location);
      EasyMock.expect(request.getParameter("profile")).andReturn(profile);
      EasyMock.expect(request.getParameter("version")).andReturn(version);

      final Map<String, String> headers = new HashMap<>();

      HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
      HttpServletResponse response =
          new HttpServletResponseWrapper(rm) {
            @Override
            public void addHeader(String name, String value) {
              headers.put(name, value);
            }
          };
      response.setStatus(EasyMock.anyInt());
      EasyMock.expectLastCall().anyTimes();
      response.setContentLength(EasyMock.anyInt());
      EasyMock.expectLastCall().anyTimes();
      response.setContentType((String) EasyMock.anyObject());
      EasyMock.expectLastCall().anyTimes();
      response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
      EasyMock.expectLastCall().anyTimes();
      response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
      EasyMock.expectLastCall().anyTimes();

      EasyMock.replay(request, rm);

      servlet.start();
      servlet.doPut(request, response);

      EasyMock.verify(request, rm);

      Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));

      return headers;
    } finally {
      server.stop();
      if (old != null) {
        System.setProperty("karaf.data", old);
      }
    }
  }
  private void testDownload(Handler serverHandler) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(serverHandler);
    server.start();

    try {
      int localPort = server.getConnectors()[0].getLocalPort();
      List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
      RuntimeProperties props = new MockRuntimeProperties();
      MavenDownloadProxyServlet servlet =
          new MavenDownloadProxyServlet(
              props,
              "target/tmp",
              remoteRepos,
              false,
              "always",
              "warn",
              "http",
              "localhost",
              localPort,
              "fuse",
              "fuse",
              null,
              projectDeployer,
              5);

      HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
      EasyMock.expect(request.getPathInfo())
          .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");

      HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      EasyMock.expect(response.getOutputStream())
          .andReturn(
              new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                  baos.write(b);
                }

                @Override
                public void write(byte[] b, int off, int len) throws IOException {
                  baos.write(b, off, len);
                }
              })
          .anyTimes();
      response.setStatus(EasyMock.anyInt());
      EasyMock.expectLastCall().anyTimes();
      response.setContentLength(EasyMock.anyInt());
      EasyMock.expectLastCall().anyTimes();
      response.setContentType((String) EasyMock.anyObject());
      EasyMock.expectLastCall().anyTimes();
      response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
      EasyMock.expectLastCall().anyTimes();
      response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
      EasyMock.expectLastCall().anyTimes();

      EasyMock.replay(request, response);

      servlet.start();
      servlet.doGet(request, response);
      Assert.assertArrayEquals(new byte[] {0x42}, baos.toByteArray());

      EasyMock.verify(request, response);
    } finally {
      server.stop();
      if (old != null) {
        System.setProperty("karaf.data", old);
      }
    }
  }
  /** Starts the Jetty instance. */
  public void startup() {
    restartNeeded = false;

    // Add listener for certificate events
    certificateListener = new CertificateListener();
    CertificateManager.addListener(certificateListener);

    adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
    adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);
    adminServer = new Server();
    final QueuedThreadPool tp = new QueuedThreadPool(254);
    tp.setName("Jetty-QTP-AdminConsole");
    adminServer.setThreadPool(tp);

    // Do not send Jetty info in HTTP headers
    adminServer.setSendServerVersion(false);

    // Create connector for http traffic if it's enabled.
    if (adminPort > 0) {
      Connector httpConnector = new SelectChannelConnector();
      // Listen on a specific network interface if it has been set.
      String bindInterface = getBindInterface();
      httpConnector.setHost(bindInterface);
      httpConnector.setPort(adminPort);
      adminServer.addConnector(httpConnector);
    }

    // Create a connector for https traffic if it's enabled.
    sslEnabled = false;
    try {
      if (adminSecurePort > 0
          && CertificateManager.isRSACertificate(SSLConfig.getKeyStore(), "*")) {
        if (!CertificateManager.isRSACertificate(
            SSLConfig.getKeyStore(), XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
          Log.warn(
              "Admin console: Using RSA certificates but they are not valid for the hosted domain");
        }

        JiveSslConnector httpsConnector = new JiveSslConnector();
        String bindInterface = getBindInterface();
        httpsConnector.setHost(bindInterface);
        httpsConnector.setPort(adminSecurePort);

        httpsConnector.setTrustPassword(SSLConfig.gets2sTrustPassword());
        httpsConnector.setTruststoreType(SSLConfig.getStoreType());
        httpsConnector.setTruststore(SSLConfig.gets2sTruststoreLocation());
        httpsConnector.setNeedClientAuth(false);
        httpsConnector.setWantClientAuth(false);

        httpsConnector.setKeyPassword(SSLConfig.getKeyPassword());
        httpsConnector.setKeystoreType(SSLConfig.getStoreType());
        httpsConnector.setKeystore(SSLConfig.getKeystoreLocation());
        adminServer.addConnector(httpsConnector);

        sslEnabled = true;
      }
    } catch (Exception e) {
      Log.error(e.getMessage(), e);
    }

    // Make sure that at least one connector was registered.
    if (adminServer.getConnectors() == null || adminServer.getConnectors().length == 0) {
      adminServer = null;
      // Log warning.
      log(LocaleUtils.getLocalizedString("admin.console.warning"));
      return;
    }

    HandlerCollection collection = new HandlerCollection();
    adminServer.setHandler(collection);
    collection.setHandlers(new Handler[] {contexts, new DefaultHandler()});

    try {
      adminServer.start();
    } catch (Exception e) {
      Log.error("Could not start admin conosle server", e);
    }

    // Log the ports that the admin server is listening on.
    logAdminConsolePorts();
  }
Ejemplo n.º 28
0
  /**
   * Configure a jetty instance and deploy the webapps presented as args
   *
   * @param args the command line arguments
   * @throws Exception if unable to configure
   */
  public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
      if ("--lib".equals(args[i])) {
        try (Resource lib = Resource.newResource(args[++i])) {
          if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib);
          _classpath.addJars(lib);
        }
      } else if ("--jar".equals(args[i])) {
        try (Resource jar = Resource.newResource(args[++i])) {
          if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar);
          _classpath.addPath(jar);
        }
      } else if ("--classes".equals(args[i])) {
        try (Resource classes = Resource.newResource(args[++i])) {
          if (!classes.exists() || !classes.isDirectory())
            usage("No such classes directory " + classes);
          _classpath.addPath(classes);
        }
      } else if (args[i].startsWith("--")) i++;
    }

    initClassLoader();

    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);

    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;

    boolean runnerServerInitialized = false;

    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--port":
          port = Integer.parseInt(args[++i]);
          break;
        case "--host":
          host = args[++i];
          break;
        case "--stop-port":
          stopPort = Integer.parseInt(args[++i]);
          break;
        case "--stop-key":
          stopKey = args[++i];
          break;
        case "--log":
          _logFile = args[++i];
          break;
        case "--out":
          String outFile = args[++i];
          PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
          LOG.info("Redirecting stderr/stdout to " + outFile);
          System.setErr(out);
          System.setOut(out);
          break;
        case "--path":
          contextPath = args[++i];
          contextPathSet = true;
          break;
        case "--config":
          if (_configFiles == null) _configFiles = new ArrayList<>();
          _configFiles.add(args[++i]);
          break;
        case "--lib":
          ++i; // skip

          break;
        case "--jar":
          ++i; // skip

          break;
        case "--classes":
          ++i; // skip

          break;
        case "--stats":
          _enableStats = true;
          _statsPropFile = args[++i];
          _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
          break;
        default:
          // process contexts

          if (!runnerServerInitialized) // log handlers not registered, server maybe not created,
                                        // etc
          {
            if (_server == null) // server not initialized yet
            {
              // build the server
              _server = new Server();
            }

            // apply jetty config files if there are any
            if (_configFiles != null) {
              for (String cfg : _configFiles) {
                try (Resource resource = Resource.newResource(cfg)) {
                  XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                  xmlConfiguration.configure(_server);
                }
              }
            }

            // check that everything got configured, and if not, make the handlers
            HandlerCollection handlers =
                (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
            if (handlers == null) {
              handlers = new HandlerCollection();
              _server.setHandler(handlers);
            }

            // check if contexts already configured
            _contexts =
                (ContextHandlerCollection)
                    handlers.getChildHandlerByClass(ContextHandlerCollection.class);
            if (_contexts == null) {
              _contexts = new ContextHandlerCollection();
              prependHandler(_contexts, handlers);
            }

            if (_enableStats) {
              // if no stats handler already configured
              if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                StatisticsHandler statsHandler = new StatisticsHandler();

                Handler oldHandler = _server.getHandler();
                statsHandler.setHandler(oldHandler);
                _server.setHandler(statsHandler);

                ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                statsContext.setSessionHandler(new SessionHandler());
                if (_statsPropFile != null) {
                  HashLoginService loginService =
                      new HashLoginService("StatsRealm", _statsPropFile);
                  Constraint constraint = new Constraint();
                  constraint.setName("Admin Only");
                  constraint.setRoles(new String[] {"admin"});
                  constraint.setAuthenticate(true);

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

                  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                  securityHandler.setLoginService(loginService);
                  securityHandler.setConstraintMappings(Collections.singletonList(cm));
                  securityHandler.setAuthenticator(new BasicAuthenticator());
                  statsContext.setSecurityHandler(securityHandler);
                }
              }
            }

            // ensure a DefaultHandler is present
            if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
              handlers.addHandler(new DefaultHandler());
            }

            // ensure a log handler is present
            _logHandler =
                (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
            if (_logHandler == null) {
              _logHandler = new RequestLogHandler();
              handlers.addHandler(_logHandler);
            }

            // check a connector is configured to listen on
            Connector[] connectors = _server.getConnectors();
            if (connectors == null || connectors.length == 0) {
              ServerConnector connector = new ServerConnector(_server);
              connector.setPort(port);
              if (host != null) connector.setHost(host);
              _server.addConnector(connector);
              if (_enableStats) connector.addBean(new ConnectorStatistics());
            } else {
              if (_enableStats) {
                for (Connector connector : connectors) {
                  ((AbstractConnector) connector).addBean(new ConnectorStatistics());
                }
              }
            }

            runnerServerInitialized = true;
          }

          // Create a context
          try (Resource ctx = Resource.newResource(args[i])) {
            if (!ctx.exists()) usage("Context '" + ctx + "' does not exist");

            if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath;

            // Configure the context
            if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) {
              // It is a context config file
              XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
              xmlConfiguration.getIdMap().put("Server", _server);
              ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
              if (contextPathSet) handler.setContextPath(contextPath);
              _contexts.addHandler(handler);
              handler.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            } else {
              // assume it is a WAR file
              WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
              webapp.setConfigurationClasses(__plusConfigurationClasses);
              webapp.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            }
          }
          // reset
          contextPathSet = false;
          contextPath = __defaultContextPath;
          break;
      }
    }

    if (_server == null) usage("No Contexts defined");
    _server.setStopAtShutdown(true);

    switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
      case 1:
        usage("Must specify --stop-key when --stop-port is specified");
        break;

      case 2:
        usage("Must specify --stop-port when --stop-key is specified");
        break;

      case 3:
        ShutdownMonitor monitor = ShutdownMonitor.getInstance();
        monitor.setPort(stopPort);
        monitor.setKey(stopKey);
        monitor.setExitVm(true);
        break;
    }

    if (_logFile != null) {
      NCSARequestLog requestLog = new NCSARequestLog(_logFile);
      requestLog.setExtended(false);
      _logHandler.setRequestLog(requestLog);
    }
  }
 public int getLocalPort() {
   return jettyServer.getConnectors()[0].getLocalPort();
 }
  public static void launchCordovaSim(
      String projectString,
      String rootFolderString,
      String startPageString,
      Integer port,
      String proxy) {
    List<String> parameters = new ArrayList<String>();
    parameters.add(NOT_STANDALONE);

    IContainer rootFolder = null;
    IProject project = null;
    String cordovaEngineLocation = null;
    String cordovaVersion = null;

    if (projectString != null) {
      project = CordovaSimLaunchParametersUtil.getProject(projectString);

      if (project != null) {
        cordovaEngineLocation = CordovaSimLaunchParametersUtil.getCordovaEngineLocation(project);
        cordovaVersion = CordovaSimLaunchParametersUtil.getCordovaVersion(project);
      }

      if (rootFolderString != null) {
        rootFolder = CordovaSimLaunchParametersUtil.getRootFolder(project, rootFolderString);
      } else {
        rootFolder = CordovaSimLaunchParametersUtil.getDefaultRootFolder(project);
      }
    }

    String actualStartPageString = null;
    if (startPageString != null) {
      actualStartPageString = startPageString;
    } else {
      IResource startPage = CordovaSimLaunchParametersUtil.getDefaultStartPage(project, rootFolder);
      IPath startPagePath = CordovaSimLaunchParametersUtil.getRelativePath(rootFolder, startPage);
      if (startPagePath != null) {
        String startPageFromConfigXml =
            CordovaSimLaunchParametersUtil.getDefaultStartPageFromConfigXml(project);
        String startPageParameters =
            CordovaSimLaunchParametersUtil.getStartPageParameters(startPageFromConfigXml);
        if (startPageParameters != null) {
          actualStartPageString = startPagePath.toString() + startPageParameters;
        } else {
          actualStartPageString = startPagePath.toString();
        }
      }
    }

    if (rootFolder != null && actualStartPageString != null) {
      try {
        if (!ServerStorage.getStorage().containsKey(port) && ServerUtil.isPortAvailable(port)) {
          Server server =
              ServerCreator.createServer(project, rootFolder, cordovaEngineLocation, port);
          server.start();

          Connector connector = server.getConnectors()[0];
          port =
              connector
                  .getLocalPort(); // for the case if port equals 0 is requested (any free port)

          ServerStorage.getStorage().put(port, server); // Adding server to the ServerStorage

          parameters.add(rootFolder.getRawLocation().makeAbsolute().toString());
          parameters.add(
              "http://localhost:"
                  + port
                  + "/"
                  + actualStartPageString); //$NON-NLS-1$ //$NON-NLS-2$

          if (cordovaVersion != null) {
            parameters.add("-version"); // $NON-NLS-1$
            parameters.add(cordovaVersion);
          }
          if (proxy != null) {
            parameters.add("-proxy"); // $NON-NLS-1$
            parameters.add(proxy);
          }
          launchCordovaSim(parameters);
        } else {
          showPortInUseMessage(port);
        }
      } catch (Exception e) {
        Activator.logError(e.getMessage(), e);
      }
    } else {
      Display.getDefault()
          .asyncExec(
              new Runnable() {
                @Override
                public void run() {
                  Shell parentShell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
                  if (parentShell == null) {
                    parentShell =
                        PlatformUI.getWorkbench().getDisplay().getShells()[0]; // Hot fix for gtk3
                  }
                  MessageDialog.openError(
                      parentShell,
                      Messages.CordovaSimLauncher_CANNOT_RUN_CORDOVASIM,
                      Messages.CordovaSimLauncher_CANNOT_FIND_ROOT_FOLDER);
                }
              });
    }
  }