Exemplo n.º 1
0
  public static void main(String[] args) throws Exception {
    Server server = new Server();

    SelectChannelConnector connector0 = new SelectChannelConnector();
    connector0.setPort(8080);
    connector0.setMaxIdleTime(30000);
    connector0.setRequestHeaderSize(8192);

    SelectChannelConnector connector1 = new SelectChannelConnector();
    connector1.setHost("127.0.0.1");
    connector1.setPort(8888);
    connector1.setThreadPool(new QueuedThreadPool(20));
    connector1.setName("admin");

    SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
    String jetty_home =
        System.getProperty("jetty.home", "../jetty-distribution/target/distribution");
    System.setProperty("jetty.home", jetty_home);
    ssl_connector.setPort(8443);
    SslContextFactory cf = ssl_connector.getSslContextFactory();
    cf.setKeyStorePath(jetty_home + "/etc/keystore");
    cf.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    cf.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");

    server.setConnectors(new Connector[] {connector0, connector1, ssl_connector});

    server.setHandler(new HelloHandler());

    server.start();
    server.join();
  }
  /**
   * set up the ssl connectors with strong ciphers
   *
   * @throws Exception
   */
  protected void initConnectors() throws Exception {
    if (!_disableHTTP) {
      if (_unsecuredConnector == null) {
        _unsecuredConnector = new SelectChannelConnector();
      }
      if (_unsecurePort != null) {
        _unsecuredConnector.setPort(Integer.parseInt(_unsecurePort));
      } else {
        _unsecuredConnector.setPort(_serviceInfo.getEndpoint().getPort());
      }
      if (_httpBindAddress != null) {
        _unsecuredConnector.setHost(_httpBindAddress);
      }
      if (lowResourcesConnections != null) {
        _unsecuredConnector.setLowResourcesConnections(lowResourcesConnections);
      }
      if (lowResourcesMaxIdleTime != null) {
        _unsecuredConnector.setLowResourcesMaxIdleTime(lowResourcesMaxIdleTime);
      }
      if (threadPool != null) {
        _unsecuredConnector.setThreadPool(threadPool);
      }
      _server.addConnector(_unsecuredConnector);
    }
    if (!_disableSSL) {
      SslContextFactory sslFac = new SslContextFactory();
      sslFac.setIncludeCipherSuites(_ciphers);

      KeyStore ks = KeyStoreUtil.getViPRKeystore(_coordinatorClient);
      _log.debug(
          "The certificates in Jetty is {}. ",
          ks.getCertificateChain(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS));

      sslFac.setCertAlias(KeystoreEngine.ViPR_KEY_AND_CERTIFICATE_ALIAS);
      sslFac.setKeyStore(ks);
      _securedConnector = new SslSelectChannelConnector(sslFac);
      if (_securePort != null) {
        _securedConnector.setPort(Integer.parseInt(_securePort));
      } else {
        _securedConnector.setPort(_serviceInfo.getEndpoint().getPort());
      }
      if (_bindAddress != null) {
        _securedConnector.setHost(_bindAddress);
      }
      if (lowResourcesConnections != null) {
        _securedConnector.setLowResourcesConnections(lowResourcesConnections);
      }
      if (lowResourcesMaxIdleTime != null) {
        _securedConnector.setLowResourcesMaxIdleTime(lowResourcesMaxIdleTime);
      }
      if (threadPool != null) {
        _securedConnector.setThreadPool(threadPool);
      }
      _server.addConnector(_securedConnector);
    }
    _server.setSendServerVersion(false);
  }
Exemplo n.º 3
0
  public SimpleHttpHandler() {
    this.server = new Server();
    SelectChannelConnector connector0 = new SelectChannelConnector();
    connector0.setPort(8888);
    connector0.setMaxIdleTime(30000);
    connector0.setRequestHeaderSize(8192);

    SelectChannelConnector connector1 = new SelectChannelConnector();
    connector1.setHost("127.0.0.1");
    connector1.setPort(8843);
    connector1.setThreadPool(new QueuedThreadPool(20));
    connector1.setName("admin");
    server.setConnectors(new Connector[] {connector0, connector1});

    server.setHandler(this);
  }
