protected Handler createHandler() {
    /*TODO: Context "/hub" is here only for backwards compatibility.
    src/org/openqa/grid/web/Hub.java has the following line:
    ''' root.addServlet("/wd/hub/*", DriverServlet.class.getName()); '''
    This seems to imply "/wd/hub" is the correct Context to use everywhere.
    */
    org.mortbay.jetty.servlet.Context old_root =
        new org.mortbay.jetty.servlet.Context(
            server, "/hub", org.mortbay.jetty.servlet.Context.SESSIONS);
    old_root.addServlet(new ServletHolder(new AndroidNativeDriverServlet()), "/*");

    org.mortbay.jetty.servlet.Context root =
        new org.mortbay.jetty.servlet.Context(
            server, "/wd/hub", org.mortbay.jetty.servlet.Context.SESSIONS);
    root.addServlet(new ServletHolder(new AndroidNativeDriverServlet()), "/*");

    org.mortbay.jetty.servlet.Context gridhealthstatus =
        new org.mortbay.jetty.servlet.Context(
            server, "/wd/hub/status", org.mortbay.jetty.servlet.Context.NO_SECURITY);
    gridhealthstatus.addServlet(new ServletHolder(new HealthStatusServlet()), "/*");

    HandlerList handlers = new HandlerList();

    handlers.setHandlers(
        new org.mortbay.jetty.Handler[] {old_root, gridhealthstatus, root, new DefaultHandler()});
    return handlers;
  }
Пример #2
0
  public void start(SoapMonitor soapMonitor, int localPort) {
    Settings settings = soapMonitor.getProject().getSettings();
    server.setThreadPool(new SoapUIJettyThreadPool());
    Context context = new Context(server, ROOT, 0);

    if (sslEndpoint != null) {
      if (sslEndpoint.startsWith(HTTPS)) {
        sslConnector = new SslSocketConnector();
        sslConnector.setKeystore(
            settings.getString(SoapMonitorAction.SecurityTabForm.SSLTUNNEL_KEYSTORE, "JKS"));
        sslConnector.setPassword(
            settings.getString(SoapMonitorAction.SecurityTabForm.SSLTUNNEL_PASSWORD, ""));
        sslConnector.setKeyPassword(
            settings.getString(SoapMonitorAction.SecurityTabForm.SSLTUNNEL_KEYPASSWORD, ""));
        sslConnector.setTruststore(
            settings.getString(SoapMonitorAction.SecurityTabForm.SSLTUNNEL_TRUSTSTORE, "JKS"));
        sslConnector.setTrustPassword(
            settings.getString(
                SoapMonitorAction.SecurityTabForm.SSLTUNNEL_TRUSTSTORE_PASSWORD, ""));
        sslConnector.setNeedClientAuth(false);
        sslConnector.setMaxIdleTime(30000);
        sslConnector.setPort(localPort);

        server.addConnector(sslConnector);
        context.addServlet(new ServletHolder(new TunnelServlet(soapMonitor, sslEndpoint)), ROOT);
      } else {
        if (sslEndpoint.startsWith(HTTP)) {
          connector.setPort(localPort);
          server.addConnector(connector);
          context.addServlet(new ServletHolder(new TunnelServlet(soapMonitor, sslEndpoint)), ROOT);
        } else {
          UISupport.showErrorMessage("Unsupported/unknown protocol tunnel will not start");
          return;
        }
      }
      proxyOrTunnel = false;
    } else {
      proxyOrTunnel = true;
      connector.setPort(localPort);
      server.addConnector(connector);
      context.addServlet(new ServletHolder(new ProxyServlet(soapMonitor)), ROOT);
    }
    try {
      server.start();
    } catch (Exception e) {
      UISupport.showErrorMessage("Error starting monitor: " + e.getMessage());
    }
  }
  @Before
  public void setUp() throws Exception {

    server = new Server();

    //		Context scontext = new Context();
    //		scontext.setContextPath("/");
    //		scontext.setResourceBase(RES_DIR);
    //		// servlet handler?
    //		scontext.addServlet("JSP", "*.jsp",
    //				"org.apache.jasper.servlet.JspServlet");
    //		scontext.addHandler(new ResourceHandler());

    Context root = new Context(server, "/", Context.SESSIONS);
    root.setContextPath("/");
    root.setResourceBase(RES_DIR);
    ServletHolder sh = new ServletHolder(org.apache.jasper.servlet.JspServlet.class);
    root.addServlet(sh, "*.jsp");

    conf = new Configuration();
    conf.addResource("nutch-default.xml");
    conf.addResource("nutch-site-test.xml");

    http = new Http();
    http.setConf(conf);
  }
