Example #1
0
  public static void main(String[] args) throws Exception {
    Server server = new Server();

    SslContextFactory factory = new SslContextFactory();
    factory.setKeyStorePath("src/test/keystore.jks");
    factory.setKeyStorePassword("storepass");
    factory.setKeyManagerPassword("keypass");
    SslSocketConnector connector = new SslSocketConnector(factory);
    connector.setPort(8443);
    server.addConnector(connector);
    InheritedChannelConnector inheritedChannelConnector = new InheritedChannelConnector();
    inheritedChannelConnector.setPort(8080);
    server.addConnector(inheritedChannelConnector);

    WebAppContext context = new WebAppContext();
    context.setConfigurationClasses(
        new String[] {WebInfConfiguration.class.getName(), WebXmlConfiguration.class.getName()});
    context.setResourceBase("src/main/webapp");
    context.setContextPath(CONTEXT_PATH);
    context.setParentLoaderPriority(true);
    server.setHandler(context);

    try {
      server.start();
      if (!context.isAvailable()) throw new IllegalStateException("context deployed failed");
      server.join();
    } catch (Exception e) {
      server.stop();
      throw new IllegalStateException("jetty failed to start: " + e.getMessage(), e);
    }
  }
Example #2
0
  /**
   * This implementation is based on http://blog.denevell.org/jetty-9-ssl-https.html
   *
   * @throws Exception
   */
  private void startHttps() throws Exception {
    _server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory(H2O.ARGS.jks);
    sslContextFactory.setKeyStorePassword(H2O.ARGS.jks_pass);

    SslSocketConnector httpsConnector = new SslSocketConnector(sslContextFactory);

    if (getIp() != null) {
      httpsConnector.setHost(getIp());
    }
    httpsConnector.setPort(getPort());

    createServer(httpsConnector);
  }
  @BeforeClass(alwaysRun = true)
  public void setUpGlobal() throws Exception {
    server = new Server();
    server2 = new Server();

    port1 = findFreePort();
    port2 = findFreePort();

    Connector listener = new SelectChannelConnector();

    listener.setHost("127.0.0.1");
    listener.setPort(port1);

    server.addConnector(listener);

    SslSocketConnector connector = new SslSocketConnector();
    connector.setHost("127.0.0.1");
    connector.setPort(port2);

    ClassLoader cl = getClass().getClassLoader();
    URL keystoreUrl = cl.getResource("ssltest-keystore.jks");
    String keyStoreFile = new File(keystoreUrl.toURI()).getAbsolutePath();
    connector.setKeystore(keyStoreFile);
    connector.setKeyPassword("changeit");
    connector.setKeystoreType("JKS");

    server2.addConnector(connector);

    server.setHandler(configureHandler());
    server.start();

    server2.setHandler(new EchoHandler());
    server2.start();
    log.info("Local HTTP server started successfully");
  }