Exemplo n.º 4
0
  void runJettyBenchmark(int port, int iterations, int clientCount, int delay, int responseSize)
      throws Exception {
    System.gc();
    Server s = new Server();
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    s.addConnector(connector);

    s.setHandler(new JettyHandler(delay, responseSize));
    s.start();

    HTTPClient[] clients = new HTTPClient[clientCount];
    for (int i = 0; i < clientCount; i++) {
      clients[i] = new HTTPClient(iterations, port);
    }

    long start = System.nanoTime();
    for (int i = 0; i < clientCount; i++) {
      clients[i].start();
    }
    for (int i = 0; i < clientCount; i++) {
      clients[i].join();
    }
    long finish = System.nanoTime();

    double seconds = (finish - start) / (1000d * 1000d * 1000d);
    double rate = (iterations * clientCount) / seconds;
    System.out.printf("Simple bench did %.2f iterations / sec.\n", rate);

    s.stop();
    s.join();
    s = null;
  }
Exemplo n.º 5
0
  public void start(Injector injector) throws Exception {
    ResourceHandler resHandler = new ResourceHandler();
    resHandler.setDirectoriesListed(false);
    resHandler.setWelcomeFiles(new String[] {"index.html"});
    resHandler.setResourceBase(args.get("jetty.resourcebase", "./src/main/webapp"));

    server = new Server();
    // getSessionHandler and getSecurityHandler should always return null
    ServletContextHandler servHandler =
        new ServletContextHandler(
            ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
    servHandler.setContextPath("/");

    servHandler.addServlet(new ServletHolder(new InvalidRequestServlet()), "/*");

    FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
    servHandler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

    SelectChannelConnector connector0 = new SelectChannelConnector();
    int httpPort = args.getInt("jetty.port", 8989);
    String host = args.get("jetty.host", "");
    connector0.setPort(httpPort);
    if (!host.isEmpty()) connector0.setHost(host);

    server.addConnector(connector0);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resHandler, servHandler});
    server.setHandler(handlers);
    server.start();
    logger.info("Started server at HTTP " + host + ":" + httpPort);
  }
  public EmbeddedJettyServer(int port, boolean useRestSession) throws Exception {
    server = new Server();
    connector = new SelectChannelConnector();
    connector.setPort(port);
    server.addConnector(connector);

    root = new WebAppContext();
    root.setContextPath("/");
    root.setResourceBase(".");
    if (useRestSession) {
      RestSessionIdManager idManager = new RestSessionIdManager();
      RestSessionManager sessionManager = new RestSessionManager();
      server.setSessionIdManager(idManager);
      sessionManager.setSessionIdManager(idManager);
      SessionHandler sessionHandler = new SessionHandler();
      sessionHandler.setSessionManager(sessionManager);
      root.setSessionHandler(sessionHandler);
      root.setClassLoader(getContextClassLoader());
    }

    server.setHandler(root);
    server.start();
    while (!server.isStarted()) {
      Thread.sleep(100);
    }
  }
Exemplo n.º 7
0
  private void doStart() {
    if (!available(port)) throw new IllegalStateException("port: " + port + " already in use!");

    deleteSessionData();

    System.out.println("Starting JFinal " + Const.JFINAL_VERSION);
    server = new Server();
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    server.addConnector(connector);
    webApp = new WebAppContext();
    webApp.setThrowUnavailableOnStartupException(true); // 在启动过程中允许抛出异常终止启动并退出 JVM
    webApp.setContextPath(context);
    webApp.setResourceBase(webAppDir); // webApp.setWar(webAppDir);
    webApp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    webApp.setInitParameter(
        "org.eclipse.jetty.servlet.Default.useFileMappedBuffer",
        "false"); // webApp.setInitParams(Collections.singletonMap("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"));
    persistSession(webApp);

    server.setHandler(webApp);
    changeClassLoader(webApp);

    // configureScanner
    if (scanIntervalSeconds > 0) {
      Scanner scanner =
          new Scanner(PathKit.getRootClassPath(), scanIntervalSeconds) {
            public void onChange() {
              try {
                System.err.println("\nLoading changes ......");
                webApp.stop();
                JFinalClassLoader loader = new JFinalClassLoader(webApp, getClassPath());
                webApp.setClassLoader(loader);
                webApp.start();
                System.err.println("Loading complete.");
              } catch (Exception e) {
                System.err.println(
                    "Error reconfiguring/restarting webapp after change in watched files");
                LogKit.error(e.getMessage(), e);
              }
            }
          };
      System.out.println("Starting scanner at interval of " + scanIntervalSeconds + " seconds.");
      scanner.start();
    }

    try {
      System.out.println("Starting web server on port: " + port);
      server.start();
      System.out.println("Starting Complete. Welcome To The JFinal World :)");
      server.join();
    } catch (Exception e) {
      LogKit.error(e.getMessage(), e);
      System.exit(100);
    }
    return;
  }
