Exemplo n.º 1
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);
  }
  @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);
  }
  /**
   * Runs the Jetty Embedded DTS Web Service.
   *
   * @throws Exception if the Server fails to start
   */
  public void run() throws Exception {
    final AbstractApplicationContext ctx =
        new ClassPathXmlApplicationContext(
            new String[] {
              "/org/dataminx/dts/ws/application-context.xml",
              "/org/dataminx/dts/ws/embedded-jetty-context.xml"
            });
    ctx.registerShutdownHook();

    final Server server = (Server) ctx.getBean("jettyServer");

    ServletContext servletContext = null;

    for (final Handler handler : server.getHandlers()) {
      if (handler instanceof Context) {
        final Context context = (Context) handler;

        servletContext = context.getServletContext();
      }
    }

    final XmlWebApplicationContext wctx = new XmlWebApplicationContext();
    wctx.setParent(ctx);
    wctx.setConfigLocation("");
    wctx.setServletContext(servletContext);
    wctx.refresh();

    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wctx);

    server.start();
  }
Exemplo n.º 4
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();
 }
Exemplo n.º 5
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();
 }
Exemplo n.º 6
0
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    Context root = new Context(server, "/");
    root.setResourceBase("./pom.xml");
    root.setHandler(new ResourceHandler());

    server.setStopAtShutdown(true);
    server.start();
  }
Exemplo n.º 7
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();
 }
Exemplo n.º 8
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();
  }
Exemplo n.º 9
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();
  }
Exemplo n.º 10
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());
    }
  }
Exemplo n.º 11
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, "/*");
 }
Exemplo n.º 12
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();
 }
Exemplo n.º 13
0
 @Override
 @After
 public void tearDown() throws Exception {
   httpStore.close();
   server.stop();
   context.destroy();
 }
Exemplo n.º 14
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();
    }
  }
 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();
   }
 }
Exemplo n.º 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();
  }
Exemplo n.º 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);
  }
Exemplo n.º 18
0
  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;
  }
