예제 #1
0
파일: Jetty.java 프로젝트: jetwang/jet-2012
  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);
    }
  }
예제 #2
0
  public void start() throws Exception {
    server = new Server(serverPort);

    File keystore = TestFileUtil.createUniqueTempFile("keystore");
    File truststore = TestFileUtil.createUniqueTempFile("truststore");
    File agentKeystore = TestFileUtil.createUniqueTempFile("agentstore");
    createX509Certificate(keystore, truststore, agentKeystore);

    server.addConnector(sslConnector(keystore, truststore, sslPort));
    WebAppContext wac = new WebAppContext("testdata/goserverstub", "/go");
    wac.setConfigurationClasses(
        new String[] {
          WebInfConfiguration.class.getCanonicalName(),
          WebXmlConfiguration.class.getCanonicalName(),
          JettyWebXmlConfiguration.class.getCanonicalName()
        });

    addFakeArtifactiPublisherServlet(wac);
    addFakeAgentCertificateServlet(wac);
    server.setHandler(wac);
    server.setStopAtShutdown(true);
    server.start();
  }
  JawrIntegrationServer() {

    Properties prop = new Properties();
    InputStream inStream = getClass().getClassLoader().getResourceAsStream(PROP_FILE_NAME);
    if (inStream != null) {
      try {
        prop.load(inStream);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      IOUtils.closeQuietly(inStream);
    }

    serverPort = Integer.parseInt(prop.getProperty(PORT_PROPERTY_NAME, DEFAULT_PORT));
    server = new Server(serverPort);
    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);

    try {

      String host = "localhost";
      int jmxPort = 1099;
      String urlPath = String.format("/jndi/rmi://%s:%s/jmxrmi", host, jmxPort);
      JMXServiceURL serviceURL = new JMXServiceURL("rmi", host, jmxPort, urlPath);
      ConnectorServer connectorServer =
          new ConnectorServer(serviceURL, "org.eclipse.jetty.jmx:name=rmiconnectorserver");
      connectorServer.start();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    server.setStopAtShutdown(true);
    String webappName = prop.getProperty(WEBAPP_PROPERTY_NAME, DEFAULT_WEBAPP_NAME);
    try {
      webAppRootDir = new File(TARGET_ROOT_DIR + webappName).getCanonicalFile().getAbsolutePath();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    boolean useEmptyContextPath =
        Boolean.parseBoolean(
            prop.getProperty(
                USE_DEFAULT_CONTEXT_PATH_PROPERTY_NAME, DONT_USE_DEFAULT_CONTEXT_PATH));
    String webAppCtx = "";
    if (!useEmptyContextPath) {
      webAppCtx = "/" + webappName;
    }

    jettyWebAppContext = new WebAppContext(webAppRootDir, webAppCtx);
    jettyWebAppContext.setConfigurationClasses(
        new String[] {
          "org.eclipse.jetty.webapp.WebInfConfiguration",
          "org.eclipse.jetty.webapp.WebXmlConfiguration",
          "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
          "org.eclipse.jetty.annotations.AnnotationConfiguration"
        });

    ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
    contextHandlerCollection.setHandlers(new Handler[] {jettyWebAppContext});
    server.setHandler(contextHandlerCollection);
  }
예제 #4
0
  /**
   * Configure a jetty instance and deploy the webapps presented as args
   *
   * @param args the command line arguments
   * @throws Exception if unable to configure
   */
  public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
      if ("--lib".equals(args[i])) {
        try (Resource lib = Resource.newResource(args[++i])) {
          if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib);
          _classpath.addJars(lib);
        }
      } else if ("--jar".equals(args[i])) {
        try (Resource jar = Resource.newResource(args[++i])) {
          if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar);
          _classpath.addPath(jar);
        }
      } else if ("--classes".equals(args[i])) {
        try (Resource classes = Resource.newResource(args[++i])) {
          if (!classes.exists() || !classes.isDirectory())
            usage("No such classes directory " + classes);
          _classpath.addPath(classes);
        }
      } else if (args[i].startsWith("--")) i++;
    }

    initClassLoader();

    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);

    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;

    boolean runnerServerInitialized = false;

    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--port":
          port = Integer.parseInt(args[++i]);
          break;
        case "--host":
          host = args[++i];
          break;
        case "--stop-port":
          stopPort = Integer.parseInt(args[++i]);
          break;
        case "--stop-key":
          stopKey = args[++i];
          break;
        case "--log":
          _logFile = args[++i];
          break;
        case "--out":
          String outFile = args[++i];
          PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
          LOG.info("Redirecting stderr/stdout to " + outFile);
          System.setErr(out);
          System.setOut(out);
          break;
        case "--path":
          contextPath = args[++i];
          contextPathSet = true;
          break;
        case "--config":
          if (_configFiles == null) _configFiles = new ArrayList<>();
          _configFiles.add(args[++i]);
          break;
        case "--lib":
          ++i; // skip

          break;
        case "--jar":
          ++i; // skip

          break;
        case "--classes":
          ++i; // skip

          break;
        case "--stats":
          _enableStats = true;
          _statsPropFile = args[++i];
          _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
          break;
        default:
          // process contexts

          if (!runnerServerInitialized) // log handlers not registered, server maybe not created,
                                        // etc
          {
            if (_server == null) // server not initialized yet
            {
              // build the server
              _server = new Server();
            }

            // apply jetty config files if there are any
            if (_configFiles != null) {
              for (String cfg : _configFiles) {
                try (Resource resource = Resource.newResource(cfg)) {
                  XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                  xmlConfiguration.configure(_server);
                }
              }
            }

            // check that everything got configured, and if not, make the handlers
            HandlerCollection handlers =
                (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
            if (handlers == null) {
              handlers = new HandlerCollection();
              _server.setHandler(handlers);
            }

            // check if contexts already configured
            _contexts =
                (ContextHandlerCollection)
                    handlers.getChildHandlerByClass(ContextHandlerCollection.class);
            if (_contexts == null) {
              _contexts = new ContextHandlerCollection();
              prependHandler(_contexts, handlers);
            }

            if (_enableStats) {
              // if no stats handler already configured
              if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                StatisticsHandler statsHandler = new StatisticsHandler();

                Handler oldHandler = _server.getHandler();
                statsHandler.setHandler(oldHandler);
                _server.setHandler(statsHandler);

                ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                statsContext.setSessionHandler(new SessionHandler());
                if (_statsPropFile != null) {
                  HashLoginService loginService =
                      new HashLoginService("StatsRealm", _statsPropFile);
                  Constraint constraint = new Constraint();
                  constraint.setName("Admin Only");
                  constraint.setRoles(new String[] {"admin"});
                  constraint.setAuthenticate(true);

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

                  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                  securityHandler.setLoginService(loginService);
                  securityHandler.setConstraintMappings(Collections.singletonList(cm));
                  securityHandler.setAuthenticator(new BasicAuthenticator());
                  statsContext.setSecurityHandler(securityHandler);
                }
              }
            }

            // ensure a DefaultHandler is present
            if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
              handlers.addHandler(new DefaultHandler());
            }

            // ensure a log handler is present
            _logHandler =
                (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
            if (_logHandler == null) {
              _logHandler = new RequestLogHandler();
              handlers.addHandler(_logHandler);
            }

            // check a connector is configured to listen on
            Connector[] connectors = _server.getConnectors();
            if (connectors == null || connectors.length == 0) {
              ServerConnector connector = new ServerConnector(_server);
              connector.setPort(port);
              if (host != null) connector.setHost(host);
              _server.addConnector(connector);
              if (_enableStats) connector.addBean(new ConnectorStatistics());
            } else {
              if (_enableStats) {
                for (Connector connector : connectors) {
                  ((AbstractConnector) connector).addBean(new ConnectorStatistics());
                }
              }
            }

            runnerServerInitialized = true;
          }

          // Create a context
          try (Resource ctx = Resource.newResource(args[i])) {
            if (!ctx.exists()) usage("Context '" + ctx + "' does not exist");

            if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath;

            // Configure the context
            if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) {
              // It is a context config file
              XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
              xmlConfiguration.getIdMap().put("Server", _server);
              ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
              if (contextPathSet) handler.setContextPath(contextPath);
              _contexts.addHandler(handler);
              handler.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            } else {
              // assume it is a WAR file
              WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
              webapp.setConfigurationClasses(__plusConfigurationClasses);
              webapp.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            }
          }
          // reset
          contextPathSet = false;
          contextPath = __defaultContextPath;
          break;
      }
    }

    if (_server == null) usage("No Contexts defined");
    _server.setStopAtShutdown(true);

    switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
      case 1:
        usage("Must specify --stop-key when --stop-port is specified");
        break;

      case 2:
        usage("Must specify --stop-port when --stop-key is specified");
        break;

      case 3:
        ShutdownMonitor monitor = ShutdownMonitor.getInstance();
        monitor.setPort(stopPort);
        monitor.setKey(stopKey);
        monitor.setExitVm(true);
        break;
    }

    if (_logFile != null) {
      NCSARequestLog requestLog = new NCSARequestLog(_logFile);
      requestLog.setExtended(false);
      _logHandler.setRequestLog(requestLog);
    }
  }