Exemplo n.º 8
0
  public void start() throws Exception {
    server = new Server();

    WebAppContext wac = new WebAppContext();
    wac.setContextPath(contextPath);
    wac.setWar(warPath);
    server.setHandler(wac);

    SelectChannelConnector scc = new SelectChannelConnector();
    scc.setPort(port);
    server.addConnector(scc);
    server.start();
  }
Exemplo n.º 9
0
  public static void main(String[] args) {
    Server server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(8080);
    server.addConnector(connector);

    WebAppContext web = new WebAppContext(server, "struts2.example", "/example");
    web.setWar("libraries/struts2/example/src/main/webapp/");

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
Exemplo n.º 10
0
  /** 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录. */
  public static Server createServerInSource(int port, String contextPath) {
    Server server = new Server();
    // 设置在JVM退出时关闭Jetty的钩子。
    server.setStopAtShutdown(true);

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    // 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
    connector.setReuseAddress(false);
    server.setConnectors(new Connector[] {connector});

    WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, contextPath);
    // 修改webdefault.xml,解决Windows下Jetty Lock住静态文件的问题.
    webContext.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH);
    server.setHandler(webContext);

    return server;
  }
  @Before
  public void startHttp() throws Exception {
    server = new Server();
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(8778);
    server.addConnector(connector);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(false);
    resource_handler.setWelcomeFiles(new String[] {});

    resource_handler.setResourceBase("target/test-classes/repo2");

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

    server.start();
  }
Exemplo n.º 12
0
  @BeforeClass
  public static void startServer() throws Exception {
    server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(PORT);
    server.setConnectors(new Connector[] {connector});

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/");

    String warPath = null;
    warPath = JAXRPCTest.class.getResource("/webapp").toURI().getPath();

    webappcontext.setWar(warPath);

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});

    server.setHandler(handlers);
    server.start();
  }