Example #4
0
  public static void main(String[] args) throws Exception {
    int timeout = (int) Duration.ONE_HOUR.getMilliseconds();

    Server server = new Server();
    SocketConnector connector = new SocketConnector();

    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(timeout);
    connector.setSoLingerTime(-1);
    connector.setPort(8080);
    server.addConnector(connector);

    Resource keystore = Resource.newClassPathResource("/keystore");
    if (keystore != null && keystore.exists()) {
      // if a keystore for a SSL certificate is available, start a SSL
      // connector on port 8443.
      // By default, the quickstart comes with a Apache Wicket Quickstart
      // Certificate that expires about half way september 2021. Do not
      // use this certificate anywhere important as the passwords are
      // available in the source.

      connector.setConfidentialPort(8443);

      SslContextFactory factory = new SslContextFactory();
      factory.setKeyStoreResource(keystore);
      factory.setKeyStorePassword("wicket");
      factory.setTrustStoreResource(keystore);
      factory.setKeyManagerPassword("wicket");
      SslSocketConnector sslConnector = new SslSocketConnector(factory);
      sslConnector.setMaxIdleTime(timeout);
      sslConnector.setPort(8443);
      sslConnector.setAcceptors(4);
      server.addConnector(sslConnector);

      System.out.println("SSL access to the quickstart has been enabled on port 8443");
      System.out.println("You can access the application using SSL on https://localhost:8443");
      System.out.println();
    }

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");
    bb.setWar("src/main/webapp");

    // START JMX SERVER
    // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    // server.getContainer().addEventListener(mBeanContainer);
    // mBeanContainer.start();

    server.setHandler(bb);

    try {
      System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
      server.start();
      System.in.read();
      System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
      server.stop();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Example #5
0
  public static void main(final String[] args) throws Exception {
    final int timeout = (int) Duration.ONE_HOUR.getMilliseconds();

    int port = 8080;
    final CommandLineParser parser = new BasicParser();
    final Options options = new Options();
    options.addOption("h", "help", false, "Prints usage information");
    options.addOption("p", "port", true, "Server port");
    options.addOption("v", "version", false, "Version");
    options.addOption("f", "file", true, "kMyMoney file path");
    // Parse the program arguments
    final CommandLine commandLine = parser.parse(options, args);
    boolean isBadArgs = false;
    String file = null;

    if (commandLine.hasOption('h')) {
      isBadArgs = true;
    }
    if (commandLine.hasOption('v')) {
      System.out.println("kMyMoneyScripter version 0.01");
      System.exit(0);
    }
    if (!commandLine.hasOption('f')) {
      isBadArgs = true;
    }
    if (commandLine.hasOption('p')) {
      try {
        System.out.println(commandLine.getOptionValue('p'));
        port = Integer.parseInt(commandLine.getOptionValue('p'));
      } catch (final Exception e) {
        isBadArgs = true;
        System.err.println("Not a proper port number:" + commandLine.getOptionValue('p'));
      }
    }
    if (commandLine.hasOption('f')) {
      file = commandLine.getOptionValue('f');
      if (file == null) {
        isBadArgs = true;
      } else {
        final File f = new File(file);
        if (f.exists() == false) {
          System.err.println("File " + file + " does not exist.");
          isBadArgs = true;
        }
      }
    }

    if (isBadArgs) {
      final HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("kMymoneyScripter", options);
      System.exit(1);
    }
    final Server server = new Server();
    final SocketConnector connector = new SocketConnector();

    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(timeout);
    connector.setSoLingerTime(-1);
    connector.setPort(port);
    server.addConnector(connector);

    // check if a keystore for a SSL certificate is available, and
    // if so, start a SSL connector on port 8443. By default, the
    // quickstart comes with a Apache Wicket Quickstart Certificate
    // that expires about half way september 2021. Do not use this
    // certificate anywhere important as the passwords are available
    // in the source.

    final Resource keystore = Resource.newClassPathResource("/keystore");
    if (keystore != null && keystore.exists()) {
      connector.setConfidentialPort(8443);

      final SslContextFactory factory = new SslContextFactory();
      factory.setKeyStoreResource(keystore);
      factory.setKeyStorePassword("wicket");
      factory.setTrustStore(keystore);
      factory.setKeyManagerPassword("wicket");
      final SslSocketConnector sslConnector = new SslSocketConnector(factory);
      sslConnector.setMaxIdleTime(timeout);
      sslConnector.setPort(8443);
      sslConnector.setAcceptors(4);
      server.addConnector(sslConnector);

      System.out.println("SSL access to the quickstart has been enabled on port 8443");
      System.out.println("You can access the application using SSL on https://localhost:8443");
      System.out.println();
    }

    final WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");

    new WicketFilter();
    final FilterHolder filterHolder = new FilterHolder(WicketFilter.class);
    filterHolder.setInitParameter(
        ContextParamWebApplicationFactory.APP_CLASS_PARAM, WICKET_WEBAPP_CLASS_NAME);
    filterHolder.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, "/*");
    // filterHolder.setInitParameter(param, value)
    bb.addFilter(filterHolder, "/*", 1);

    bb.setWar(Start.class.getClassLoader().getResource("webapp").toExternalForm());
    // START JMX SERVER
    // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    // server.getContainer().addEventListener(mBeanContainer);
    // mBeanContainer.start();

    server.setHandler(bb);
    createDB(file);

    try {
      System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
      server.start();
      System.in.read();
      System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
      server.stop();
      server.join();
      WicketApplication.db.close();
    } catch (final Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Example #6
0
  public Server getJettyServer(int port, int sslPort, int maxThreads) throws IOException {

    Server server = new Server();
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setThreadPool(new QueuedThreadPool(maxThreads));

    SslSocketConnector sslSocketConnector = null;
    if (sslPort > 0) {
      System.out.println("SSL is Starting on port " + sslPort + "...");
      sslSocketConnector = new SslSocketConnector();
      sslSocketConnector.setPort(getContainerConfig().getSSLPort());
      sslSocketConnector.setKeystore("conf/servertestkeystore");
      sslSocketConnector.setPassword(getContainerConfig().getSSLKeyPassword());
      sslSocketConnector.setKeyPassword(getContainerConfig().getSSLKeyStorePassword());
      sslSocketConnector.setTruststore("conf/servertestkeystore");
      sslSocketConnector.setTrustPassword(getContainerConfig().getSSLKeyStorePassword());
    } else if (getContainerConfig().isAcEnabled())
      logger.error("SSL MUST be configured in the gsn.xml file when Access Control is enabled !");

    AbstractConnector connector =
        new SelectChannelConnector(); // before was connector//new SocketConnector ();//using basic
                                      // connector for windows bug; Fast
                                      // option=>SelectChannelConnector
    connector.setPort(port);
    connector.setMaxIdleTime(30000);
    connector.setAcceptors(2);
    connector.setConfidentialPort(sslPort);

    if (sslSocketConnector == null) server.setConnectors(new Connector[] {connector});
    else server.setConnectors(new Connector[] {connector, sslSocketConnector});

    WebAppContext webAppContext = new WebAppContext(contexts, DEFAULT_WEB_APP_PATH, "/");

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

    Properties usernames = new Properties();
    usernames.load(new FileReader("conf/realm.properties"));
    if (!usernames.isEmpty()) {
      HashLoginService loginService = new HashLoginService();
      loginService.setName("GSNRealm");
      loginService.setConfig("conf/realm.properties");
      loginService.setRefreshInterval(10000); // re-reads the file every 10 seconds.

      Constraint constraint = new Constraint();
      constraint.setName("GSN User");
      constraint.setRoles(new String[] {"gsnuser"});
      constraint.setAuthenticate(true);

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

      ConstraintMapping cm2 = new ConstraintMapping();
      cm2.setConstraint(constraint);
      cm2.setPathSpec("/*");
      cm2.setMethod("POST");

      ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
      securityHandler.setLoginService(loginService);
      securityHandler.setConstraintMappings(new ConstraintMapping[] {cm, cm2});
      securityHandler.setAuthenticator(new BasicAuthenticator());
      webAppContext.setSecurityHandler(securityHandler);
    }

    server.setSendServerVersion(true);
    server.setStopAtShutdown(true);
    server.setSendServerVersion(false);
    server.setSessionIdManager(new HashSessionIdManager(new Random()));

    return server;
  }
Example #7
0
  protected void initializeServerWithConfig(final JUnitHttpServer config) {
    Server server = null;
    if (config.https()) {
      server = new Server();
      final SslContextFactory factory = new SslContextFactory(config.keystore());
      factory.setKeyStorePath(config.keystore());
      factory.setKeyStorePassword(config.keystorePassword());
      factory.setKeyManagerPassword(config.keyPassword());
      factory.setTrustStore(config.keystore());
      factory.setTrustStorePassword(config.keystorePassword());

      final SslSocketConnector connector = new SslSocketConnector(factory);
      connector.setPort(config.port());
      server.setConnectors(new Connector[] {connector});
    } else {
      server = new Server(config.port());
    }
    m_server = server;
    final ContextHandler context1 = new ContextHandler();
    context1.setContextPath("/");
    context1.setWelcomeFiles(new String[] {"index.html"});
    context1.setResourceBase(config.resource());
    context1.setClassLoader(Thread.currentThread().getContextClassLoader());
    context1.setVirtualHosts(config.vhosts());

    final ContextHandler context = context1;

    Handler topLevelHandler = null;
    final HandlerList handlers = new HandlerList();

    if (config.basicAuth()) {
      // check for basic auth if we're configured to do so
      LOG.debug("configuring basic auth");

      final HashLoginService loginService = new HashLoginService("MyRealm", config.basicAuthFile());
      loginService.setRefreshInterval(300000);
      m_server.addBean(loginService);

      final ConstraintSecurityHandler security = new ConstraintSecurityHandler();

      final Set<String> knownRoles = new HashSet<String>();
      knownRoles.add("user");
      knownRoles.add("admin");
      knownRoles.add("moderator");

      final Constraint constraint = new Constraint();
      constraint.setName("auth");
      constraint.setAuthenticate(true);
      constraint.setRoles(knownRoles.toArray(new String[0]));

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

      security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
      security.setAuthenticator(new BasicAuthenticator());
      security.setLoginService(loginService);
      security.setStrict(false);
      security.setRealmName("MyRealm");

      security.setHandler(context);
      topLevelHandler = security;
    } else {
      topLevelHandler = context;
    }

    final Webapp[] webapps = config.webapps();
    if (webapps != null) {
      for (final Webapp webapp : webapps) {
        final WebAppContext wac = new WebAppContext();
        String path = null;
        if (!"".equals(webapp.pathSystemProperty())
            && System.getProperty(webapp.pathSystemProperty()) != null) {
          path = System.getProperty(webapp.pathSystemProperty());
        } else {
          path = webapp.path();
        }
        if (path == null || "".equals(path)) {
          throw new IllegalArgumentException(
              "path or pathSystemProperty of @Webapp points to a null or blank value");
        }
        wac.setWar(path);
        wac.setContextPath(webapp.context());
        handlers.addHandler(wac);
      }
    }

    final ResourceHandler rh = new ResourceHandler();
    rh.setWelcomeFiles(new String[] {"index.html"});
    rh.setResourceBase(config.resource());
    handlers.addHandler(rh);

    // fall through to default
    handlers.addHandler(new DefaultHandler());

    context.setHandler(handlers);
    m_server.setHandler(topLevelHandler);
  }