Пример #4
0
  public void init() throws Exception {
    initializeEmitter();
    initializeMonitors();
    initializeMergerConfig();
    initializeTaskToolbox();
    initializeJacksonInjections();
    initializeJacksonSubtypes();
    initializeCuratorFramework();
    initializeCuratorCoordinator();
    initializeTaskMonitor();
    initializeServer();

    final ScheduledExecutorFactory scheduledExecutorFactory =
        ScheduledExecutors.createFactory(lifecycle);
    final ScheduledExecutorService globalScheduledExec =
        scheduledExecutorFactory.create(1, "Global--%d");
    final MonitorScheduler monitorScheduler =
        new MonitorScheduler(
            configFactory.build(MonitorSchedulerConfig.class),
            globalScheduledExec,
            emitter,
            monitors);
    lifecycle.addManagedInstance(monitorScheduler);

    final Context root = new Context(server, "/", Context.SESSIONS);

    root.addServlet(new ServletHolder(new StatusServlet()), "/status");
    root.addServlet(new ServletHolder(new DefaultServlet()), "/mmx/*");
    root.addFilter(GuiceFilter.class, "/mmx/indexer/worker/v1/*", 0);
  }
Пример #5
0
 private static void addDefaultServletTo(Context parent) {
   ServletHolder holder = new ServletHolder(DefaultServlet.class);
   holder.setInitParameter("dirAllowed", "false");
   holder.setInitParameter("welcomeServlets", "index.html");
   holder.setInitParameter("resourceBase", ".");
   parent.addServlet(holder, "/*");
 }
Пример #6
0
 @Before
 public void setup() throws Exception {
   server = new Server(8181);
   Context root = new Context(server, "/arquillian-protocol", Context.SESSIONS);
   root.addServlet(ServletTestRunner.class, ServletMethodExecutor.ARQUILLIAN_SERVLET_MAPPING);
   server.start();
 }
Пример #7
0
 public static void main(String[] args) throws Exception {
   Server server = new Server(9008);
   Context root = new Context(server, "/", Context.SESSIONS);
   //		addDefaultServletTo(root);
   root.addServlet(new ServletHolder(new MyReceiveServlet()), "/");
   server.start();
   server.join();
 }
Пример #8
0
  public static void main(String[] args) throws Exception {
    final ContextHandlerCollection contexts;
    final HubConfiguration configuration;
    final Server server;
    final Context root;

    configuration = HubRegistry.registry().gridConfiguration().getHub();
    server = new Server(configuration.getPort());

    contexts = new ContextHandlerCollection();
    server.setHandler(contexts);

    root = new Context(contexts, "/", Context.SESSIONS);
    root.addServlet(new ServletHolder(new WebDriverServlet()), "/wd/*");
    root.addServlet(new ServletHolder(new HubServlet()), "/selenium-server/driver/*");
    root.addServlet(new ServletHolder(new ConsoleServlet()), "/console");
    root.addServlet(new ServletHolder(new RegistrationServlet()), "/registration-manager/register");
    root.addServlet(
        new ServletHolder(new UnregistrationServlet()), "/registration-manager/unregister");
    root.addServlet(new ServletHolder(new LifecycleManagerServlet()), "/lifecycle-manager");
    root.addServlet(new ServletHolder(new HeartbeatServlet()), "/heartbeat");

    startRemoteControlPoller();
    ensureRemoteControlPollerStopOnShutdown();

    server.start();
    server.join();
  }