Exemplo n.º 13
0
  public static void main(String[] args) throws Exception {

    // load main configuration
    String configLoc = System.getProperty(CONFIG_LOCATION_SYS_VAR, CONFIG_LOCATION_DEFAULT);
    System.setProperty(CONFIG_LOCATION_SYS_VAR, configLoc);
    Properties configProps = new Properties();
    try {
      configProps.load(new FileInputStream(ResourceUtils.getFile(configLoc)));
      logger.info("Successfully loaded main configuration.");
    } catch (Exception ex) {
      logger.error("Fail to start in early part", ex);
      throw ex;
    }
    Config config = new Config(configProps);

    // load log4j configuration
    // @todo review the effect and final configuration when -Dlog4j.properties is specified with
    // command line
    String log4jConfigLoc = config.getValue(ItemMeta.BOOTSTRAP_LOG4J_CONFIG_LOCATION);
    if (log4jConfigLoc != null) {
      Properties log4jConfig = new Properties();

      try {
        log4jConfig.load(new FileInputStream(ResourceUtils.getFile(log4jConfigLoc)));
        org.apache.log4j.LogManager.resetConfiguration();
        org.apache.log4j.PropertyConfigurator.configure(log4jConfig);
        logger.info("Successfully loaded log4j configuration at {}", log4jConfigLoc);
      } catch (Exception ex) {
        logger.error("Faile to load specified log4j configuration", ex);
        throw ex;
      }
    }

    ServletContextHandler sch =
        new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS);

    sch.setContextPath(config.getValue(ItemMeta.ROOT_SERVLET_CONTEXT_PATH));
    sch.getSessionHandler()
        .getSessionManager()
        .setSessionCookie(config.getValue(ItemMeta.ROOT_SERVLET_SESSION_ID));

    ServletHolder dsh = sch.addServlet(DefaultServlet.class, "/");
    dsh.setInitOrder(1);

    ServletHolder jsh = new ServletHolder(JerseySpringServlet.class);
    jsh.setInitParameter(
        JerseySpringServlet.INIT_PARM_SPRING_CONFIG_LOCATION,
        config.getValue(ItemMeta.BOOTSTRAP_SPRING_CONFIG_LOCATION));
    // Refer https://jersey.java.net/apidocs/1.18/jersey/index.html?constant-values.html
    jsh.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true");
    jsh.setInitParameter(
        ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS,
        "com.sun.jersey.api.container.filter.LoggingFilter");
    jsh.setInitParameter(
        ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS,
        "com.sun.jersey.api.container.filter.LoggingFilter");
    jsh.setInitParameter(ResourceConfig.FEATURE_TRACE, "true");
    // jsh.setInitParameter(JSONMarshaller.FORMATTED, "true");
    // jsh.setInitParameter(FeaturesAndProperties.FEATURE_FORMATTED, "true");
    // jsh.setInitParameter(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true");

    sch.addServlet(jsh, config.getValue(ItemMeta.JERSEY_SERVLET_URL_PATTEN));
    jsh.setInitOrder(config.getIntValue(ItemMeta.JERSEY_SERVLET_INIT_ORDER));

    // For more, refer
    // http://download.eclipse.org/jetty/stable-7/apidocs/index.html?org/eclipse/jetty/servlets/CrossOriginFilter.html
    FilterHolder fh = new FilterHolder(CrossOriginFilter.class);
    fh.setName("crossOriginFilter");
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_ORIGINS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_ORIGINS));
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_METHODS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_METHODS));
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_HEADERS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_HEADERS));
    sch.addFilter(fh, "/*", FilterMapping.DEFAULT);

    Server jetty = new Server();
    HandlerList hl = new HandlerList();
    hl.addHandler(sch);
    jetty.setHandler(hl);
    jetty.setThreadPool(
        new QueuedThreadPool(config.getIntValue(ItemMeta.WEB_SERVER_THREAD_POOL_SIZE)));

    SelectChannelConnector conn = new SelectChannelConnector();
    conn.setPort(config.getIntValue(ItemMeta.WEB_SERVER_PORT));
    conn.setMaxIdleTime(config.getIntValue(ItemMeta.WEB_SERVER_MAX_IDLE_TIME));

    MBeanContainer mbc = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    mbc.setDomain(config.getValue(ItemMeta.JMX_DOMAIN) + ".jetty");
    jetty.getContainer().addEventListener(mbc);
    jetty.addBean(mbc);

    jetty.addConnector(conn);
    jetty.setStopAtShutdown(true);

    try {
      jetty.start();
      logger.info("Jetty started at port {} on {}", conn.getPort(), "127.0.0.1");
    } catch (Exception ex) {
      logger.error("Fail to start Jetty.", ex);
      System.exit(-1);
    }
  }
