コード例 #1
0
  public void applyHandle(Boolean warDeployFlag) {
    if (StringUtils.isBlank(webDefault)) {
      webDefault = "org.eclipse.jetty.webapp.webdefault.xml";
    }

    // contexts handler
    ContextHandlerCollection contexthandler = new ContextHandlerCollection();

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(contextPath);
    webapp.setDefaultsDescriptor(webDefault);
    webapp.setTempDirectory(new File(warTmp));

    // webapp.setParentLoaderPriority(true);
    if (!warDeployFlag) {
      webapp.setResourceBase(resourceBase);
      webapp.setDescriptor(webXmlPath);
    } else {
      webapp.setWar(warPath);
    }

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase(resourceBase);

    contexthandler.setHandlers(
        new Handler[] {
          webapp, resource_handler, new DefaultHandler(), new StatisticsHandler(), new GzipHandler()
        });

    super.setHandler(contexthandler);
  }
コード例 #2
0
ファイル: MetricsServer.java プロジェクト: bigloupe/bigloupe
  /**
   * Start Jetty web server
   *
   * @param version of bigloupe-chart
   * @return
   * @throws Exception
   */
  private Server startWebServer(String version) throws Exception {
    if (!cmd.hasOption(OPTION_NO_WEBSERVER)) {

      applyOptionWithWebServer();

      Server server = new Server(getPortWebServer());

      WebAppContext root = new WebAppContext();
      root.setContextPath("/");

      if (cmd.hasOption(OPTION_WEBSERVER_WEBROOT)) {
        String webRoot = cmd.getOptionValue(OPTION_WEBSERVER_WEBROOT);
        Resource resource = FileResource.newResource(webRoot);
        root.setBaseResource(resource);

      } else {
        String webFiles = "bigloupe-chart-" + version + "-webapp.war";
        File fileWebApp = new File(webFiles);
        if (!fileWebApp.exists()) {
          if (version.equals("'undefined'")) {
            Resource resource = FileResource.newResource("src/main/webapp");
            root.setBaseResource(resource);
            root.setDefaultsDescriptor("./etc/webdefault.xml");
            logger.info(
                "Embedded webServer started with base resource "
                    + resource.getFile().getAbsolutePath());
          } else {
            logger.info(webFiles + " file not available");
            logger.info("Embedded webServer will be not started");
            return null;
          }
        } else {
          root.setWar(fileWebApp.getAbsolutePath());
        }
      }

      File tmp = new File("tmp");
      if (!tmp.exists()) tmp.mkdir();
      root.setTempDirectory(tmp);

      ContextHandlerCollection contexts = new ContextHandlerCollection();
      Handler handlerHawtIO = addWebApplicationHawtIO();
      if (handlerHawtIO != null) contexts.setHandlers(new Handler[] {root, handlerHawtIO});
      else contexts.setHandlers(new Handler[] {root});
      server.setHandler(contexts);

      server.start();
      addWebServerJMXSupport(server);
      return server;
    } else {
      applyOptionWithoutWebServer();
      return null;
    }
  }
コード例 #3
0
ファイル: JettyFactory.java プロジェクト: qljlld/aglieEAP
  /** 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录. */
  public static Server createServerInSource(int port, String contextPath) {
    Server server = new Server();
    // 设置在JVM退出时关闭Jetty的钩子。
    server.setStopAtShutdown(true);

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    // 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
    connector.setReuseAddress(false);
    server.setConnectors(new Connector[] {connector});

    WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, contextPath);
    // 修改webdefault.xml,解决Windows下Jetty Lock住静态文件的问题.
    webContext.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH);
    server.setHandler(webContext);

    return server;
  }
コード例 #4
0
 public EmbeddedWebServer(BimServer bimServer, boolean localDev) {
   server = new Server();
   //		Disabled 26-04-2015, I am pretty sure we don't use session anymore at all
   //		HashSessionIdManager hashSessionIdManager = new HashSessionIdManager(new Random()); //
   // Should be SecureRandom, but this makes startup slow on certain systems
   //		server.setSessionIdManager(hashSessionIdManager);
   ServerConnector socketConnector = new ServerConnector(server);
   socketConnector.setPort(bimServer.getConfig().getPort());
   server.addConnector(socketConnector);
   context = new WebAppContext(server, "", "/");
   context.setTempDirectory(bimServer.getHomeDir().resolve("jettytmp").toFile());
   if (localDev) {
     // TODO document why
     context.setDefaultsDescriptor("www/WEB-INF/webdefault.xml");
   }
   context.getServletContext().setAttribute("bimserver", bimServer);
   if (context.getResourceBase() == null) {
     context.setResourceBase("../BimServer/www");
   }
 }