Пример #9
0
  /** Starts the server for end-to-end tests. */
  private Server createServer(int port) throws Exception {
    Server newServer = new Server(port);

    // Attach the test resources in /endtoend as static content for the test
    ResourceHandler resources = new ResourceHandler();
    URL resource = EndToEndTest.class.getResource("/endtoend");
    resources.setBaseResource(Resource.newResource(resource));
    newServer.addHandler(resources);

    Context context = new Context(newServer, "/", Context.SESSIONS);
    context.addEventListener(new GuiceServletContextListener());

    Map<String, String> initParams = Maps.newHashMap();
    String modules =
        Join.join(
            ":",
            EndToEndModule.class.getName(),
            DefaultGuiceModule.class.getName(),
            PropertiesModule.class.getName(),
            OAuthModule.class.getName());

    initParams.put(GuiceServletContextListener.MODULES_ATTRIBUTE, modules);
    context.setInitParams(initParams);

    // Attach the gadget rendering servlet
    ServletHolder gadgetServletHolder = new ServletHolder(new GadgetRenderingServlet());
    context.addServlet(gadgetServletHolder, GADGET_BASE);

    // Attach DataServiceServlet, wrapped in a proxy to fake errors
    ServletHolder restServletHolder =
        new ServletHolder(new ForceErrorServlet(new DataServiceServlet()));
    context.addServlet(restServletHolder, REST_BASE);
    context.addFilter(AuthenticationServletFilter.class, REST_BASE, 0);

    // Attach JsonRpcServlet, wrapped in a proxy to fake errors
    ServletHolder rpcServletHolder = new ServletHolder(new ForceErrorServlet(new JsonRpcServlet()));
    context.addServlet(rpcServletHolder, JSON_RPC_BASE);
    context.addFilter(AuthenticationServletFilter.class, JSON_RPC_BASE, 0);

    // Attach the ConcatProxyServlet - needed for
    ServletHolder concatHolder = new ServletHolder(new ConcatProxyServlet());
    context.addServlet(concatHolder, CONCAT_BASE);

    return newServer;
  }
Пример #10
0
 protected void setUp() throws Exception {
   LOG.info("********** " + toString() + " [setUp] **********");
   super.setUp();
   server = new Server(PORT);
   Context root = new Context(server, "/", Context.SESSIONS);
   ServletHolder holder = new ServletHolder(new RestServlet());
   holder.setInitParameter(
       "persistence-context", "h2-backend"); // TODO Set this based on which datastore in use
   root.addServlet(holder, "/dn/*");
   server.start();
 }
Пример #11
0
  /** Run couchdb-lucene. */
  public static void main(String[] args) throws Exception {
    final HierarchicalINIConfiguration configuration =
        new HierarchicalINIConfiguration(
            Main.class.getClassLoader().getResource("couchdb-lucene.ini"));
    configuration.setReloadingStrategy(new FileChangedReloadingStrategy());

    final File dir = new File(configuration.getString("lucene.dir", "indexes"));

    if (dir == null) {
      LOG.error("lucene.dir not set.");
      System.exit(1);
    }
    if (!dir.exists() && !dir.mkdir()) {
      LOG.error("Could not create " + dir.getCanonicalPath());
      System.exit(1);
    }
    if (!dir.canRead()) {
      LOG.error(dir + " is not readable.");
      System.exit(1);
    }
    if (!dir.canWrite()) {
      LOG.error(dir + " is not writable.");
      System.exit(1);
    }
    LOG.info("Index output goes to: " + dir.getCanonicalPath());

    final Server server = new Server();
    final SelectChannelConnector connector = new SelectChannelConnector();
    connector.setHost(configuration.getString("lucene.host", "localhost"));
    connector.setPort(configuration.getInt("lucene.port", 5985));

    LOG.info("Accepting connections with " + connector);

    server.setConnectors(new Connector[] {connector});
    server.setStopAtShutdown(true);
    server.setSendServerVersion(false);

    HttpClientFactory.setIni(configuration);
    final HttpClient httpClient = HttpClientFactory.getInstance();

    final LuceneServlet servlet = new LuceneServlet(httpClient, dir, configuration);

    final Context context = new Context(server, "/", Context.NO_SESSIONS | Context.NO_SECURITY);
    context.addServlet(new ServletHolder(servlet), "/*");
    context.addFilter(new FilterHolder(new GzipFilter()), "/*", Handler.DEFAULT);
    context.setErrorHandler(new JSONErrorHandler());
    server.setHandler(context);

    server.start();
    server.join();
  }
 private static void setUpJetty() throws Exception {
   if (jettyServer == null) {
     int port = 8080;
     jettyServer = new Server(port);
     baseUrl = "http://localhost:" + port;
     Context jettyContext = new Context(jettyServer, "/");
     jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/echo");
     jettyContext.addServlet(new ServletHolder(new GzipServlet()), "/gzip");
     jettyContext.addServlet(new ServletHolder(new StatusServlet(200)), "/status/ok");
     jettyContext.addServlet(new ServletHolder(new StatusServlet(404)), "/status/notfound");
     jettyContext.addServlet(new ServletHolder(new MethodServlet("DELETE")), "/methods/delete");
     jettyContext.addServlet(new ServletHolder(new MethodServlet("GET")), "/methods/get");
     jettyContext.addServlet(new ServletHolder(new MethodServlet("HEAD")), "/methods/head");
     jettyContext.addServlet(new ServletHolder(new MethodServlet("OPTIONS")), "/methods/options");
     jettyContext.addServlet(new ServletHolder(new PostServlet()), "/methods/post");
     jettyContext.addServlet(new ServletHolder(new MethodServlet("PUT")), "/methods/put");
     jettyServer.start();
   }
 }
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    // assumes that this directory contains .html and .jsp files
    // This is just a directory within your source tree, and can be exported
    // as part of your normal .jar
    final String WEBAPPDIR = "jetty/embed/yanwmapp";

    final Server server = new Server(8080);

    final String CONTEXTPATH = "/admin";

    // for localhost:port/admin/index.html and whatever else is in the webapp directory
    final URL warUrl = EmbeddingJettyServletsJsps.class.getClassLoader().getResource(WEBAPPDIR);
    final String warUrlString = warUrl.toExternalForm();
    server.setHandler(new WebAppContext(warUrlString, CONTEXTPATH));

    String whatever = "see you!";

    // for localhost:port/servlets/cust, etc.
    final Context context = new Context(server, "/servlets", Context.SESSIONS);
    context.addServlet(new ServletHolder(new CustomerServlet(whatever)), "/cust");
    context.addServlet(new ServletHolder(new UserServlet(whatever)), "/user");

    server.start();
  }
