public EmbeddedWebServer(String host, int port) {
    server = new Server();
    handler = new ContextHandlerCollection();
    root = new Context(handler, "/", new SessionHandler(), null, null, null);

    if (EMPTY.equals(Monitor.getSystemConfiguration().get(Property.MONITOR_SSL_KEYSTORE))
        || EMPTY.equals(Monitor.getSystemConfiguration().get(Property.MONITOR_SSL_KEYSTOREPASS))
        || EMPTY.equals(Monitor.getSystemConfiguration().get(Property.MONITOR_SSL_TRUSTSTORE))
        || EMPTY.equals(
            Monitor.getSystemConfiguration().get(Property.MONITOR_SSL_TRUSTSTOREPASS))) {
      sock = new SocketConnector();
      usingSsl = false;
    } else {
      sock = new SslSocketConnector();
      ((SslSocketConnector) sock)
          .setKeystore(Monitor.getSystemConfiguration().get(Property.MONITOR_SSL_KEYSTORE));
      ((SslSocketConnector) sock)
          .setKeyPassword(Monitor.getSystemConfiguration().get(Property.MONITOR_SSL_KEYSTOREPASS));
      ((SslSocketConnector) sock)
          .setTruststore(Monitor.getSystemConfiguration().get(Property.MONITOR_SSL_TRUSTSTORE));
      ((SslSocketConnector) sock)
          .setTrustPassword(
              Monitor.getSystemConfiguration().get(Property.MONITOR_SSL_TRUSTSTOREPASS));
      usingSsl = true;
    }
    sock.setHost(host);
    sock.setPort(port);
  }
 private static SslSocketConnector getSslConnector(int port) {
   SslSocketConnector sslConnector = new SslSocketConnector();
   sslConnector.setKeystore(resourceBase + "/keystore");
   sslConnector.setKeyPassword("pulkkisenjorma");
   sslConnector.setPort(port);
   sslConnector.setMaxIdleTime(30000);
   return sslConnector;
 }
  protected void configureConnectors() {
    if (server != null) {
      if (_useNIO) {
        SelectChannelConnector nioConnector = new SelectChannelConnector();
        nioConnector.setUseDirectBuffers(false);
        nioConnector.setPort(_port);
        server.addConnector(nioConnector);
      } else {
        SocketConnector bioConnector = new SocketConnector();
        bioConnector.setPort(_port);
        bioConnector.setMaxIdleTime(3000);
        server.addConnector(bioConnector);
      }

      if (_useSSL) {
        SslSocketConnector sslConnector = new SslSocketConnector();
        sslConnector.setPort(_sslPort);
        // sslConnector.setKeystore("/sdcard/jetty/etc/keystore");
        sslConnector.setKeystore(_keystoreFile);
        sslConnector.setKeystoreType("bks");
        // sslConnector.setTruststore("/sdcard/jetty/etc/keystore");
        sslConnector.setTruststore(_truststoreFile);
        // sslConnector.setPassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
        sslConnector.setPassword(_keystorePassword);
        // sslConnector.setKeyPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
        sslConnector.setKeyPassword(_keymgrPassword);
        // sslConnector.setTrustPassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
        sslConnector.setTrustPassword(_truststorePassword);
        sslConnector.setTruststoreType("bks");
        server.addConnector(sslConnector);
      }
    }
  }
