private void addWebApp(String path, String warPath) throws Exception {
    if (handlerCollection != null) {
      //			boolean extractWar = warPath.endsWith(".war");
      //			boolean parentLoaderPriority = true;

      // add it to the server
      //			boolean restartHandler = handlerCollection.isRunning();
      //			if (restartHandler) {
      //				handlerCollection.stop();
      //			}

      logger.log(Level.INFO, "Adding web app: " + warPath + " to path " + path);

      // create a webapp
      WebAppContext wah = new WebAppContext(handlerCollection, warPath, path);

      // configure it
      //			wah.setExtractWAR(extractWar);
      //			wah.setParentLoaderPriority(parentLoaderPriority);

      wah.setClassLoader(ObjectUtility.class.getClassLoader()); // set MeemServer classloader

      handlerCollection.addHandler(wah);
      wah.start();

      //			if (restartHandler) {
      //				handlerCollection.start();
      //			}
    }
  }
  public EmbeddedJettyServer(int port, boolean useRestSession) throws Exception {
    server = new Server();
    connector = new SelectChannelConnector();
    connector.setPort(port);
    server.addConnector(connector);

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

    server.setHandler(root);
    server.start();
    while (!server.isStarted()) {
      Thread.sleep(100);
    }
  }
示例#3
0
  /** 快速重新启动application,重载target/classes与target/test-classes. */
  public static void reloadContext(Server server) throws Exception {
    WebAppContext context = (WebAppContext) server.getHandler();

    System.out.println("Application reloading");
    context.stop();

    WebAppClassLoader classLoader = new WebAppClassLoader(context);
    classLoader.addClassPath("target/classes");
    classLoader.addClassPath("target/test-classes");
    context.setClassLoader(classLoader);

    context.start();

    System.out.println("Application reloaded");
  }
示例#4
0
  private static WebAppContext buildContext() throws IOException {
    ProtectionDomain protectionDomain = Startup.class.getProtectionDomain();
    URL location = protectionDomain.getCodeSource().getLocation();

    WebAppContext context = new WebAppContext();
    WebAppClassLoader webAppClassLoader =
        new WebAppClassLoader(Startup.class.getClassLoader(), context);
    context.setClassLoader(webAppClassLoader);
    context.setContextPath(URIUtil.SLASH);
    context.setWar(location.toExternalForm());

    if (tempDir != null) {
      File tempDirectory = new File(tempDir);
      context.setTempDirectory(tempDirectory);
    }
    return context;
  }
  /**
   * Starts the web application. The web application root directory will be define in
   * target/jawr-integration-test, the directory used for the war generation.
   *
   * @throws Exception if an exception occurs
   */
  public void startWebApplication() throws Exception {

    // Create a new class loader to take in account the changes of the jawr
    // config file in the WEB-INF/classes
    WebAppClassLoader webAppClassLoader = new WebAppClassLoader(jettyWebAppContext);
    jettyWebAppContext.setClassLoader(webAppClassLoader);
    // Fix issue with web app context reloading on Windows where deleting temporary directory fails
    // because of locked files
    jettyWebAppContext.setPersistTempDirectory(true);

    if (server.isStopped()) {
      LOGGER.info("Start jetty server....");
      server.start();
    }
    if (jettyWebAppContext.isStopped()) {
      LOGGER.info("Start jetty webApp context....");
      jettyWebAppContext.start();
    }
  }
示例#6
0
  static WebAppContext newWebAppContext() throws MalformedURLException {
    final WebAppContext handler = new WebAppContext();
    handler.setContextPath("/");
    handler.setBaseResource(Resource.newClassPathResource("/tomcat_service"));
    handler.setClassLoader(
        new URLClassLoader(
            new URL[] {
              Resource.newClassPathResource("/tomcat_service/WEB-INF/lib/hello.jar")
                  .getURI()
                  .toURL()
            },
            JettyService.class.getClassLoader()));

    handler.addBean(new ServletContainerInitializersStarter(handler), true);
    handler.setAttribute(
        "org.eclipse.jetty.containerInitializers",
        Collections.singletonList(new ContainerInitializer(new JettyJasperInitializer(), null)));
    return handler;
  }