Пример #14
0
 @Test
 @TestJetty
 public void testJetty() throws Exception {
   Context context = new Context();
   context.setContextPath("/");
   context.addServlet(MyServlet.class, "/bar");
   Server server = TestJettyHelper.getJettyServer();
   server.addHandler(context);
   server.start();
   URL url = new URL(TestJettyHelper.getJettyURL(), "/bar");
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
   BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   assertEquals(reader.readLine(), "foo");
   reader.close();
 }
Пример #15
0
  /** Call this once to bring up the server */
  private void initServer() {
    String _servername = this.configuration.getConfiguration(RemoteAPI.class, "export.server");
    String servername = _servername == null ? "127.0.0.1" : _servername;

    String _port = this.configuration.getConfiguration(RemoteAPIImpl.class, "export.port");
    int port = getFreePort();
    if (_port != null) {
      port = Integer.parseInt(_port);
    }

    // Set the location and server
    this.location = "http://" + servername + ":" + port;
    this.server = new Server(port);
    this.bridge = new JSONRPCBridge(); // JSONRPCBridge.getGlobalBridge();

    // Create context and our specially hacked jsonrpc servlet.
    final Context context = new Context(this.server, "/", Context.SESSIONS);
    final JSONRPCServlet servlet =
        new JSONRPCServlet() {
          /** */
          private static final long serialVersionUID = 7129007024968608285L;

          @Override
          public void service(HttpServletRequest arg0, HttpServletResponse arg1)
              throws IOException {

            // Register our global bridge, so jabsorb does not complain about
            // sessionless globals
            final HttpSession session = arg0.getSession();
            session.setAttribute("JSONRPCBridge", RemoteAPIImpl.this.bridge);

            super.service(arg0, arg1);
          }
        };

    final ServletHolder servletholder = new ServletHolder(servlet);

    servletholder.setInitParameter("gzip_threshold", "200");
    context.addServlet(servletholder, "/*");

    try {
      this.server.start();
    } catch (final Exception e) {
      e.printStackTrace();
    }
  }