Exemplo n.º 19
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;
  }
  /** 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();
  }
  /**
   * @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();
  }
  @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();
      }
    }
  }
Exemplo n.º 23
0
 @Override
 @Before
 public void setUp() throws Exception {
   super.setUp();
   context =
       ServerTestUtils.getJettyServer(
           getClusterXml(),
           getStoreDefXml(),
           getValidStoreName(),
           RequestFormatType.VOLDEMORT_V1,
           getLocalNode().getHttpPort());
   server = context.getServer();
   httpStore =
       ServerTestUtils.getHttpStore(
           getValidStoreName(), RequestFormatType.VOLDEMORT_V1, getLocalNode().getHttpPort());
   url = getLocalNode().getHttpUrl().toString();
 }
Exemplo n.º 24
0
  public void startServer() throws Exception {
    basedir = getBasedir();

    // ----------------------------------------------------------------------------
    // Context Setup
    // ----------------------------------------------------------------------------

    context = new HashMap();

    context.put("basedir", getBasedir());

    customizeContext(new DefaultContext(context));

    boolean hasPlexusHome = context.containsKey("plexus.home");

    if (!hasPlexusHome) {
      File f = getTestFile("target/plexus-home");

      if (!f.isDirectory()) {
        f.mkdir();
      }

      context.put("plexus.home", f.getAbsolutePath());
    }

    // ----------------------------------------------------------------------------
    // Configuration
    // ----------------------------------------------------------------------------

    String config = getCustomConfigurationName();
    InputStream is;

    if (config != null) {
      is = getClass().getClassLoader().getResourceAsStream(config);

      if (is == null) {
        try {
          File configFile = new File(config);

          if (configFile.exists()) {
            is = new FileInputStream(configFile);
          }
        } catch (IOException e) {
          throw new Exception("The custom configuration specified is null: " + config);
        }
      }

    } else {
      config = getConfigurationName(null);

      is = getClass().getClassLoader().getResourceAsStream(config);
    }

    // Look for a configuration associated with this test but return null if we
    // can't find one so the container doesn't look for a configuration that we
    // know doesn't exist. Not all tests have an associated Foo.xml for testing.

    if (is == null) {
      config = null;
    } else {
      is.close();
    }

    // ----------------------------------------------------------------------------
    // Create the container
    // ----------------------------------------------------------------------------

    container = createContainerInstance(context, config);

    // ----------------------------------------------------------------------------
    // Create the DavServerManager
    // ----------------------------------------------------------------------------

    manager = (DavServerManager) container.lookup(DavServerManager.ROLE, getProviderHint());

    // ----------------------------------------------------------------------------
    // Create the jetty server
    // ----------------------------------------------------------------------------

    System.setProperty("DEBUG", "");
    System.setProperty("org.mortbay.log.class", "org.slf4j.impl.SimpleLogger");

    server = new Server(PORT);
    Context root = new Context(server, "/", Context.SESSIONS);
    ServletHandler servletHandler = root.getServletHandler();
    root.setContextPath("/");
    root.setAttribute(PlexusConstants.PLEXUS_KEY, container);

    // ----------------------------------------------------------------------------
    // Configure the webdav servlet
    // ----------------------------------------------------------------------------

    ServletHolder holder =
        servletHandler.addServletWithMapping(BasicWebDavServlet.class, "/projects/*");

    // Initialize server contents directory.
    File serverContentsDir = new File("target/test-server/");

    FileUtils.deleteDirectory(serverContentsDir);
    if (serverContentsDir.exists()) {
      throw new IllegalStateException(
          "Unable to execute test, server contents test directory ["
              + serverContentsDir.getAbsolutePath()
              + "] exists, and cannot be deleted by the test case.");
    }

    if (!serverContentsDir.mkdirs()) {
      throw new IllegalStateException(
          "Unable to execute test, server contents test directory ["
              + serverContentsDir.getAbsolutePath()
              + "] cannot be created.");
    }

    holder.setInitParameter("dav.root", serverContentsDir.getAbsolutePath());

    // ----------------------------------------------------------------------------
    // Start the jetty server
    // ----------------------------------------------------------------------------

    server.start();
  }
  /**
   * 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()
                  + '.');
        }
      }
    }
  }
Exemplo n.º 27
0
  private synchronized void enableRemoteAccess() throws Exception {

    if (remoteAccessForward == null) {
      logger.fine("enabling remote access");
      Connector connector = new SelectChannelConnector();
      connector.setHost(LOCALHOST);
      connector.setPort(Constants.LOCAL_WEB_SERVER_PORT_AUTH);

      authenticatedServer = new Server();
      authenticatedServer.addConnector(connector);

      // sets the thread pool (just so it is deamon=true)
      QueuedThreadPool threadPool = new QueuedThreadPool();
      threadPool.setMinThreads(5);
      // threadPool.setMaxThreads(10);
      threadPool.setName("Auth Jetty thread pool");
      threadPool.setDaemon(true);
      authenticatedServer.setThreadPool(threadPool);

      Constraint constraint = new Constraint();
      constraint.setName(Constraint.__BASIC_AUTH);
      constraint.setRoles(new String[] {"remote_user"});
      constraint.setAuthenticate(true);

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

      SecurityHandler securityHandler = new SecurityHandler();
      securityHandler.setUserRealm(
          new ExtraSaltHashUserRealm(
              RemoteAccessConfig.usesMD5Sha1Password(),
              "OneSwarm Remote",
              RemoteAccessConfig.REMOTE_ACCESS_FILE.getCanonicalPath()));
      securityHandler.setConstraintMappings(new ConstraintMapping[] {cm});

      ContextHandlerCollection contexts = new ContextHandlerCollection();

      authenticatedServer.setHandler(contexts);
      Context root = new Context(contexts, "/", Context.NO_SESSIONS);

      root.addFilter(new FilterHolder(new GzipFilter()), "/*", Handler.ALL);

      MultiHandler mh = new MultiHandler(coreInterface, true);

      if (System.getProperty("com.sun.management.jmxremote") != null) {
        RequestLogHandler requestLogHandler = new RequestLogHandler();

        NCSARequestLog requestLog = new NCSARequestLog("/tmp/jetty-yyyy_mm_dd.remoterequest.log");
        requestLog.setRetainDays(1);
        requestLog.setAppend(false);
        requestLog.setExtended(true);
        requestLog.setLogTimeZone("GMT");
        requestLogHandler.setRequestLog(requestLog);

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[] {mh, requestLogHandler});
        root.setHandler(handlers);
      } else {
        root.setHandler(mh);
      }

      root.addHandler(securityHandler);

      // make sure that the class loader can find all classes in the
      // osgwtui
      // plugin dir...
      root.setClassLoader(pluginInterface.getPluginClassLoader());

      authenticatedServer.start();

      remoteAccessForward = new RemoteAccessForward();
      remoteAccessForward.start();
      logger.fine("remote access enabled");
    }
    coreInterface.setRemoteAccess(remoteAccessForward);
  }
Exemplo n.º 28
0
 public void addServlet(Class<? extends HttpServlet> klass, String where) {
   root.addServlet(klass, where);
 }
Exemplo n.º 29
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);
    }
  }
Exemplo n.º 30
0
  public void initialize(PluginInterface pluginInterface) throws PluginException {
    this.coreInterface = new CoreInterface(pluginInterface);

    // make sure to unload in case of shutdown

    this.pluginInterface = pluginInterface;

    logger.fine("oneswarm ui plugin loaded");

    Connector connector = new SelectChannelConnector();
    connector.setHost(LOCALHOST);
    connector.setPort(Constants.LOCAL_WEB_SERVER_PORT);

    server = new Server();

    /** If we're running with jconsole support, start the MBean server */
    if (System.getProperty("com.sun.management.jmxremote") != null) {
      connector.setStatsOn(true);

      logger.info("Starting managemenat bean");
      // MBeanServer mBeanServer =
      // ManagementFactory.getPlatformMBeanServer();
      // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
      // server.getContainer().addEventListener(mBeanContainer);
      // mBeanContainer.start();
    }

    checkAutoStartRegistry();
    server.addConnector(connector);

    // sets the thread pool (just so it is deamon=true)
    BoundedThreadPool threadPool = new BoundedThreadPool();
    threadPool.setMinThreads(5);
    // threadPool.setMaxThreads(10);
    threadPool.setName("Jetty thread pool");
    threadPool.setDaemon(true);
    server.setThreadPool(threadPool);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);
    Context root = new Context(contexts, "/", Context.NO_SESSIONS);

    MultiHandler mh = new MultiHandler(coreInterface, false);

    if (System.getProperty("com.sun.management.jmxremote") != null) {
      RequestLogHandler requestLogHandler = new RequestLogHandler();

      NCSARequestLog requestLog = new NCSARequestLog("/tmp/jetty-yyyy_mm_dd.request.log");
      requestLog.setRetainDays(1);
      requestLog.setAppend(false);
      requestLog.setExtended(true);
      requestLog.setLogTimeZone("GMT");
      requestLogHandler.setRequestLog(requestLog);

      HandlerCollection handlers = new HandlerCollection();
      handlers.setHandlers(new Handler[] {mh, requestLogHandler});
      root.setHandler(handlers);
    } else {
      root.setHandler(mh);
    }

    // make sure that the class loader can find all classes in the osgwtui
    // plugin dir...
    root.setClassLoader(pluginInterface.getPluginClassLoader());

    root.setVirtualHosts(new String[] {LOCALHOST});

    try {
      server.start();
      if (isRemoteAccessAllowed()) {
        enableRemoteAccess();
      }
      installRemoteAccessPropertyListener();
      // Thread.sleep(10000);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    CommunityServerManager.get();

    // check to see if we can parse a planetlab-style experiment config file
    try {
      Class expConfigManagerClass =
          Class.forName("edu.washington.cs.oneswarm.planetlab.ExperimentConfigManager");
      if (expConfigManagerClass != null) {

        Method getMethod = expConfigManagerClass.getMethod("get");
        Object configManager = getMethod.invoke(null, new Object[] {});
        if (configManager != null) {
          logger.info("Got experimental manager");
          Method setCore =
              expConfigManagerClass.getMethod("setCore", new Class[] {CoreInterface.class});
          setCore.invoke(configManager, coreInterface);
          logger.info("Set core");
          Method startHeartbeats = expConfigManagerClass.getMethod("startHeartbeats");
          startHeartbeats.invoke(configManager);
          logger.info("startHeartbeats");
        } else {
          logger.info("configManager is null -- classes found but experimental mode not enabled");
        }
      }

    } catch (ClassNotFoundException e) {
      logger.info("PlanetLab classes not found -- not running in experimental mode.");
    } catch (Exception e) {
      System.err.println(e);
      logger.info("PlanetLab classes failed to load -- not running in experimental mode.");
    }

    // make sure community server refreshes whether we load the web UI or
    // not.
    CommunityServerManager.get();

    /*
     * add the listener to the sha1 hasher manager
     */
    Sha1HashManager.getInstance()
        .addJobListener(
            new Sha1HashJobListener() {
              public Sha1CalcListener jobAdded(String name) {
                final int taskID =
                    BackendTaskManager.get()
                        .createTask(
                            "Hashing: " + name,
                            new CancellationListener() {
                              public void cancelled(int inID) {
                                Sha1HashManager.getInstance().stop();
                              }
                            });
                final BackendTask task = BackendTaskManager.get().getTask(taskID);
                task.setSummary("Calculating SHA1 and ED2K hashes of " + name);
                return new Sha1CalcListener() {
                  public void progress(double fraction) {
                    int percent = (int) Math.round(100 * fraction);
                    task.setProgress(percent + "%");
                  }

                  public void errorOccured(Throwable cause) {
                    BackendTaskManager.get().removeTask(taskID);
                  }

                  public void completed(Sha1Result result) {
                    BackendTaskManager.get().removeTask(taskID);
                  }
                };
              }
            });

    /** Start health checking */
    HealthChecker health = new HealthChecker();
    health.start();
  }