Beispiel #4
0
  private static void initSSL(
      Server server,
      int sslport,
      String keystore,
      String password,
      String keyPassword,
      boolean needClientAuth) {

    if (keystore == null) {
      throw new IllegalStateException(
          "you need to provide argument -Drjrkeystore with -Drjrsslport");
    }
    if (password == null) {
      throw new IllegalStateException(
          "you need to provide argument -Drjrpassword with -Drjrsslport");
    }
    if (keyPassword == null) {
      throw new IllegalStateException(
          "you need to provide argument -Drjrkeypassword with -Drjrsslport");
    }

    SslSocketConnector sslConnector = new SslSocketConnector();
    sslConnector.setKeystore(keystore);
    sslConnector.setPassword(password);
    sslConnector.setKeyPassword(keyPassword);

    if (needClientAuth) {
      System.err.println("Enable NeedClientAuth.");
      sslConnector.setNeedClientAuth(needClientAuth);
    }
    sslConnector.setMaxIdleTime(30000);
    sslConnector.setPort(sslport);

    server.addConnector(sslConnector);
  }
  private static SslSocketConnector createSslConnector() {
    SslSocketConnector sslConnector = new SslSocketConnector();
    sslConnector.setPort(sslPort);
    sslConnector.setKeyPassword("secret");
    sslConnector.setKeystore("src/test/resources/keystore");
    sslConnector.setTrustPassword("secret");
    sslConnector.setTruststore("src/main/resources/truststore");
    sslConnector.setPassword("secret");
    sslConnector.setWantClientAuth(true);
    // sslConnector.setNeedClientAuth(true);

    return sslConnector;
  }
  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());
    }
  }
 @BeforeClass
 public static void startJetty() throws Exception {
   port = PortFactory.findFreePort();
   server = new Server();
   SslSocketConnector sslSocketConnector = new SslSocketConnector();
   sslSocketConnector.setKeystore("src/test/resources/keystore");
   sslSocketConnector.setKeyPassword("password");
   sslSocketConnector.setPort(port);
   server.setConnectors(new Connector[] {sslSocketConnector});
   server.addHandler(
       new AbstractHandler() {
         public void handle(
             String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
             throws IOException, ServletException {
           response.setStatus(Response.Status.OK.getStatusCode());
           Request base_request =
               request instanceof Request
                   ? (Request) request
                   : HttpConnection.getCurrentConnection().getRequest();
           base_request.setHandled(true);
         }
       });
   server.start();
 }
Beispiel #8
0
  public static void main(String[] args) throws Exception {
    ApplicationProperties properties = new ApplicationProperties();

    Server server = new Server();
    SocketConnector connector = new SocketConnector();
    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(1000 * 60 * 60);
    connector.setSoLingerTime(-1);

    int port = Integer.getInteger("jetty.port", properties.getHttpPort());
    connector.setPort(port);

    SslSocketConnector sslConnector = new SslSocketConnector();
    sslConnector.setMaxIdleTime(1000 * 60 * 60);
    sslConnector.setSoLingerTime(-1);
    sslConnector.setKeyPassword("password");
    sslConnector.setPassword("password");
    sslConnector.setKeystore("src/main/webapp/WEB-INF/keystore");

    port = Integer.getInteger("jetty.sslport", properties.getHttpsPort());
    sslConnector.setPort(port);

    server.setConnectors(new Connector[] {connector, sslConnector});

    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.addHandler(bb);

    try {
      System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
      server.start();
      while (System.in.available() == 0) {
        Thread.sleep(5000);
      }
      server.stop();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
Beispiel #9
0
  /**
   * Method to start the Jetty server
   *
   * @param jobDataMap
   */
  private void startServer(JobDataMap jobDataMap) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Initialising HTTP server");
    }
    int port = Integer.parseInt(jobDataMap.getString("port"));
    String bindAddress = jobDataMap.getString("bindAddress");
    String authConfigFile = jobDataMap.getString("authConfigFile");
    String keystore = jobDataMap.getString("keystore");
    Server server = new Server();
    if (keystore == null || keystore.equals("")) {
      LOG.info("Starting with HTTP (non-encrypted) protocol");
      SelectChannelConnector connector = new SelectChannelConnector();
      connector.setHost(bindAddress);
      connector.setPort(port);
      server.addConnector(connector);
    } else {
      LOG.info("Starting with HTTPS (encrypted) protocol");
      SslSocketConnector sslConnector = new SslSocketConnector();
      sslConnector.setHost(bindAddress);
      sslConnector.setPort(port);
      sslConnector.setKeystore(jobDataMap.getString("keystore"));
      sslConnector.setKeyPassword(jobDataMap.getString("keyPassword"));
      sslConnector.setTruststore(jobDataMap.getString("trustStore"));
      sslConnector.setTrustPassword(jobDataMap.getString("trustPassword"));
      sslConnector.setPassword(jobDataMap.getString("password"));
      server.addConnector(sslConnector);
    }

    if (authConfigFile != null && !(authConfigFile.equals(""))) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Requiring basic auth");
      }
      Constraint constraint = new Constraint();
      constraint.setName(Constraint.__BASIC_AUTH);
      ;
      constraint.setRoles(new String[] {"user", "grouper"});
      constraint.setAuthenticate(true);

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

      SecurityHandler sh = new SecurityHandler();
      try {
        sh.setUserRealm(new HashUserRealm("Grouper", authConfigFile));
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      sh.setConstraintMappings(new ConstraintMapping[] {cm});

      Handler[] handlers = new Handler[] {sh, new EsbHttpHandler()};
      server.setHandlers(handlers);

    } else {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Not requiring basic auth");
      }
      server.setHandler(new EsbHttpHandler());
    }
    try {
      server.start();
      LOG.info("HTTP server started on address " + bindAddress + " port " + port);
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #10
0
  /**
   * http://irc.codehaus.org/display/JETTY/Porting+to+jetty6
   *
   * <pre>
   * Server
   * 	HandlerCollection
   * 		ContextHandlerCollection
   * 			WebAppContext (i.e. ContextHandler)
   * 				SessionHandler
   * 				SecurityHandler
   * 				ServletHandler
   * 					servlets...
   * 			WebAppContext
   * 			...
   * 		DefaultHandler
   * 		RequestLogHandler (opt)
   * </pre>
   */
  public void startConsole() {
    File workDir = new SecureDirectory(_context.getTempDir(), "jetty-work");
    boolean workDirRemoved = FileUtil.rmdir(workDir, false);
    if (!workDirRemoved)
      System.err.println("ERROR: Unable to remove Jetty temporary work directory");
    boolean workDirCreated = workDir.mkdirs();
    if (!workDirCreated)
      System.err.println("ERROR: Unable to create Jetty temporary work directory");

    // try {
    //    Log.setLog(new I2PLogger(_context));
    // } catch (Throwable t) {
    //    System.err.println("INFO: I2P Jetty logging class not found, logging to wrapper log");
    // }
    // This way it doesn't try to load Slf4jLog first
    System.setProperty("org.mortbay.log.class", "net.i2p.jetty.I2PLogger");

    // so Jetty can find WebAppConfiguration
    System.setProperty("jetty.class.path", _context.getBaseDir() + "/lib/routerconsole.jar");
    _server = new Server();
    _server.setGracefulShutdown(1000);

    try {
      ThreadPool ctp = new CustomThreadPoolExecutor();
      ctp.prestartAllCoreThreads();
      _server.setThreadPool(ctp);
    } catch (Throwable t) {
      // class not found...
      System.out.println("INFO: Jetty concurrent ThreadPool unavailable, using QueuedThreadPool");
      QueuedThreadPool qtp = new QueuedThreadPool(MAX_THREADS);
      qtp.setMinThreads(MIN_THREADS);
      qtp.setMaxIdleTimeMs(MAX_IDLE_TIME);
      _server.setThreadPool(qtp);
    }

    HandlerCollection hColl = new HandlerCollection();
    ContextHandlerCollection chColl = new ContextHandlerCollection();
    _server.addHandler(hColl);
    hColl.addHandler(chColl);
    hColl.addHandler(new DefaultHandler());

    String log = _context.getProperty("routerconsole.log");
    if (log != null) {
      File logFile = new File(log);
      if (!logFile.isAbsolute()) logFile = new File(_context.getLogDir(), "logs/" + log);
      try {
        RequestLogHandler rhl = new RequestLogHandler();
        rhl.setRequestLog(new NCSARequestLog(logFile.getAbsolutePath()));
        hColl.addHandler(rhl);
      } catch (Exception ioe) {
        System.err.println("ERROR: Unable to create Jetty log: " + ioe);
      }
    }
    boolean rewrite = false;
    Properties props = webAppProperties();
    if (props.isEmpty()) {
      props.setProperty(PREFIX + ROUTERCONSOLE + ENABLED, "true");
      rewrite = true;
    }

    // Get an absolute path with a trailing slash for the webapps dir
    // We assume relative to the base install dir for backward compatibility
    File app = new File(_webAppsDir);
    if (!app.isAbsolute()) {
      app = new File(_context.getBaseDir(), _webAppsDir);
      try {
        _webAppsDir = app.getCanonicalPath();
      } catch (IOException ioe) {
      }
    }
    if (!_webAppsDir.endsWith("/")) _webAppsDir += '/';

    WebAppContext rootWebApp = null;
    ServletHandler rootServletHandler = null;
    List<Connector> connectors = new ArrayList(4);
    try {
      int boundAddresses = 0;
      Set addresses = Addresses.getAllAddresses();
      boolean hasIPV4 = addresses.contains("0.0.0.0");
      boolean hasIPV6 = addresses.contains("0:0:0:0:0:0:0:0");

      // add standard listeners
      int lport = 0;
      if (_listenPort != null) {
        try {
          lport = Integer.parseInt(_listenPort);
        } catch (NumberFormatException nfe) {
        }
        if (lport <= 0) System.err.println("Bad routerconsole port " + _listenPort);
      }
      if (lport > 0) {
        StringTokenizer tok = new StringTokenizer(_listenHost, " ,");
        while (tok.hasMoreTokens()) {
          String host = tok.nextToken().trim();
          try {
            // Test before we add the connector, because Jetty 6 won't start if any of the
            // connectors are bad
            InetAddress test = InetAddress.getByName(host);
            if ((!hasIPV6) && (!(test instanceof Inet4Address)))
              throw new IOException("IPv6 addresses unsupported");
            if ((!hasIPV4) && (test instanceof Inet4Address))
              throw new IOException("IPv4 addresses unsupported");
            ServerSocket testSock = null;
            try {
              // On Windows, this was passing and Jetty was still failing,
              // possibly due to %scope_id ???
              // https://issues.apache.org/jira/browse/ZOOKEEPER-667
              // testSock = new ServerSocket(0, 0, test);
              // so do exactly what Jetty does in SelectChannelConnector.open()
              testSock = new ServerSocket();
              InetSocketAddress isa = new InetSocketAddress(host, 0);
              testSock.bind(isa);
            } finally {
              if (testSock != null)
                try {
                  testSock.close();
                } catch (IOException ioe) {
                }
            }
            // if (host.indexOf(":") >= 0) // IPV6 - requires patched Jetty 5
            //    _server.addListener('[' + host + "]:" + _listenPort);
            // else
            //    _server.addListener(host + ':' + _listenPort);
            AbstractConnector lsnr;
            if (SystemVersion.isJava6() && !SystemVersion.isGNU()) {
              SelectChannelConnector slsnr = new SelectChannelConnector();
              slsnr.setUseDirectBuffers(false); // default true seems to be leaky
              lsnr = slsnr;
            } else {
              // Jetty 6 and NIO on Java 5 don't get along that well
              // Also: http://jira.codehaus.org/browse/JETTY-1238
              // "Do not use GCJ with Jetty, it will not work."
              // Actually it does if you don't use NIO
              lsnr = new SocketConnector();
            }
            lsnr.setHost(host);
            lsnr.setPort(lport);
            lsnr.setMaxIdleTime(90 * 1000); // default 10 sec
            lsnr.setName("ConsoleSocket"); // all with same name will use the same thread pool
            // _server.addConnector(lsnr);
            connectors.add(lsnr);
            boundAddresses++;
          } catch (Exception ioe) {
            System.err.println(
                "Unable to bind routerconsole to " + host + " port " + _listenPort + ": " + ioe);
            System.err.println(
                "You may ignore this warning if the console is still available at http://localhost:"
                    + _listenPort);
          }
        }
        // XXX: what if listenhosts do not include 127.0.0.1? (Should that ever even happen?)
        _context.portMapper().register(PortMapper.SVC_CONSOLE, lport);
      }

      // add SSL listeners
      int sslPort = 0;
      if (_sslListenPort != null) {
        try {
          sslPort = Integer.parseInt(_sslListenPort);
        } catch (NumberFormatException nfe) {
        }
        if (sslPort <= 0) System.err.println("Bad routerconsole SSL port " + _sslListenPort);
      }
      if (sslPort > 0) {
        File keyStore = new File(_context.getConfigDir(), "keystore/console.ks");
        if (verifyKeyStore(keyStore)) {
          StringTokenizer tok = new StringTokenizer(_sslListenHost, " ,");
          while (tok.hasMoreTokens()) {
            String host = tok.nextToken().trim();
            // doing it this way means we don't have to escape an IPv6 host with []
            try {
              // Test before we add the connector, because Jetty 6 won't start if any of the
              // connectors are bad
              InetAddress test = InetAddress.getByName(host);
              if ((!hasIPV6) && (!(test instanceof Inet4Address)))
                throw new IOException("IPv6 addresses unsupported");
              if ((!hasIPV4) && (test instanceof Inet4Address))
                throw new IOException("IPv4 addresses unsupported");
              ServerSocket testSock = null;
              try {
                // see comments above
                // testSock = new ServerSocket(0, 0, test);
                testSock = new ServerSocket();
                InetSocketAddress isa = new InetSocketAddress(host, 0);
                testSock.bind(isa);
              } finally {
                if (testSock != null)
                  try {
                    testSock.close();
                  } catch (IOException ioe) {
                  }
              }
              // TODO if class not found use SslChannelConnector
              // Sadly there's no common base class with the ssl methods in it
              AbstractConnector ssll;
              if (SystemVersion.isJava6() && !SystemVersion.isGNU()) {
                SslSelectChannelConnector sssll = new SslSelectChannelConnector();
                // the keystore path and password
                sssll.setKeystore(keyStore.getAbsolutePath());
                sssll.setPassword(
                    _context.getProperty(PROP_KEYSTORE_PASSWORD, DEFAULT_KEYSTORE_PASSWORD));
                // the X.509 cert password (if not present, verifyKeyStore() returned false)
                sssll.setKeyPassword(_context.getProperty(PROP_KEY_PASSWORD, "thisWontWork"));
                sssll.setUseDirectBuffers(false); // default true seems to be leaky
                ssll = sssll;
              } else {
                // Jetty 6 and NIO on Java 5 don't get along that well
                SslSocketConnector sssll = new SslSocketConnector();
                // the keystore path and password
                sssll.setKeystore(keyStore.getAbsolutePath());
                sssll.setPassword(
                    _context.getProperty(PROP_KEYSTORE_PASSWORD, DEFAULT_KEYSTORE_PASSWORD));
                // the X.509 cert password (if not present, verifyKeyStore() returned false)
                sssll.setKeyPassword(_context.getProperty(PROP_KEY_PASSWORD, "thisWontWork"));
                ssll = sssll;
              }
              ssll.setHost(host);
              ssll.setPort(sslPort);
              ssll.setMaxIdleTime(90 * 1000); // default 10 sec
              ssll.setName("ConsoleSocket"); // all with same name will use the same thread pool
              // _server.addConnector(ssll);
              connectors.add(ssll);
              boundAddresses++;
            } catch (Exception e) {
              System.err.println(
                  "Unable to bind routerconsole to "
                      + host
                      + " port "
                      + sslPort
                      + " for SSL: "
                      + e);
              if (SystemVersion.isGNU())
                System.err.println("Probably because GNU classpath does not support Sun keystores");
              System.err.println(
                  "You may ignore this warning if the console is still available at https://localhost:"
                      + sslPort);
            }
          }
          _context.portMapper().register(PortMapper.SVC_HTTPS_CONSOLE, sslPort);
        } else {
          System.err.println(
              "Unable to create or access keystore for SSL: " + keyStore.getAbsolutePath());
        }
      }

      if (boundAddresses <= 0) {
        System.err.println(
            "Unable to bind routerconsole to any address on port "
                + _listenPort
                + (sslPort > 0 ? (" or SSL port " + sslPort) : ""));
        return;
      }

      rootWebApp = new LocaleWebAppHandler(_context, "/", _webAppsDir + ROUTERCONSOLE + ".war");
      File tmpdir =
          new SecureDirectory(
              workDir, ROUTERCONSOLE + "-" + (_listenPort != null ? _listenPort : _sslListenPort));
      tmpdir.mkdir();
      rootWebApp.setTempDirectory(tmpdir);
      rootWebApp.setExtractWAR(false);
      rootWebApp.setSessionHandler(new SessionHandler());
      rootServletHandler = new ServletHandler();
      rootWebApp.setServletHandler(rootServletHandler);
      initialize(_context, rootWebApp);
      chColl.addHandler(rootWebApp);

    } catch (Exception ioe) {
      ioe.printStackTrace();
    }

    try {
      // start does a mapContexts()
      _server.start();
    } catch (Throwable me) {
      // NoClassFoundDefError from a webapp is a throwable, not an exception
      System.err.println("Error starting the Router Console server: " + me);
      me.printStackTrace();
    }

    if (_server.isRunning()) {
      // Add and start the connectors one-by-one
      boolean error = false;
      for (Connector conn : connectors) {
        try {
          _server.addConnector(conn);
          // start after adding so it gets the right thread pool
          conn.start();
        } catch (Throwable me) {
          try {
            _server.removeConnector(conn);
          } catch (Throwable t) {
            t.printStackTrace();
          }
          System.err.println("WARNING: Error starting " + conn + ": " + me);
          me.printStackTrace();
          error = true;
        }
      }
      if (error) {
        System.err.println(
            "WARNING: Error starting one or more listeners of the Router Console server.\n"
                + "If your console is still accessible at http://127.0.0.1:"
                + _listenPort
                + "/,\n"
                + "this may be a problem only with binding to the IPV6 address ::1.\n"
                + "If so, you may ignore this error, or remove the\n"
                + "\"::1,\" in the \"clientApp.0.args\" line of the clients.config file.");
      }
    }

    // Start all the other webapps after the server is up,
    // so things start faster.
    // Jetty 6 starts the connector before the router console is ready
    // This also prevents one webapp from breaking the whole thing
    List<String> notStarted = new ArrayList();
    if (_server.isRunning()) {
      File dir = new File(_webAppsDir);
      String fileNames[] = dir.list(WarFilenameFilter.instance());
      if (fileNames != null) {
        for (int i = 0; i < fileNames.length; i++) {
          String appName = fileNames[i].substring(0, fileNames[i].lastIndexOf(".war"));
          String enabled = props.getProperty(PREFIX + appName + ENABLED);
          if (!"false".equals(enabled)) {
            try {
              String path = new File(dir, fileNames[i]).getCanonicalPath();
              WebAppStarter.startWebApp(_context, chColl, appName, path);
              if (enabled == null) {
                // do this so configclients.jsp knows about all apps from reading the config
                props.setProperty(PREFIX + appName + ENABLED, "true");
                rewrite = true;
              }
            } catch (Throwable t) {
              System.err.println("ERROR: Failed to start " + appName + ' ' + t);
              t.printStackTrace();
              notStarted.add(appName);
            }
          } else {
            notStarted.add(appName);
          }
        }
        changeState(RUNNING);
      }
    } else {
      System.err.println("ERROR: Router console did not start, not starting webapps");
      changeState(START_FAILED);
    }

    if (rewrite) storeWebAppProperties(_context, props);

    if (rootServletHandler != null && notStarted.size() > 0) {
      // map each not-started webapp to the error page
      ServletHolder noWebApp = rootServletHandler.getServlet("net.i2p.router.web.jsp.nowebapp_jsp");
      for (int i = 0; i < notStarted.size(); i++) {
        // we want a new handler for each one since if the webapp is started we remove the
        // handler???
        try {
          if (noWebApp != null) {
            String path = '/' + notStarted.get(i);
            // LocaleWebAppsHandler adds a .jsp
            rootServletHandler.addServletWithMapping(noWebApp, path + ".jsp");
            rootServletHandler.addServletWithMapping(noWebApp, path + "/*");
          } else {
            System.err.println("Can't find nowebapp.jsp?");
          }
        } catch (Throwable me) {
          System.err.println(me);
          me.printStackTrace();
        }
      }
    }

    Thread t = new I2PAppThread(new StatSummarizer(), "StatSummarizer", true);
    t.setPriority(Thread.NORM_PRIORITY - 1);
    t.start();

    ConsoleUpdateManager um = new ConsoleUpdateManager(_context);
    um.start();

    if (PluginStarter.pluginsEnabled(_context)) {
      t = new I2PAppThread(new PluginStarter(_context), "PluginStarter", true);
      t.setPriority(Thread.NORM_PRIORITY - 1);
      t.start();
      _context.addShutdownTask(new PluginStopper(_context));
    }
    // stat summarizer registers its own hook
    _context.addShutdownTask(new ServerShutdown());
    ConfigServiceHandler.registerSignalHandler(_context);
  }
  public static void main(String[] args) throws Exception {
    SocketConnector socketConnector = new SocketConnector();
    socketConnector.setPort(6080);

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setPort(6443);
    //        sslSocketConnector.setNeedClientAuth(true); //why not use mutual authentication when
    // we can

    String serverKeystore =
        MockHttpListenerWithAuthentication.class
            .getClassLoader()
            .getResource("cert/serverkeystore.jks")
            .getPath();
    sslSocketConnector.setKeystore(serverKeystore);
    sslSocketConnector.setKeyPassword("serverpass");
    String serverTruststore =
        MockHttpListenerWithAuthentication.class
            .getClassLoader()
            .getResource("cert/servertruststore.jks")
            .getPath();
    sslSocketConnector.setTruststore(serverTruststore);
    sslSocketConnector.setTrustPassword("serverpass");

    server.addConnector(socketConnector);
    server.addConnector(sslSocketConnector);

    SecurityHandler securityHandler = createBasicAuthenticationSecurityHandler();

    HandlerList handlerList = new HandlerList();
    handlerList.addHandler(securityHandler);
    handlerList.addHandler(
        new AbstractHandler() {
          @Override
          public void handle(
              String s,
              HttpServletRequest httpServletRequest,
              HttpServletResponse httpServletResponse,
              int i)
              throws IOException, ServletException {
            System.out.println("uri: " + httpServletRequest.getRequestURI());
            System.out.println("queryString: " + httpServletRequest.getQueryString());
            System.out.println("method: " + httpServletRequest.getMethod());

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(httpServletRequest.getInputStream(), baos);

            System.out.println("body: " + baos.toString());

            PrintWriter writer = httpServletResponse.getWriter();
            writer.append("testsvar");
            Random r = new Random();
            for (int j = 0; j < 10; j++) {
              int value = r.nextInt(Integer.MAX_VALUE);
              writer.append(value + "");
            }
            System.out.println();
            writer.close();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
          }
        });

    server.addHandler(handlerList);
    server.start();
  }
  @SuppressWarnings("unchecked")
  public static void startup(String args[]) {
    try {
      Server server = new Server();
      System.err.println("mycat init ... ");

      int httpPort = 7066;
      int httpsPort = -1;
      String contextPath = "/";

      String keyStorePath = null;
      String keyStorePassword = null;

      String updateServer = null;

      boolean disableUpdateCenterSwitch = false;
      boolean skipInitSetup = false;

      for (int i = 0; i < args.length; ++i) {
        String portStr;
        if (args[i].startsWith("--httpPort=")) {
          portStr = args[i].substring("--httpPort=".length());
          httpPort = Integer.parseInt(portStr);
        }

        if (args[i].startsWith("--httpsPort=")) {
          portStr = args[i].substring("--httpsPort=".length());
          httpsPort = Integer.parseInt(portStr);
        }

        if (args[i].startsWith("--httpsKeyStore=")) {
          keyStorePath = args[i].substring("--httpsKeyStore=".length());
        }

        if (args[i].startsWith("--httpsKeyStorePassword="******"--httpsKeyStorePassword="******"--prefix=")) {
          String prefix = args[i].substring("--prefix=".length());
          if (prefix.startsWith("/")) contextPath = prefix;
          else {
            contextPath = "/" + prefix;
          }
        }
        if (args[i].startsWith("--updateServer=")) {
          updateServer = args[i].substring("--updateServer=".length());
        }

        if (args[i].startsWith("--disableUpdateCenterSwitch")) {
          disableUpdateCenterSwitch = true;
        }

        if (args[i].startsWith("--skipInitSetup")) {
          skipInitSetup = true;
        }
      }

      List connectors = new ArrayList();
      if (httpPort != -1) {
        SelectChannelConnector httpConnector = new SelectChannelConnector();
        httpConnector.setPort(httpPort);
        connectors.add(httpConnector);
      }

      if (httpsPort != -1) {
        SslSocketConnector httpsConnector = new SslSocketConnector();
        httpsConnector.setPort(httpsPort);
        if (keyStorePath != null) {
          httpsConnector.setKeystore(keyStorePath);
        }
        if (keyStorePassword != null) {
          httpsConnector.setKeyPassword(keyStorePassword);
        }
        connectors.add(httpsConnector);
      }

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

      ProtectionDomain protectionDomain = Executable.class.getProtectionDomain();
      URL location = protectionDomain.getCodeSource().getLocation();
      String url = java.net.URLDecoder.decode(location.getPath(), "utf-8");
      System.out.println(url);

      File tempDir = new File(getHomeDir(), "war");
      tempDir.mkdirs();

      WebAppContext webapp = new WebAppContext();
      webapp.setContextPath("/mycat"); //
      webapp.setDescriptor(url + "/WEB-INF/web.xml");
      webapp.setResourceBase(url);
      webapp.setTempDirectory(tempDir);

      server.setHandler(webapp);

      System.err.println("mycat start success,port: " + httpsPort);
      server.start();
      server.join();

    } catch (Exception e) {
      System.exit(-1);
    }
  }
  private void deployWebApp() {
    try {
      Server server = new Server();
      SelectChannelConnector connector = new SelectChannelConnector();
      connector.setMaxIdleTime(MAX_IDLE_TIME_MILLIS);
      connector.setHeaderBufferSize(HEADER_BUFFER_SIZE);
      connector.setHost(getHost());
      connector.setPort(getPort());
      if (isHttpsEnabled()) {
        connector.setConfidentialPort(getHttpsPort());
      }
      server.addConnector(connector);

      if (isHttpsEnabled()) {
        SslSocketConnector sslConnector = new SslSocketConnector();
        sslConnector.setMaxIdleTime(MAX_IDLE_TIME_MILLIS);
        sslConnector.setHeaderBufferSize(HEADER_BUFFER_SIZE);
        sslConnector.setHost(getHost());
        sslConnector.setPort(getHttpsPort());
        sslConnector.setKeystore(
            System.getProperty(
                "subsonic.ssl.keystore",
                getClass().getResource("/subsonic.keystore").toExternalForm()));
        sslConnector.setPassword(System.getProperty("subsonic.ssl.password", "subsonic"));
        server.addConnector(sslConnector);
      }

      WebAppContext context = new WebAppContext();
      context.setTempDirectory(getJettyDirectory());
      context.setContextPath(getContextPath());
      context.setWar(getWar());
      context.setOverrideDescriptor("/web-jetty.xml");

      if (isHttpsEnabled()) {

        // Allow non-https for streaming and cover art (for Chromecast, UPnP, Sonos etc)
        context
            .getSecurityHandler()
            .setConstraintMappings(
                new ConstraintMapping[] {
                  createConstraintMapping("/stream", Constraint.DC_NONE),
                  createConstraintMapping("/coverArt.view", Constraint.DC_NONE),
                  createConstraintMapping("/ws/*", Constraint.DC_NONE),
                  createConstraintMapping("/sonos/*", Constraint.DC_NONE),
                  createConstraintMapping("/", Constraint.DC_CONFIDENTIAL)
                });
      }

      server.addHandler(context);
      server.start();

      System.err.println("Subsonic running on: " + getUrl());
      if (isHttpsEnabled()) {
        System.err.println("                and: " + getHttpsUrl());
      }

    } catch (Throwable x) {
      x.printStackTrace();
      exception = x;
    }
  }