Пример #16
0
  @Override
  protected void doSetUp() throws Exception {
    httpServer = new Server(SERVER_PORT);

    Context c = new Context(httpServer, "/", Context.SESSIONS);
    c.addServlet(new ServletHolder(new MuleAjaxServlet()), "/ajax/*");
    c.addEventListener(
        new ServletContextListener() {
          public void contextInitialized(ServletContextEvent sce) {
            sce.getServletContext().setAttribute(MuleProperties.MULE_CONTEXT_PROPERTY, muleContext);
          }

          public void contextDestroyed(ServletContextEvent sce) {}
        });

    httpServer.start();

    super.doSetUp();
  }
Пример #17
0
  public void setUp(boolean redirection) throws Exception {
    conf = new Configuration();
    conf.addResource("nutch-default.xml");
    conf.addResource("nutch-site-test.xml");

    http = new Http();
    http.setConf(conf);

    server = new Server();

    if (redirection) {
      root = new Context(server, "/redirection", Context.SESSIONS);
      root.setAttribute("newContextURL", "/redirect");
    } else {
      root = new Context(server, "/", Context.SESSIONS);
    }

    ServletHolder sh = new ServletHolder(org.apache.jasper.servlet.JspServlet.class);
    root.addServlet(sh, "*.jsp");
    root.setResourceBase(RES_DIR);
  }
  /** Creates and starts the shutdown service. */
  public synchronized void start() {
    if (adminService.isRunning()) {
      throw new IllegalStateException("Admin service is already running");
    }

    Context commandContext = new Context(adminService, "/", false, false);

    adminCommands.add(buildShutdownCommand());

    ServletHolder servletHolder;
    for (AbstractAdminCommand command : adminCommands) {
      servletHolder = new ServletHolder(command);
      commandContext.addServlet(servletHolder, command.getCommandPath());
    }

    if (adminPassword != null) {
      FilterHolder passwordFiler = new FilterHolder(new PasswordProtectFilter(adminPassword));
      commandContext.addFilter(passwordFiler, "/*", Handler.REQUEST);
    }

    JettyRunThread shutdownServiceRunThread = new JettyRunThread(adminService);
    shutdownServiceRunThread.start();
  }
  @Test
  public void testContextClose() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    int port = FreePortScanner.getFreePort();
    Server jettyServer = new Server(port);
    Context jettyContext = new Context(jettyServer, "/");
    jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/");
    jettyServer.start();
    WebServiceConnection connection = null;
    try {

      StaticApplicationContext appContext = new StaticApplicationContext();
      appContext.registerSingleton("messageSender", CommonsHttpMessageSender.class);
      appContext.refresh();

      CommonsHttpMessageSender messageSender =
          appContext.getBean("messageSender", CommonsHttpMessageSender.class);
      connection = messageSender.createConnection(new URI("http://localhost:" + port));

      appContext.close();

      connection.send(new SaajSoapMessage(messageFactory.createMessage()));
      connection.receive(new SaajSoapMessageFactory(messageFactory));
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (IOException ex) {
          // ignore
        }
      }
      if (jettyServer.isRunning()) {
        jettyServer.stop();
      }
    }
  }
