@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);
  }
Exemplo n.º 2
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.º 3
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, "/");
  }
  /**
   * 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);
    }
  }