예제 #5
0
  /* ------------------------------------------------------------ */
  @Override
  public ContextHandler createContextHandler(final App app) throws Exception {
    Resource resource = Resource.newResource(app.getOriginId());
    File file = resource.getFile();
    if (!resource.exists())
      throw new IllegalStateException("App resouce does not exist " + resource);

    String context = file.getName();

    if (resource.exists() && FileID.isXmlFile(file)) {
      XmlConfiguration xmlc = new XmlConfiguration(resource.getURL());

      xmlc.getIdMap().put("Server", getDeploymentManager().getServer());
      if (getConfigurationManager() != null)
        xmlc.getProperties().putAll(getConfigurationManager().getProperties());
      return (ContextHandler) xmlc.configure();
    } else if (file.isDirectory()) {
      // must be a directory
    } else if (FileID.isWebArchiveFile(file)) {
      // Context Path is the same as the archive.
      context = context.substring(0, context.length() - 4);
    } else {
      throw new IllegalStateException("unable to create ContextHandler for " + app);
    }

    // Ensure "/" is Not Trailing in context paths.
    if (context.endsWith("/") && context.length() > 0) {
      context = context.substring(0, context.length() - 1);
    }

    // Start building the webapplication
    WebAppContext wah = new WebAppContext();
    wah.setDisplayName(context);

    // special case of archive (or dir) named "root" is / context
    if (context.equalsIgnoreCase("root")) {
      context = URIUtil.SLASH;
    } else if (context.toLowerCase().startsWith("root-")) {
      int dash = context.toLowerCase().indexOf('-');
      String virtual = context.substring(dash + 1);
      wah.setVirtualHosts(new String[] {virtual});
      context = URIUtil.SLASH;
    }

    // Ensure "/" is Prepended to all context paths.
    if (context.charAt(0) != '/') {
      context = "/" + context;
    }

    wah.setContextPath(context);
    wah.setWar(file.getAbsolutePath());
    if (_defaultsDescriptor != null) {
      wah.setDefaultsDescriptor(_defaultsDescriptor);
    }
    wah.setExtractWAR(_extractWars);
    wah.setParentLoaderPriority(_parentLoaderPriority);
    if (_configurationClasses != null) {
      wah.setConfigurationClasses(_configurationClasses);
    }

    if (_tempDirectory != null) {
      /* Since the Temp Dir is really a context base temp directory,
       * Lets set the Temp Directory in a way similar to how WebInfConfiguration does it,
       * instead of setting the
       * WebAppContext.setTempDirectory(File).
       * If we used .setTempDirectory(File) all webapps will wind up in the
       * same temp / work directory, overwriting each others work.
       */
      wah.setAttribute(WebAppContext.BASETEMPDIR, _tempDirectory);
    }
    return wah;
  }
    public void configureWebApp() throws Exception {
      // TODO turn this around and let any context.xml file get applied first, and have the
      // properties override
      _webApp.setContextPath(_contextPath);

      // osgi Enterprise Spec r4 p.427
      _webApp.setAttribute(OSGiWebappConstants.OSGI_BUNDLECONTEXT, _bundle.getBundleContext());

      String overrideBundleInstallLocation =
          (String) _properties.get(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE);
      File bundleInstallLocation =
          (overrideBundleInstallLocation == null
              ? BundleFileLocatorHelperFactory.getFactory()
                  .getHelper()
                  .getBundleInstallLocation(_bundle)
              : new File(overrideBundleInstallLocation));
      URL url = null;
      Resource rootResource =
          Resource.newResource(
              BundleFileLocatorHelperFactory.getFactory()
                  .getHelper()
                  .getLocalURL(bundleInstallLocation.toURI().toURL()));
      // try and make sure the rootResource is useable - if its a jar then make it a jar file url
      if (rootResource.exists()
          && !rootResource.isDirectory()
          && !rootResource.toString().startsWith("jar:")) {
        Resource jarResource = JarResource.newJarResource(rootResource);
        if (jarResource.exists() && jarResource.isDirectory()) rootResource = jarResource;
      }

      // if the path wasn't set or it was ., then it is the root of the bundle's installed location
      if (_webAppPath == null || _webAppPath.length() == 0 || ".".equals(_webAppPath)) {
        url = bundleInstallLocation.toURI().toURL();
      } else {
        // Get the location of the root of the webapp inside the installed bundle
        if (_webAppPath.startsWith("/") || _webAppPath.startsWith("file:")) {
          url = new File(_webAppPath).toURI().toURL();
        } else if (bundleInstallLocation != null && bundleInstallLocation.isDirectory()) {
          url = new File(bundleInstallLocation, _webAppPath).toURI().toURL();
        } else if (bundleInstallLocation != null) {
          Enumeration<URL> urls =
              BundleFileLocatorHelperFactory.getFactory()
                  .getHelper()
                  .findEntries(_bundle, _webAppPath);
          if (urls != null && urls.hasMoreElements()) url = urls.nextElement();
        }
      }

      if (url == null) {
        throw new IllegalArgumentException(
            "Unable to locate "
                + _webAppPath
                + " in "
                + (bundleInstallLocation != null
                    ? bundleInstallLocation.getAbsolutePath()
                    : "unlocated bundle '" + _bundle.getSymbolicName() + "'"));
      }

      // Sets the location of the war file
      // converts bundleentry: protocol if necessary
      _webApp.setWar(
          BundleFileLocatorHelperFactory.getFactory().getHelper().getLocalURL(url).toString());

      // Set up what has been configured on the provider
      _webApp.setParentLoaderPriority(isParentLoaderPriority());
      _webApp.setExtractWAR(isExtract());
      if (getConfigurationClasses() != null)
        _webApp.setConfigurationClasses(getConfigurationClasses());
      else _webApp.setConfigurationClasses(__defaultConfigurations);

      if (getDefaultsDescriptor() != null) _webApp.setDefaultsDescriptor(getDefaultsDescriptor());

      // Set up configuration from manifest headers
      // extra classpath
      String tmp = (String) _properties.get(OSGiWebappConstants.JETTY_EXTRA_CLASSPATH);
      if (tmp != null) _webApp.setExtraClasspath(tmp);

      // web.xml
      tmp = (String) _properties.get(OSGiWebappConstants.JETTY_WEB_XML_PATH);
      if (tmp != null && tmp.trim().length() != 0) {
        File webXml = getFile(tmp, bundleInstallLocation);
        if (webXml != null && webXml.exists()) _webApp.setDescriptor(webXml.getAbsolutePath());
      }

      // webdefault.xml
      tmp = (String) _properties.get(OSGiWebappConstants.JETTY_DEFAULT_WEB_XML_PATH);
      if (tmp != null) {
        File defaultWebXml = getFile(tmp, bundleInstallLocation);
        if (defaultWebXml != null) {
          if (defaultWebXml.exists())
            _webApp.setDefaultsDescriptor(defaultWebXml.getAbsolutePath());
          else LOG.warn(defaultWebXml.getAbsolutePath() + " does not exist");
        }
      }

      // Handle Require-TldBundle
      // This is a comma separated list of names of bundles that contain tlds that this webapp uses.
      // We add them to the webapp classloader.
      String requireTldBundles = (String) _properties.get(OSGiWebappConstants.REQUIRE_TLD_BUNDLE);
      String pathsToTldBundles = getPathsToRequiredBundles(requireTldBundles);

      // make sure we provide access to all the jetty bundles by going
      // through this bundle.
      OSGiWebappClassLoader webAppLoader =
          new OSGiWebappClassLoader(
              _serverWrapper.getParentClassLoaderForWebapps(), _webApp, _bundle);

      if (pathsToTldBundles != null) webAppLoader.addClassPath(pathsToTldBundles);
      _webApp.setClassLoader(webAppLoader);

      // apply any META-INF/context.xml file that is found to configure
      // the webapp first
      applyMetaInfContextXml(rootResource);

      // pass the value of the require tld bundle so that the TagLibOSGiConfiguration
      // can pick it up.
      _webApp.setAttribute(OSGiWebappConstants.REQUIRE_TLD_BUNDLE, requireTldBundles);

      // Set up some attributes
      // rfc66
      _webApp.setAttribute(
          OSGiWebappConstants.RFC66_OSGI_BUNDLE_CONTEXT, _bundle.getBundleContext());

      // spring-dm-1.2.1 looks for the BundleContext as a different attribute.
      // not a spec... but if we want to support
      // org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext
      // then we need to do this to:
      _webApp.setAttribute(
          "org.springframework.osgi.web." + BundleContext.class.getName(),
          _bundle.getBundleContext());

      // also pass the bundle directly. sometimes a bundle does not have a
      // bundlecontext.
      // it is still useful to have access to the Bundle from the servlet
      // context.
      _webApp.setAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE, _bundle);
    }