示例#7
0
  @Override
  protected Server createServer() {

    Server server =
        new Server(
            new Integer(ConfigContext.getCurrentContextConfig().getProperty("ksb.client2.port")));
    URL webRoot = getClass().getClassLoader().getResource(WEB_ROOT);
    String location = webRoot.getPath();

    LOG.debug("#####################################");
    LOG.debug("#");
    LOG.debug("#  Starting Client2 using web root " + location);
    LOG.debug("#");
    LOG.debug("#####################################");

    WebAppContext context = new WebAppContext(location, CONTEXT);
    context.setThrowUnavailableOnStartupException(true);
    context.setClassLoader(new KsbTestClientClassLoader());
    server.setHandler(context);
    return server;
  }
示例#8
0
文件: Jetty.java 项目: LiuQ1ang/jrds
  public void start(String args[]) {
    Logger.getRootLogger().setLevel(Level.ERROR);

    PropertiesManager pm = new PropertiesManager();
    File propFile = new File(propFileName);
    if (propFile.isFile()) pm.join(propFile);
    pm.importSystemProps();
    try {
      pm.update();
    } catch (IllegalArgumentException e) {
      System.err.println("invalid configuration, can't start: " + e.getMessage());
      System.exit(1);
    }

    if (pm.withjmx) {
      doJmx(pm);
    }

    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog");
    System.setProperty("org.eclipse.jetty.LEVEL", "DEBUG");

    final Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    if (host != null) {
      connector.setHost(host);
    }
    connector.setPort(port);

    // Let's try to start the connector before the application
    try {
      connector.open();
    } catch (IOException e) {
      connector.close();
      throw new RuntimeException("Jetty server failed to start", e);
    }
    server.setConnectors(new Connector[] {connector});

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setResourceBase(webRoot);
    webapp.setClassLoader(getClass().getClassLoader());
    webapp.setInitParameter("propertiesFile", propFileName);

    ResourceHandler staticFiles = new ResourceHandler();
    staticFiles.setWelcomeFiles(new String[] {"index.html"});
    staticFiles.setResourceBase(webRoot);

    if (pm.security) {
      LoginService loginService = new HashLoginService("jrds", pm.userfile);
      server.addBean(loginService);

      Authenticator auth = new BasicAuthenticator();
      Constraint constraint = new Constraint();
      constraint.setName("jrds");
      constraint.setRoles(new String[] {Constraint.ANY_ROLE});
      constraint.setAuthenticate(true);
      constraint.setDataConstraint(Constraint.DC_NONE);

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

      ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
      sh.setConstraintMappings(Collections.singletonList(cm));
      sh.setAuthenticator(auth);
      webapp.setSecurityHandler(sh);
    }

    HandlerCollection handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {staticFiles, webapp});
    server.setHandler(handlers);

    if (pm.withjmx || MBeanServerFactory.findMBeanServer(null).size() > 0) {
      MBeanServer mbs = java.lang.management.ManagementFactory.getPlatformMBeanServer();
      server.addBean(new MBeanContainer(mbs));
      handlers.addHandler(new StatisticsHandler());
    }

    // Properties are not needed any more
    pm = null;

    Thread finish =
        new Thread() {
          public void run() {
            try {
              server.stop();
            } catch (Exception e) {
              throw new RuntimeException("Jetty server failed to stop", e);
            }
          }
        };
    Runtime.getRuntime().addShutdownHook(finish);

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      throw new RuntimeException("Jetty server failed to start", e);
    }
  }
  @Test
  public void checkBasicAuthAccess() throws Throwable {
    final Server server = new Server();
    final SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(/* any */ 0);
    connector.setReuseAddress(false);
    connector.setSoLingerTime(0);
    server.addConnector(connector);

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

    final CountDownLatch latch = new CountDownLatch(1);

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

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

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

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

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

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

        assertThat(r.getDocuments()).hasSize(50);
      } finally {
        c.dispose();
      }
    } finally {
      server.stop();
    }
  }
    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);
    }