Exemplo n.º 14
0
  public void start(final int port, IRascalMonitor monitor) throws Exception {
    monitor.startJob("Loading Course Manager");
    eval.eval(monitor, "import " + "CourseManager" + ";", URIUtil.rootScheme("stdin"));
    monitor.endJob(true);

    Log.setLog(
        new Logger() {

          @Override
          public String getName() {
            return "no logger";
          }

          @Override
          public void warn(String msg, Object... args) {}

          @Override
          public void warn(Throwable thrown) {}

          @Override
          public void warn(String msg, Throwable thrown) {}

          @Override
          public void info(String msg, Object... args) {}

          @Override
          public void info(Throwable thrown) {}

          @Override
          public void info(String msg, Throwable thrown) {}

          @Override
          public boolean isDebugEnabled() {
            return false;
          }

          @Override
          public void setDebugEnabled(boolean enabled) {}

          @Override
          public void debug(String msg, Object... args) {}

          @Override
          public void debug(Throwable thrown) {}

          @Override
          public void debug(String msg, Throwable thrown) {}

          @Override
          public Logger getLogger(String name) {
            return this;
          }

          @Override
          public void ignore(Throwable ignored) {}
        });

    monitor.startJob("Starting Webserver");
    server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    connector.setMaxIdleTime(30000);
    connector.setResponseHeaderSize(1000 * 1000);
    connector.setRequestBufferSize(1000 * 1000);
    connector.setConfidentialPort(8443);

    server.setConnectors(new Connector[] {connector});
    server.setHandler(getTutorHandler());
    server.start();
    monitor.endJob(true);
  }