Пример #20
0
  @BeforeClass
  @SuppressWarnings("unchecked")
  public static void setUpClass() throws Exception {

    URI webappUri = EmbeddedJettyServer.extractResourceDir("webapp", true);
    server = new Server(port);

    ServletHolder jerseyServletHolder = new ServletHolder(ServletContainer.class);
    jerseyServletHolder.setInitParameter(
        "com.sun.jersey.config.property.resourceConfigClass",
        "com.sun.jersey.api.core.PackagesResourceConfig");
    jerseyServletHolder.setInitParameter(
        "com.sun.jersey.config.property.packages", "fr.inria.edelweiss.kgramserver.webservice");
    Context servletCtx = new Context(server, "/kgram", Context.SESSIONS);
    servletCtx.addServlet(jerseyServletHolder, "/*");
    logger.info("----------------------------------------------");
    logger.info("Corese/KGRAM endpoint started on http://localhost:" + port + "/kgram");
    logger.info("----------------------------------------------");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase(webappUri.getRawPath());
    ContextHandler staticContextHandler = new ContextHandler();
    staticContextHandler.setContextPath("/");
    staticContextHandler.setHandler(resource_handler);
    logger.info("----------------------------------------------");
    logger.info("Corese/KGRAM webapp UI started on http://localhost:" + port);
    logger.info("----------------------------------------------");

    HandlerList handlers_s1 = new HandlerList();
    handlers_s1.setHandlers(new Handler[] {staticContextHandler, servletCtx});
    server.setHandler(handlers_s1);

    try {
      server.start();
    } catch (Exception e) {
      e.printStackTrace();
    }

    ///// Data extraction
    humanData = File.createTempFile("human", ".rdf");
    FileWriter fw = new FileWriter(humanData);
    InputStream is =
        RDFS_entailmentsTest.class.getClassLoader().getResourceAsStream("human_2007_09_11.rdf");
    int c;
    while ((c = is.read()) != -1) {
      fw.write(c);
    }
    is.close();
    fw.close();

    humanOnt = File.createTempFile("humanOnt", ".rdfs");
    fw = new FileWriter(humanOnt);
    is = RDFS_entailmentsTest.class.getClassLoader().getResourceAsStream("human_2007_09_11.rdfs");
    while ((c = is.read()) != -1) {
      fw.write(c);
    }
    is.close();
    fw.close();

    ///// Data upload
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(new URI("http://localhost:" + port + "/kgram"));

    // entailments
    MultivaluedMap formData = new MultivaluedMapImpl();
    formData.add("entailments", "true");
    service.path("sparql").path("reset").post(formData);

    formData = new MultivaluedMapImpl();
    formData.add("remote_path", humanOnt.getAbsolutePath());
    service.path("sparql").path("load").post(formData);

    formData = new MultivaluedMapImpl();
    formData.add("remote_path", humanData.getAbsolutePath());
    service.path("sparql").path("load").post(formData);
  }
  /**
   * Initialize the embedded Jetty server. This sets up the server and adds the connectors and a
   * thread pool.
   *
   * @throws Exception error occurs initializing server
   */
  public synchronized void init() throws Exception {
    this.logger.debug("Starting the Scheduling Server server up.");

    final List<Connector> connectors = new ArrayList<Connector>();

    /* Get the configuration service. */
    final ServiceReference<Config> ref = this.bundleContext.getServiceReference(Config.class);
    Config config = null;
    if (ref == null || (config = this.bundleContext.getService(ref)) == null) {
      this.logger.error(
          "Unable to get configuration service reference so unable "
              + "to load server configuration.");
      throw new Exception("Unable to load server configuration.");
    }

    /* --------------------------------------------------------------------
     * ---- 1. Create the server. -----------------------------------------
     * ----------------------------------------------------------------- */
    /* The server is the main class for the Jetty HTTP server. It uses a
     * connectors to receive requests, a serverContext to handle requests and
     * a thread pool to manage concurrent requests.
     */
    this.server = new Server();

    /* --------------------------------------------------------------------
     * ---- 2. Create and configure the connectors. ------------------------
     * ----------------------------------------------------------------- */
    /* The connectors receives requests and calls handle on handler object
     * to handle a request. */
    final Connector http = new SelectChannelConnector();
    String tmp = config.getProperty("Listening_Port", String.valueOf(ServerImpl.DEFAULT_HTTP_PORT));
    try {
      http.setPort(Integer.parseInt(tmp));
      this.logger.info("Listening on port (HTTP) " + tmp + '.');
    } catch (NumberFormatException nfe) {
      http.setPort(ServerImpl.DEFAULT_HTTP_PORT);
      this.logger.error(
          "Invalid configuration for the Scheduling Server HTTP listening port. "
              + tmp
              + " is "
              + "not a valid port number. Using the default of "
              + ServerImpl.DEFAULT_HTTP_PORT
              + '.');
    }
    connectors.add(http);

    /* HTTPS connector. */
    //	    final SslSelectChannelConnector https = new SslSelectChannelConnector();
    //	    tmp = config.getProperty("Listening_Port_HTTPS",
    // String.valueOf(ServerImpl.DEFAULT_HTTPS_PORT));
    //	    try
    //	    {
    //	        https.setPort(Integer.parseInt(tmp));
    //	    }
    //	    catch (NumberFormatException nfe)
    //	    {
    //	        https.setPort(ServerImpl.DEFAULT_HTTPS_PORT);
    //	        this.logger.info("Invalid configuration for the Scheduling Server HTTPS listening
    // port." + tmp + " is " +
    //	                "not a valid port number. Using the default of " +
    // ServerImpl.DEFAULT_HTTPS_PORT + '.');
    //	    }
    //	    /* TODO Set up SSL engine. */
    //	    connectors.add(https);

    this.server.setConnectors(connectors.toArray(new Connector[connectors.size()]));

    /* --------------------------------------------------------------------
     * ---- 3. Create and configure the request thread pool. --------------
     * ----------------------------------------------------------------- */
    int concurrentReqs = 100;
    tmp = config.getProperty("Concurrent_Requests", "100");
    try {
      concurrentReqs = Integer.parseInt(tmp);
      this.logger.info("Allowable concurrent requests is " + concurrentReqs + ".");
    } catch (NumberFormatException nfe) {
      this.logger.warn(
          tmp
              + " is not a valid number of concurrent requests. Using the default of "
              + concurrentReqs
              + '.');
    }
    this.threadPool = new QueuedThreadPool(concurrentReqs);
    this.server.setThreadPool(this.threadPool);

    /* --------------------------------------------------------------------
     * ---- 4. Set up the content container and the primoridal  -----------
     * ----    context for the root path. ---------------------------------
     * ----------------------------------------------------------------- */
    /* The context container is used to keep each context in isolation
     * from each other, stopping classes leaking across servlets and
     * causing problems. */
    this.contextCollection = new ContextHandlerCollection();
    this.server.addHandler(this.contextCollection);

    final Context context = new Context(Context.SESSIONS);
    context.setContextPath("/");
    this.contextCollection.addHandler(context);
    this.contexts.put(new Object(), context);

    final ServletHolder holder = new ServletHolder(new RootServlet());
    context.addServlet(holder, "/");
  }
  /**
   * Adds a servlet to hosted on server based on the provided service reference. If the server is
   * started, it is briefly stopped to add the servlet and is then restarted.
   *
   * @param ref service reference pointing to a ServletContainerService service
   */
  public synchronized void addService(final ServiceReference<ServletContainerService> ref) {
    boolean wasRunning = false;
    try {
      final ServletContainerService serv = this.bundleContext.getService(ref);
      ServletContainer containers[] = serv.getServlets();
      if (containers.length == 0) {
        this.logger.error(
            "Server registration from bundle "
                + ref.getBundle().getSymbolicName()
                + " does not contain a servlet so it cannot be hosted. This is a bug.");
        throw new IllegalArgumentException("Servlet is empty.");
      }

      /* If running, stop the server. */
      wasRunning = this.server.isStarted() || this.server.isStarting();
      if (wasRunning) this.server.stop();

      /* Create the context. */
      final String contextPath =
          serv.getOverriddingPathSpec() == null
              ? '/' + ref.getBundle().getSymbolicName()
              : serv.getOverriddingPathSpec();
      this.logger.info(
          "The servlets for bundle "
              + ref.getBundle().getSymbolicName()
              + " will be hosted on "
              + "path "
              + contextPath
              + '.');
      final Context context = new Context(this.server, contextPath, Context.SESSIONS);
      this.contexts.put(ref.getProperty(Constants.SERVICE_ID), context);

      /* Populate a context with all the servlets to run. */
      for (ServletContainer cont : containers) {
        final ServletHolder holder = new ServletHolder(cont.getServlet());
        if (cont.isAxis()) {
          URL repoUrl = cont.getServlet().getClass().getResource("/META-INF/repo");
          if (repoUrl != null) {
            this.logger.debug(
                "Axis repository for bundle "
                    + ref.getBundle().getSymbolicName()
                    + " has URI "
                    + repoUrl.toURI().toString()
                    + '.');
            holder.setInitParameter("axis2.repository.url", repoUrl.toURI().toString());
          } else {
            this.logger.error(
                "Unable to find the repository resource from the "
                    + ref.getBundle().getSymbolicName()
                    + " bundle. There must be a 'repo' folder in the "
                    + "bundle META-INF folder containing the services list (services.list) and a service "
                    + "archive file with the service WSDL and service descriptor (services.xml).");
            continue;
          }
        }
        this.logger.debug(
            "Deploying servlet from the "
                + ref.getBundle().getSymbolicName()
                + " bundle with service ID: "
                + ref.getProperty(Constants.SERVICE_ID));
        context.addServlet(holder, cont.getPath());
      }

      this.contextCollection.addHandler(context);
    } catch (Exception ex) {
      ex.printStackTrace();
      this.logger.error(
          "Failed adding server service from bundle "
              + ref.getBundle().getSymbolicName()
              + " because of exception with message: "
              + ex.getMessage()
              + '.');
    } finally {
      /* Restore the server state. */
      if (wasRunning && this.server.isStopped()) {
        try {
          this.logger.debug("Restarting Scheduling server servlet server.");
          this.server.start();
        } catch (Exception e) {
          this.logger.error(
              "Failed starting Jetty server because of exception with message: "
                  + e.getMessage()
                  + '.');
        }
      }
    }
  }