コード例 #5
0
  public ServerMain(String configDir) throws Exception {

    config = Util.getConfig(configDir);
    // make sure we have all the correct dirs and files now
    ensureInstall();

    logger.info("Freeboard starting....");

    // do we have a USB drive connected?
    logger.info("USB drive " + Util.getUSBFile());

    // create a new Camel Main so we can easily start Camel
    Main main = new Main();

    // enable hangup support which mean we detect when the JVM terminates, and stop Camel graceful
    main.enableHangupSupport();

    NavDataWebSocketRoute route = new NavDataWebSocketRoute(config);
    // must do this early!
    CamelContextFactory.setContext(route);
    // web socket on port 9090
    logger.info("  Websocket port:" + config.getProperty(Constants.WEBSOCKET_PORT));
    route.setPort(Integer.valueOf(config.getProperty(Constants.WEBSOCKET_PORT)));

    // are we running demo?
    logger.info("  Serial url:" + config.getProperty(Constants.SERIAL_URL));
    route.setSerialUrl(config.getProperty(Constants.SERIAL_URL));

    // add our routes to Camel
    main.addRouteBuilder(route);

    Connector connector = new SelectChannelConnector();
    logger.info("  Webserver http port:" + config.getProperty(Constants.HTTP_PORT));
    connector.setPort(Integer.valueOf(config.getProperty(Constants.HTTP_PORT)));

    // virtual hosts
    String virtualHosts = config.getProperty(Constants.VIRTUAL_URL);
    server = new Server();
    server.addConnector(connector);

    // serve mapcache
    ServletContextHandler mapContext = new ServletContextHandler();
    logger.info("  Mapcache url:" + config.getProperty(Constants.MAPCACHE));
    mapContext.setContextPath(config.getProperty(Constants.MAPCACHE));
    logger.info("  Mapcache resource:" + config.getProperty(Constants.MAPCACHE_RESOURCE));
    mapContext.setResourceBase(config.getProperty(Constants.MAPCACHE_RESOURCE));
    ServletHolder mapHolder = mapContext.addServlet(DefaultServlet.class, "/*");
    mapHolder.setInitParameter("cacheControl", "max-age=3600,public");

    // serve tracks
    ServletContextHandler trackContext = new ServletContextHandler();
    logger.info("  Tracks url:" + config.getProperty(Constants.TRACKS));
    trackContext.setContextPath(config.getProperty(Constants.TRACKS));
    logger.info("  Tracks resource:" + config.getProperty(Constants.TRACKS_RESOURCE));
    trackContext.setResourceBase(config.getProperty(Constants.TRACKS_RESOURCE));
    trackContext.addServlet(DefaultServlet.class, "/*");

    if (StringUtils.isNotBlank(virtualHosts)) {
      mapContext.setVirtualHosts(virtualHosts.split(","));
      trackContext.setVirtualHosts(virtualHosts.split(","));
    }
    HandlerList handlers = new HandlerList();
    handlers.addHandler(mapContext);
    handlers.addHandler(trackContext);

    // serve freeboard
    WebAppContext wac = new WebAppContext();
    logger.info("  Freeboard resource:" + config.getProperty(Constants.FREEBOARD_RESOURCE));
    wac.setWar(config.getProperty(Constants.FREEBOARD_RESOURCE));
    wac.setDefaultsDescriptor(
        config.getProperty(Constants.FREEBOARD_RESOURCE) + "WEB-INF/webdefault.xml");

    wac.setDescriptor(config.getProperty(Constants.FREEBOARD_RESOURCE) + "WEB-INF/web.xml");
    logger.info("  Freeboard url:" + config.getProperty(Constants.FREEBOARD_URL));
    wac.setContextPath(config.getProperty(Constants.FREEBOARD_URL));
    wac.setServer(server);
    wac.setParentLoaderPriority(true);
    wac.setVirtualHosts(null);
    if (StringUtils.isNotBlank(virtualHosts)) {
      wac.setVirtualHosts(virtualHosts.split(","));
    }
    handlers.addHandler(wac);

    server.setHandler(handlers);
    server.start();

    // and run, which keeps blocking until we terminate the JVM (or stop CamelContext)
    main.run();

    // so now shutdown serial reader and server

    route.stopSerial();
    server.stop();
    System.exit(0);
  }
コード例 #6
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;
  }
コード例 #7
0
    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);
    }