Exemplo n.º 15
0
  /**
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {

    CommandLineParser parser = new PosixParser();
    String warcDir = null;
    String workDir = null;
    String host = "localhost";

    Options options = new Options();
    options.addOption("h", "help", false, "Show this help message.");
    options.addOption(
        "i",
        "index-folder",
        true,
        "Specify a custom directory for caching the web archiving index files. Indexes are usually re-built every time you start WaybackPlayer, which might be cumbersome for large indexes. Use this option to specify a folder in which to cache the indexes.");
    options.addOption(
        "s", "server-name", true, "Specify a server name to use, defaults to 'localhost'");
    try {
      CommandLine line = parser.parse(options, args);
      String cli_args[] = line.getArgs();

      // Check there is an argument for the warcs folder:
      if (!(cli_args.length > 0)) {
        printUsage(options);
        return;
      }
      warcDir = cli_args[0];

      // Show help if required:
      if (line.hasOption("h")) {
        printUsage(options);
        return;
      }

      // Allow index folder to be overridden (and thus cached):
      if (line.hasOption("i")) {
        workDir = line.getOptionValue("i");
      }

      // Allow the host to be overridden:
      if (line.hasOption("s")) {
        host = line.getOptionValue("s");
      }

    } catch (ParseException e1) {
      e1.printStackTrace();
      return;
    }

    // Avoid requiring the JDK for Jetty JSP compilation.
    // See http://www.eclipse.org/jetty/documentation/current/configuring-jsp.html
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "true");

    // An embedded server:
    Server server = new Server();

    // Default connector for playback:
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(18080);
    connector.setHost(host);

    // Connector for Proxy mode:
    SelectChannelConnector connector2 = new SelectChannelConnector();
    connector2.setPort(18090);
    connector2.setHost(host);

    // Attach the two connectors:
    server.setConnectors(new Connector[] {connector, connector2});

    // Set a property so Wayback Spring can find the WARCs etc.
    System.setProperty("wayback.warc.dir", warcDir);

    // Set a propery so the host and ports are known:
    System.setProperty("wayback.host", host);
    System.setProperty("wayback.port", "" + 18080);
    System.setProperty("wayback.proxy.port", "" + 18090);

    // TODO Option to wipe it if it's there and looks like ours?
    File waywork = null;
    if (workDir == null) {
      waywork = File.createTempFile("wayback-play", "");
      waywork.delete();
      waywork.mkdir();
      System.setProperty("wayback.work.dir", waywork.getAbsolutePath());
      waywork.deleteOnExit();
    } else {
      waywork = new File(workDir);
      System.setProperty("wayback.work.dir", workDir);
    }
    System.err.println("Indexes held in: " + System.getProperty("wayback.work.dir"));

    // Prior to start up, generate CDX files and path-index.txt file and put them in
    // wayback.work.dir:
    File wdf = new File(warcDir);
    List<String> paths = new ArrayList<String>();
    for (File wf : wdf.listFiles()) {
      paths.add(wf.getName() + "\t" + wf.getAbsolutePath());
      System.out.println("LINE: " + wf.getAbsolutePath());
      // CDX generation:
      File cdxFile = new File(waywork, wf.getName() + ".cdx");
      if (!cdxFile.exists()) {
        System.out.println("Generating " + cdxFile.getPath() + " from " + wf.getPath() + "...");
        IndexWorker.main(new String[] {wf.getAbsolutePath(), cdxFile.getAbsolutePath()});
      } else {
        System.out.println(
            "The CDX " + cdxFile.getPath() + " for " + wf.getPath() + " already exists.");
      }
    }

    // For path-index.txt:
    Collections.sort(paths);
    PrintWriter writer = new PrintWriter(new File(waywork, "path-index.txt"), "UTF-8");
    for (String path : paths) {
      writer.println(path);
    }
    writer.close();

    // Set up the Wayback web app:
    WebAppContext wac = new WebAppContext();
    wac.setContextPath("/");
    // this is path to .war OR TO expanded, existing webapp; WILL FIND web.xml and parse it
    // wac.setWar("/Users/andy/Documents/workspace/waybacks/wayback-play/target/wayback-play");
    URL resourceUrl =
        ClassLoader.getSystemClassLoader().getResource("lib/warc-explorer-player.war");
    // Copy to tmp space:
    File tmpWar = File.createTempFile("wayback-player", ".war");
    tmpWar.deleteOnExit();
    IOUtils.copy(resourceUrl.openStream(), new FileOutputStream(tmpWar));
    // Fire it up:
    wac.setWar(tmpWar.getAbsolutePath());
    server.setHandler(wac);
    server.setStopAtShutdown(true);

    // Launch the server:
    try {
      server.start();
      server.join();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      //
      connector.close();
      try {
        server.stop();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      if (waywork != null) {
        if (waywork.exists()) {
          waywork.delete();
        }
      }
    }

    System.err.println("Bye.");
  }
Exemplo n.º 16
0
  @Test
  public void checkBasicAuthAccess() throws Throwable {
    final Server server = new Server();
    final SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(/* any */ 0);
    connector.setReuseAddress(false);
    connector.setSoLingerTime(0);
    server.addConnector(connector);

    HashLoginService loginService = new HashLoginService();
    loginService.putUser("username", new Password("userpass"), new String[] {"role1", "role2"});

    final CountDownLatch latch = new CountDownLatch(1);

    WebAppContext wac = new WebAppContext();
    wac.getSecurityHandler().setLoginService(loginService);
    wac.setContextPath("/");

    connector.addLifeCycleListener(
        new ListenerAdapter() {
          public void lifeCycleStarted(LifeCycle lc) {
            System.out.println("Started on port: " + connector.getLocalPort());
            latch.countDown();
          }

          public void lifeCycleFailure(LifeCycle lc, Throwable t) {
            System.out.println("Failure: " + t);
            latch.countDown();
          }
        });
    wac.setParentLoaderPriority(true);

    URL resource = getClass().getResource("/auth/basic/kaczynski.xml");
    assertThat(resource.toURI().getScheme()).isEqualTo("file");
    File webapp = new File(resource.toURI());
    webapp = webapp.getParentFile(); // /auth/basic
    webapp = webapp.getParentFile(); // /auth
    wac.setWar(webapp.getAbsolutePath());
    wac.setClassLoader(Thread.currentThread().getContextClassLoader());

    server.setHandler(wac);
    server.setStopAtShutdown(true);
    try {
      server.start();
      latch.await();

      System.setProperty(HttpAuthHub.USERNAME_PROPERTY, "username");
      System.setProperty(HttpAuthHub.PASSWORD_PROPERTY, "userpass");
      Controller c = ControllerFactory.createSimple();
      try {
        Map<String, Object> attrs = new HashMap<String, Object>();
        XmlDocumentSourceDescriptor.attributeBuilder(attrs)
            .xml(
                new URLResourceWithParams(
                    new URL(
                        "http://localhost:" + connector.getLocalPort() + "/basic/kaczynski.xml")));
        ProcessingResult r = c.process(attrs, XmlDocumentSource.class);

        assertThat(r.getDocuments()).hasSize(50);
      } finally {
        c.dispose();
      }
    } finally {
      server.stop();
    }
  }