Exemple #1
1
  public final void start(int port) throws Exception {
    String nodeId = registerForNotifications();
    port = setPort(port);

    System.out.println("DSO SharedQueue (node " + nodeId + ")");
    System.out.println(
        "Open your browser and go to - http://" + getHostName() + ":" + port + "/webapp\n");

    Server server = new Server();
    Connector connector = new SocketConnector();
    connector.setPort(port);
    server.setConnectors(new Connector[] {connector});

    queue = new Queue(port);
    worker = queue.createWorker(nodeId);

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase(".");

    ContextHandler ajaxContext = new ContextHandler();
    ajaxContext.setContextPath(SimpleHttpHandler.ACTION);
    ajaxContext.setResourceBase(cwd.getPath());
    ajaxContext.setClassLoader(Thread.currentThread().getContextClassLoader());
    ajaxContext.addHandler(new SimpleHttpHandler(queue));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {ajaxContext, resourceHandler});
    server.setHandler(handlers);

    startReaper();
    server.start();
    server.join();
  }
 public synchronized void pause(boolean paused) {
   try {
     if (paused) for (Connector connector : getConnectors()) connector.stop();
     else for (Connector connector : getConnectors()) connector.start();
   } catch (Exception e) {
   }
 }
  public void setConnector(int port) throws Exception {
    Connector listener = new SelectChannelConnector();

    listener.setHost("127.0.0.1");
    listener.setPort(port);
    server.addConnector(listener);
  }
  /** ignores the arguments and just bootstraps JettyViewer, come what may. */
  @Override
  public void bootstrap(final Injector injector) {

    final IsisConfigurationBuilder isisConfigurationBuilder = runner.getStartupConfiguration();

    // we don't actually bootstrap the system here; instead we expect it to
    // be bootstrapped
    // from the ServletContextInitializer in the web.xml
    final IsisConfiguration configuration = isisConfigurationBuilder.getConfiguration();
    final int port =
        configuration.getInteger(EMBEDDED_WEB_SERVER_PORT_KEY, EMBEDDED_WEB_SERVER_PORT_DEFAULT);
    final String webappContextPath =
        configuration.getString(
            EMBEDDED_WEB_SERVER_RESOURCE_BASE_KEY, EMBEDDED_WEB_SERVER_RESOURCE_BASE_DEFAULT);
    final StartupMode startupMode =
        StartupMode.lookup(
            configuration.getString(
                EMBEDDED_WEB_SERVER_STARTUP_MODE_KEY, EMBEDDED_WEB_SERVER_STARTUP_MODE_DEFAULT));
    // TODO get and use the address

    jettyServer = new Server(port);
    Connector[] connectors = jettyServer.getConnectors();
    Connector connector = connectors[0];
    connector.setHeaderBufferSize(8192);
    final WebAppContext context = new WebAppContext(SRC_MAIN_WEBAPP, webappContextPath);

    copyConfigurationPrimersIntoServletContext(context);

    jettyServer.setHandler(context);

    LOG.info("starting Jetty on port " + port + " to serve webapp");
    try {
      jettyServer.start();
      if (startupMode.isForeground()) {
        jettyServer.join();
      }
    } catch (final Exception ex) {
      throw new IsisException("Unable to start Jetty server", ex);
    }
  }
  @Test
  public void submitJob() throws Exception {
    org.h2.tools.Server h2 = org.h2.tools.Server.createTcpServer();
    Server server = new Server();
    Connector connector = new SelectChannelConnector();
    connector.setPort(8081);
    connector.setHost("127.0.0.1");
    server.addConnector(connector);

    WebAppContext wac = new WebAppContext();
    wac.setContextPath("/springbatchadmin");
    wac.setWar("./src/main/webapp");
    server.setHandler(wac);
    server.setStopAtShutdown(true);

    try {
      h2.start();
      server.start();
      assertTrue(restTemplate.getForObject(BASE_URL + "jobs.json", String.class).contains(JOB));
    } finally {
      server.stop();
      h2.stop();
    }
  }
  /** temp main - just to help testing */
  public static void main(String[] args) throws Exception {
    Server server = new Server();
    Connector connector = new GrizzlyConnector();
    connector.setPort(8080);
    server.setConnectors(new Connector[] {connector});

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

    // TODO add javadoc context to contexts

    WebAppContext.addWebApplications(
        server, "../../webapps", "org/mortbay/jetty/webapp/webdefault.xml", true, false);

    HashUserRealm userRealm = new HashUserRealm();
    userRealm.setName("Test Realm");
    userRealm.setConfig("../../etc/realm.properties");
    server.setUserRealms(new UserRealm[] {userRealm});

    server.start();
    server.join();
  }
  /**
   * 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, "/");
  }
  /**
   * 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);
  }
Exemple #9
0
  public static void main(String[] args) throws Exception {
    String name = args.length > 0 ? args[0] : "app";
    Mocker mocker = Mocker.init(name);
    String webXml = mocker.getWebXml();
    int port = mocker.getPort();

    File fapp = new File(APP_PATH);
    final Connector conn = new SelectChannelConnector();
    conn.setPort(port);
    conn.setMaxIdleTime(60000);
    conn.setHeaderBufferSize(20480); // 缺省4K, Chrome下可能会报错: 413 FULL head

    Listener listerner =
        new Listener() {

          @Override
          public void lifeCycleFailure(LifeCycle arg0, Throwable arg1) {
            logger.info("YDJT SYSTEM {} FAILED!!!", Application.VERSION);
          }

          @Override
          public void lifeCycleStarted(LifeCycle arg0) {
            logger.info("YDJT SYSTEM {} STARTED!", Application.VERSION);
          }

          @Override
          public void lifeCycleStarting(LifeCycle arg0) {
            logger.info("YDJT SYSTEM {} STARTING...", Application.VERSION);
          }

          @Override
          public void lifeCycleStopped(LifeCycle arg0) {
            logger.info("YDJT SYSTEM {} STOPPED!", Application.VERSION);
          }

          @Override
          public void lifeCycleStopping(LifeCycle arg0) {
            logger.info("YDJT SYSTEM {} STOPPING...", Application.VERSION);
          }
        };
    Server server = new Server();
    server.addLifeCycleListener(listerner);
    server.addConnector(conn);
    WebAppContext wapp = new WebAppContext(server, fapp.getCanonicalPath(), CONTEXT_PATH);

    HandlerCollection hc = new HandlerCollection();
    ContextHandlerCollection chc = new ContextHandlerCollection();
    hc.setHandlers(new Handler[] {chc, new DefaultHandler()});

    ContextDeployer cd = new ContextDeployer();
    cd.setContexts(chc);
    cd.setConfigurationDir(APP_PATH);
    cd.setDirectory(APP_PATH);
    cd.setScanInterval(5);

    wapp.setClassLoader(ClassLoader.getSystemClassLoader());
    wapp.setParentLoaderPriority(false);
    wapp.setExtractWAR(false);
    // setDescriptor() -- 使用其他文件作为web.xml
    // wapp.setDefaultsDescriptor(WEB_XML);
    // setWelcomeFiles()和web.xml中的welcome-file-list都没有用,
    // 因为/已定义在test-mvc的servlet-mapping中??
    wapp.setDescriptor(APP_PATH + "/WEB-INF/" + webXml);

    // server.addLifeCycle(wapp);
    server.addHandler(hc);
    server.start();
    server.join();
    wapp.start();
    server.addLifeCycle(cd);
  }
  /**
   * 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);
    }
  }
 private static Connector createHttpConnector() {
   Connector connector = new SelectChannelConnector();
   connector.setPort(port);
   return connector;
 }
Exemple #12
0
  public static void main(String[] args) throws Exception {
    int port = 8080;
    try {
      if (System.getProperty("port") != null && !System.getProperty("port").equals("")) {
        port = Integer.decode(System.getProperty("port"));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    boolean rhttpEnabled = (args.length == 0);
    boolean rsoapEnabled =
        args.length == 0
            && System.getProperty("soapenabled") != null
            && System.getProperty("soapenabled").equals("true");

    Server server = new Server();
    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    connector.setHost(getHostIp());
    server.addConnector(connector);

    Connector connectorLocal = new SelectChannelConnector();
    connectorLocal.setPort(port);
    connectorLocal.setHost("127.0.0.1");
    server.addConnector(connectorLocal);

    if (rhttpEnabled) {
      cacheJar(
          new URL("http://biocep-distrib.r-forge.r-project.org/appletlibs/rvirtual.war"),
          ServerManager.INSTALL_DIR,
          LOG_PRGRESS_TO_SYSTEM_OUT,
          false);
      if (rsoapEnabled) {
        cacheJar(
            new URL("http://biocep-distrib.r-forge.r-project.org/appletlibs/rws.war"),
            ServerManager.INSTALL_DIR,
            LOG_PRGRESS_TO_SYSTEM_OUT,
            false);
        args =
            new String[] {
              ServerManager.INSTALL_DIR + "rvirtual.war", ServerManager.INSTALL_DIR + "rws.war"
            };
      } else {
        args = new String[] {ServerManager.INSTALL_DIR + "rvirtual.war"};
      }
    }

    for (int i = 0; i < args.length; ++i) {
      File warfile = new File(args[i]);
      if (!warfile.exists()) {
        System.out.println("couldn't find the war file :" + args[i]);
        System.exit(0);
      }

      String contextPath = "/" + warfile.getName();
      if (contextPath.endsWith(".war"))
        contextPath = contextPath.substring(0, contextPath.length() - ".war".length());

      WebAppContext wac = new WebAppContext();
      wac.setContextPath(contextPath);
      wac.setWar(warfile.getAbsolutePath());
      server.addHandler(wac);
    }

    server.setStopAtShutdown(true);
    server.start();

    while (!server.isStarted()) {
      try {
        Thread.sleep(20);
      } catch (Exception ex) {
      }
    }

    System.out.println("--> Http Server Started sucessfully on port " + port);

    if (rhttpEnabled) {
      System.out.println("R-HTTP URL: http://" + getHostIp() + ":" + port + "/rvirtual/cmd");
      System.out.println(
          "--> From the Virtual R Workbench, in Http mode, connect via the following URL:"
              + "http://"
              + getHostIp()
              + ":"
              + port
              + "/rvirtual/cmd");
    }

    if (rsoapEnabled) {
      System.out.println(
          "R-SOAP WSDL:" + "http://" + getHostIp() + ":" + port + "/rws/rGlobalEnvFunction?wsdl");
    }
  }
Exemple #13
0
  public void init(String host, int port) throws Exception {
    logger.info("Starting Server bound to '" + host + ":" + port + "'");

    String memory = Configurations.get("refine.memory");
    if (memory != null) {
      logger.info(
          "refine.memory size: " + memory + " JVM Max heap: " + Runtime.getRuntime().maxMemory());
    }

    int maxThreads = Configurations.getInteger("refine.queue.size", 30);
    int maxQueue = Configurations.getInteger("refine.queue.max_size", 300);
    long keepAliveTime = Configurations.getInteger("refine.queue.idle_time", 60);

    LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(maxQueue);

    threadPool =
        new ThreadPoolExecutor(maxThreads, maxQueue, keepAliveTime, TimeUnit.SECONDS, queue);

    this.setThreadPool(new ThreadPoolExecutorAdapter(threadPool));

    Connector connector = new SocketConnector();
    connector.setPort(port);
    connector.setHost(host);
    connector.setMaxIdleTime(Configurations.getInteger("refine.connection.max_idle_time", 60000));
    connector.setStatsOn(false);
    this.addConnector(connector);

    File webapp = new File(Configurations.get("refine.webapp", "main/webapp"));

    if (!isWebapp(webapp)) {
      webapp = new File("main/webapp");
      if (!isWebapp(webapp)) {
        webapp = new File("webapp");
        if (!isWebapp(webapp)) {
          logger.warn(
              "Warning: Failed to find web application at '" + webapp.getAbsolutePath() + "'");
          System.exit(-1);
        }
      }
    }

    final String contextPath = Configurations.get("refine.context_path", "/");

    logger.info(
        "Initializing context: '" + contextPath + "' from '" + webapp.getAbsolutePath() + "'");
    WebAppContext context = new WebAppContext(webapp.getAbsolutePath(), contextPath);
    context.setMaxFormContentSize(1048576);

    this.setHandler(context);
    this.setStopAtShutdown(true);
    this.setSendServerVersion(true);

    // Enable context autoreloading
    if (Configurations.getBoolean("refine.autoreload", false)) {
      scanForUpdates(webapp, context);
    }

    // start the server
    try {
      this.start();
    } catch (BindException e) {
      logger.error(
          "Failed to start server - is there another copy running already on this port/address?");
      throw e;
    }

    configure(context);
  }
Exemple #14
0
  private synchronized void enableRemoteAccess() throws Exception {

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

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

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

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

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

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

      ContextHandlerCollection contexts = new ContextHandlerCollection();

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

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

      MultiHandler mh = new MultiHandler(coreInterface, true);

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

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

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

      root.addHandler(securityHandler);

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

      authenticatedServer.start();

      remoteAccessForward = new RemoteAccessForward();
      remoteAccessForward.start();
      logger.fine("remote access enabled");
    }
    coreInterface.setRemoteAccess(remoteAccessForward);
  }
Exemple #15
0
  public void initialize(PluginInterface pluginInterface) throws PluginException {
    this.coreInterface = new CoreInterface(pluginInterface);

    // make sure to unload in case of shutdown

    this.pluginInterface = pluginInterface;

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

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

    server = new Server();

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

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

    checkAutoStartRegistry();
    server.addConnector(connector);

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

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

    MultiHandler mh = new MultiHandler(coreInterface, false);

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

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

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

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

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

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

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

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

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

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

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

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

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

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