Пример #23
0
 public void addServlet(Class<? extends HttpServlet> klass, String where) {
   root.addServlet(klass, where);
 }
Пример #24
0
  /**
   * Starts the container and hence the embedded jetty server.
   *
   * @throws Exception if there is an issue while starting the server
   */
  @PostConstruct
  public void init() throws Exception {
    try {
      if (alreadyInited.compareAndSet(false, true)) {
        initAdminContainerConfigIfNeeded();
        initAdminRegistryIfNeeded();

        if (!adminContainerConfig.shouldEnable()) {
          return;
        }

        if (adminContainerConfig.shouldScanClassPathForPluginDiscovery()) {
          adminPageRegistry.registerAdminPagesWithClasspathScan();
        }

        Injector adminResourceInjector;
        if (shouldShareResourcesWithParentInjector()) {
          adminResourceInjector = appInjector.createChildInjector(buildAdminPluginsGuiceModules());
        } else {
          adminResourceInjector =
              LifecycleInjector.builder()
                  .inStage(Stage.DEVELOPMENT)
                  .usingBasePackages("com.netflix.explorers")
                  .withModules(buildAdminPluginsGuiceModules())
                  .build()
                  .createInjector();
          adminResourceInjector.getInstance(LifecycleManager.class).start();
        }

        server = new Server(adminContainerConfig.listenPort());

        // redirect filter based on configurable RedirectRules
        final Context rootHandler = new Context();
        rootHandler.setContextPath("/");
        rootHandler.addFilter(
            new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)),
            "/*",
            Handler.DEFAULT);
        rootHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*");

        // admin page template resources
        AdminResourcesFilter arfTemplatesResources =
            adminResourceInjector.getInstance(AdminResourcesFilter.class);
        arfTemplatesResources.setPackages(adminContainerConfig.jerseyViewableResourcePkgList());

        final Context adminTemplatesResHandler = new Context();
        adminTemplatesResHandler.setContextPath(adminContainerConfig.templateResourceContext());
        adminTemplatesResHandler.setSessionHandler(new SessionHandler());
        adminTemplatesResHandler.addFilter(LoggingFilter.class, "/*", Handler.DEFAULT);
        adminTemplatesResHandler.addFilter(
            new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)),
            "/*",
            Handler.DEFAULT);
        adminTemplatesResHandler.addFilter(
            new FilterHolder(arfTemplatesResources), "/*", Handler.DEFAULT);
        adminTemplatesResHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*");

        // admin page data resources
        final String jerseyPkgListForAjaxResources =
            appendCoreJerseyPackages(adminPageRegistry.buildJerseyResourcePkgListForAdminPages());
        AdminResourcesFilter arfDataResources =
            adminResourceInjector.getInstance(AdminResourcesFilter.class);
        arfDataResources.setPackages(jerseyPkgListForAjaxResources);

        final Context adminDataResHandler = new Context();
        adminDataResHandler.setContextPath(adminContainerConfig.ajaxDataResourceContext());
        adminDataResHandler.addFilter(
            new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)),
            "/*",
            Handler.DEFAULT);
        adminDataResHandler.addFilter(new FilterHolder(arfDataResources), "/*", Handler.DEFAULT);
        adminDataResHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*");

        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setDaemon(true);
        server.setThreadPool(threadPool);

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(
            new Handler[] {adminTemplatesResHandler, adminDataResHandler, rootHandler});
        server.setHandler(handlers);

        server.start();

        final Connector connector = server.getConnectors()[0];
        serverPort = connector.getLocalPort();
      }
    } catch (Exception e) {
      logger.error("Exception in building AdminResourcesContainer ", e);
    }
  }