Exemplo n.º 1
0
  /**
   * Look for jars in WEB-INF/lib
   *
   * @param context
   * @return the list of jar resources found within context
   * @throws Exception
   */
  protected List<Resource> findJars(WebAppContext context) throws Exception {
    List<Resource> jarResources = new ArrayList<Resource>();

    Resource web_inf = context.getWebInf();
    if (web_inf == null || !web_inf.exists()) return null;

    Resource web_inf_lib = web_inf.addPath("/lib");

    if (web_inf_lib.exists() && web_inf_lib.isDirectory()) {
      String[] files = web_inf_lib.list();
      for (int f = 0; files != null && f < files.length; f++) {
        try {
          Resource file = web_inf_lib.addPath(files[f]);
          String fnlc = file.getName().toLowerCase(Locale.ENGLISH);
          int dot = fnlc.lastIndexOf('.');
          String extension = (dot < 0 ? null : fnlc.substring(dot));
          if (extension != null && (extension.equals(".jar") || extension.equals(".zip"))) {
            jarResources.add(file);
          }
        } catch (Exception ex) {
          LOG.warn(Log.EXCEPTION, ex);
        }
      }
    }
    return jarResources;
  }
  @Override
  public Resource getResource(String uriInContext) throws MalformedURLException {
    Resource resource = null;
    // Try to get regular resource
    resource = super.getResource(uriInContext);

    // If no regular resource exists check for access to /WEB-INF/lib or /WEB-INF/classes
    if ((resource == null || !resource.exists()) && uriInContext != null && _classes != null) {
      String uri = URIUtil.canonicalPath(uriInContext);
      if (uri == null) return null;

      try {
        // Replace /WEB-INF/classes with candidates for the classpath
        if (uri.startsWith(WEB_INF_CLASSES_PREFIX)) {
          if (uri.equalsIgnoreCase(WEB_INF_CLASSES_PREFIX)
              || uri.equalsIgnoreCase(WEB_INF_CLASSES_PREFIX + "/")) {
            // exact match for a WEB-INF/classes, so preferentially return the resource matching the
            // web-inf classes
            // rather than the test classes
            if (_classes != null) return Resource.newResource(_classes);
            else if (_testClasses != null) return Resource.newResource(_testClasses);
          } else {
            // try matching
            Resource res = null;
            int i = 0;
            while (res == null && (i < _webInfClasses.size())) {
              String newPath = uri.replace(WEB_INF_CLASSES_PREFIX, _webInfClasses.get(i).getPath());
              res = Resource.newResource(newPath);
              if (!res.exists()) {
                res = null;
                i++;
              }
            }
            return res;
          }
        } else if (uri.startsWith(WEB_INF_LIB_PREFIX)) {
          // Return the real jar file for all accesses to
          // /WEB-INF/lib/*.jar
          String jarName = uri.replace(WEB_INF_LIB_PREFIX, "");
          if (jarName.startsWith("/") || jarName.startsWith("\\")) jarName = jarName.substring(1);
          if (jarName.length() == 0) return null;
          File jarFile = _webInfJarMap.get(jarName);
          if (jarFile != null) return Resource.newResource(jarFile.getPath());

          return null;
        }
      } catch (MalformedURLException e) {
        throw e;
      } catch (IOException e) {
        LOG.ignore(e);
      }
    }
    return resource;
  }
Exemplo n.º 3
0
  @Override
  public Resource getResource(String uriInContext) throws MalformedURLException {
    Resource resource = null;
    // Try to get regular resource
    //        replacer.getAutoconfigTempDirectory().getAbsolutePath()
    try {
      resource = getAutoconfigResource(uriInContext);
      if (resource == null) {
        //                resource = super.getResource(uriInContext);
        resource = getResourceFromMavenOrSuper(uriInContext);
      }
    } catch (Exception e) {
      logger.warn("find autoconfig resource error! " + uriInContext, e);
    }
    // If no regular resource exists check for access to /WEB-INF/lib or /WEB-INF/classes
    if ((resource == null || !resource.exists()) && uriInContext != null && webInfClasses != null) {
      String uri = URIUtil.canonicalPath(uriInContext);

      try {
        // Replace /WEB-INF/classes with real classes directory
        if (uri.startsWith(WEB_INF_CLASSES_PREFIX)) {
          Resource res = null;
          int i = 0;
          while (res == null && (i < webInfClasses.size())) {
            String newPath = uri.replace(WEB_INF_CLASSES_PREFIX, webInfClasses.get(i).getPath());
            res = Resource.newResource(newPath);
            if (!res.exists()) {
              res = null;
              i++;
            }
          }
          return res;
        }
        // Return the real jar file for all accesses to
        // /WEB-INF/lib/*.jar
        else if (uri.startsWith(WEB_INF_LIB_PREFIX)) {
          String jarName = uri.replace(WEB_INF_LIB_PREFIX, "");
          if (jarName.startsWith("/") || jarName.startsWith("\\")) jarName = jarName.substring(1);
          if (jarName.length() == 0) return null;
          File jarFile = webInfJarMap.get(jarName);
          if (jarFile != null) return Resource.newResource(jarFile.getPath());

          return null;
        }
      } catch (MalformedURLException e) {
        throw e;
      } catch (IOException e) {
        Log.ignore(e);
      }
    }
    return resource;
  }
Exemplo n.º 4
0
  /* ------------------------------------------------------------ */
  private HttpContent load(String pathInContext, Resource resource) throws IOException {
    Content content = null;

    if (resource == null || !resource.exists()) return null;

    // Will it fit in the cache?
    if (!resource.isDirectory() && isCacheable(resource)) {
      // Create the Content (to increment the cache sizes before adding the content
      content = new Content(pathInContext, resource);

      // reduce the cache to an acceptable size.
      shrinkCache();

      // Add it to the cache.
      Content added = _cache.putIfAbsent(pathInContext, content);
      if (added != null) {
        content.invalidate();
        content = added;
      }

      return content;
    }

    return new HttpContent.ResourceAsHttpContent(
        resource,
        _mimeTypes.getMimeByExtension(resource.toString()),
        getMaxCachedFileSize(),
        _etags);
  }
Exemplo n.º 5
0
 /* ------------------------------------------------------------ */
 @Test
 public void testEncoding() throws Exception {
   Resource r = Resource.newResource("/tmp/a file with,spe#ials/");
   assertTrue(r.getURL().toString().indexOf("a%20file%20with,spe%23ials") > 0);
   assertTrue(r.getFile().toString().indexOf("a file with,spe#ials") > 0);
   r.delete();
   assertFalse("File should have been deleted.", r.exists());
 }
Exemplo n.º 6
0
 public File findWorkDirectory(WebAppContext context) throws IOException {
   if (context.getBaseResource() != null) {
     Resource web_inf = context.getWebInf();
     if (web_inf != null && web_inf.exists()) {
       return new File(web_inf.getFile(), "work");
     }
   }
   return null;
 }
Exemplo n.º 7
0
 /* ------------------------------------------------------------ */
 @Override
 public String toString() {
   return String.format(
       "%s %s %d %s %s",
       _resource,
       _resource.exists(),
       _resource.lastModified(),
       _contentType,
       _lastModifiedBytes);
 }
Exemplo n.º 8
0
  /** Test a class path resource for existence. */
  @Test
  public void testClassPathResourceClassAbsolute() {
    final String classPathName = "/org/eclipse/jetty/util/resource/Resource.class";

    Resource resource = Resource.newClassPathResource(classPathName);

    assertTrue(resource != null);

    // A class path cannot be a directory
    assertFalse("Class path cannot be a directory.", resource.isDirectory());

    // A class path must exist
    assertTrue("Class path resource does not exist.", resource.exists());
  }
Exemplo n.º 9
0
  /** Test a class path resource for existence. */
  @Test
  public void testClassPathResourceClassRelative() {
    final String classPathName = "Resource.class";

    Resource resource = Resource.newClassPathResource(classPathName);

    assertTrue(resource != null);

    // A class path cannot be a directory
    assertFalse("Class path cannot be a directory.", resource.isDirectory());

    // A class path must exist
    assertTrue("Class path resource does not exist.", resource.exists());
  }
Exemplo n.º 10
0
  @Override
  public void setWar(String path) {
    super.setWar(path);

    try {
      Resource war = Resource.newResource(path);
      if (war.exists() && war.isDirectory() && getDescriptor() == null) {
        Resource webXml = war.addPath("WEB-INF/web.xml");
        setDescriptor(webXml.toString());
      }
    } catch (IOException e) {
      throw new BuildException(e);
    }
  }
Exemplo n.º 11
0
  @Override
  public void configure(WebAppContext context) throws Exception {
    // cannot configure if the context is already started
    if (context.isStarted()) {
      if (LOG.isDebugEnabled())
        LOG.debug("Cannot configure webapp " + context + " after it is started");
      return;
    }

    Resource web_inf = context.getWebInf();

    // Add WEB-INF classes and lib classpaths
    if (web_inf != null
        && web_inf.isDirectory()
        && context.getClassLoader() instanceof WebAppClassLoader) {
      // Look for classes directory
      Resource classes = web_inf.addPath("classes/");
      if (classes.exists()) ((WebAppClassLoader) context.getClassLoader()).addClassPath(classes);

      // Look for jars
      Resource lib = web_inf.addPath("lib/");
      if (lib.exists() || lib.isDirectory())
        ((WebAppClassLoader) context.getClassLoader()).addJars(lib);
    }

    // Look for extra resource
    @SuppressWarnings("unchecked")
    List<Resource> resources = (List<Resource>) context.getAttribute(RESOURCE_URLS);
    if (resources != null) {
      Resource[] collection = new Resource[resources.size() + 1];
      int i = 0;
      collection[i++] = context.getBaseResource();
      for (Resource resource : resources) collection[i++] = resource;
      context.setBaseResource(new ResourceCollection(collection));
    }
  }
Exemplo n.º 12
0
  /** Test a class path resource for directories. */
  @Test
  public void testClassPathResourceDirectory() throws Exception {
    final String classPathName = "/";

    Resource resource = Resource.newClassPathResource(classPathName);

    assertTrue(resource != null);

    // A class path must be a directory
    assertTrue("Class path must be a directory.", resource.isDirectory());

    assertTrue("Class path returned file must be a directory.", resource.getFile().isDirectory());

    // A class path must exist
    assertTrue("Class path resource does not exist.", resource.exists());
  }
Exemplo n.º 13
0
    /* ------------------------------------------------------------ */
    Content(String pathInContext, Resource resource) {
      _key = pathInContext;
      _resource = resource;

      _contentType = _mimeTypes.getMimeByExtension(_resource.toString());
      boolean exists = resource.exists();
      _lastModified = exists ? resource.lastModified() : -1;
      _lastModifiedBytes =
          _lastModified < 0 ? null : new ByteArrayBuffer(HttpFields.formatDate(_lastModified));

      _length = exists ? (int) resource.length() : 0;
      _cachedSize.addAndGet(_length);
      _cachedFiles.incrementAndGet();
      _lastAccessed = System.currentTimeMillis();

      _etagBuffer = _etags ? new ByteArrayBuffer(resource.getWeakETag()) : null;
    }
Exemplo n.º 14
0
    public void addJars(Resource lib) throws IOException {
      if (lib == null || !lib.exists()) throw new IllegalStateException("No such lib: " + lib);

      String[] list = lib.list();
      if (list == null) return;

      for (String path : list) {
        if (".".equals(path) || "..".equals(path)) continue;

        try (Resource item = lib.addPath(path)) {
          if (item.isDirectory()) addJars(item);
          else {
            if (path.toLowerCase().endsWith(".jar") || path.toLowerCase().endsWith(".zip")) {
              URL url = item.getURL();
              _classpath.add(url);
            }
          }
        }
      }
    }
Exemplo n.º 15
0
  /**
   * Parse a resource
   *
   * @param r
   * @param resolver
   * @throws Exception
   */
  public void parse(Resource r, final ClassNameResolver resolver) throws Exception {
    if (r == null) return;

    if (r.exists() && r.isDirectory()) {
      parseDir(r, resolver);
      return;
    }

    String fullname = r.toString();
    if (fullname.endsWith(".jar")) {
      parseJar(r, resolver);
      return;
    }

    if (fullname.endsWith(".class")) {
      scanClass(r.getInputStream());
      return;
    }

    if (LOG.isDebugEnabled()) LOG.warn("Resource not scannable for classes: {}", r);
  }
    /* ------------------------------------------------------------ */
    CachedHttpContent(String pathInContext, Resource resource, CachedHttpContent gzipped) {
      _key = pathInContext;
      _resource = resource;

      String contentType = _mimeTypes.getMimeByExtension(_resource.toString());
      _contentType =
          contentType == null
              ? null
              : new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, contentType);
      _characterEncoding =
          _contentType == null ? null : MimeTypes.getCharsetFromContentType(contentType);
      _mimeType =
          _contentType == null
              ? null
              : MimeTypes.CACHE.get(MimeTypes.getContentTypeWithoutCharset(contentType));

      boolean exists = resource.exists();
      _lastModifiedValue = exists ? resource.lastModified() : -1L;
      _lastModified =
          _lastModifiedValue == -1
              ? null
              : new PreEncodedHttpField(
                  HttpHeader.LAST_MODIFIED, DateGenerator.formatDate(_lastModifiedValue));

      _contentLengthValue = exists ? (int) resource.length() : 0;
      _contentLength =
          new PreEncodedHttpField(HttpHeader.CONTENT_LENGTH, Long.toString(_contentLengthValue));

      if (_cachedFiles.incrementAndGet() > _maxCachedFiles) shrinkCache();

      _lastAccessed = System.currentTimeMillis();

      _etag =
          ResourceCache.this._etags
              ? new PreEncodedHttpField(HttpHeader.ETAG, resource.getWeakETag())
              : null;

      _gzipped = gzipped == null ? null : new CachedGzipHttpContent(this, gzipped);
    }
Exemplo n.º 17
0
  @Test
  public void testUncPathResourceFile() throws Exception {
    // This test is intended to run only on Windows platform
    assumeTrue(OS.IS_WINDOWS);

    String path = __userURL.toURI().getPath().replace('/', '\\') + "ResourceTest.java";
    System.err.println(path);

    Resource resource = Resource.newResource(path, false);
    System.err.println(resource);
    assertTrue(resource.exists());

    /*

    String uncPath = "\\\\127.0.0.1"+__userURL.toURI().getPath().replace('/','\\').replace(':','$')+"ResourceTest.java";
    System.err.println(uncPath);

    Resource uncResource = Resource.newResource(uncPath, false);
    System.err.println(uncResource);
    assertTrue(uncResource.exists());

    */
  }
Exemplo n.º 18
0
  /**
   * Parse all classes in a directory
   *
   * @param dir
   * @param resolver
   * @throws Exception
   */
  public void parseDir(Resource dir, ClassNameResolver resolver) throws Exception {
    // skip dirs whose name start with . (ie hidden)
    if (!dir.isDirectory() || !dir.exists() || dir.getName().startsWith(".")) return;

    if (LOG.isDebugEnabled()) {
      LOG.debug("Scanning dir {}", dir);
    }
    ;

    String[] files = dir.list();
    for (int f = 0; files != null && f < files.length; f++) {
      try {
        Resource res = dir.addPath(files[f]);
        if (res.isDirectory()) parseDir(res, resolver);
        else {
          // we've already verified the directories, so just verify the class file name
          String filename = res.getFile().getName();
          if (isValidClassFileName(filename)) {
            String name = res.getName();
            if ((resolver == null)
                || (!resolver.isExcluded(name)
                    && (!isParsed(name) || resolver.shouldOverride(name)))) {
              Resource r = Resource.newResource(res.getURL());
              if (LOG.isDebugEnabled()) {
                LOG.debug("Scanning class {}", r);
              }
              ;
              scanClass(r.getInputStream());
            }
          }
        }
      } catch (Exception ex) {
        LOG.warn(Log.EXCEPTION, ex);
      }
    }
  }
Exemplo n.º 19
0
  /** Test a class path resource for a file. */
  @Test
  public void testClassPathResourceFile() throws Exception {
    final String fileName = "resource.txt";
    final String classPathName = "/" + fileName;

    // Will locate a resource in the class path
    Resource resource = Resource.newClassPathResource(classPathName);

    assertTrue(resource != null);

    // A class path cannot be a directory
    assertFalse("Class path must be a directory.", resource.isDirectory());

    assertTrue(resource != null);

    File file = resource.getFile();

    assertTrue("File returned from class path should not be null.", file != null);
    assertEquals("File name from class path is not equal.", fileName, file.getName());
    assertTrue("File returned from class path should be a file.", file.isFile());

    // A class path must exist
    assertTrue("Class path resource does not exist.", resource.exists());
  }
    public void configureContextHandler() throws Exception {
      if (_configured) return;

      _configured = true;

      // Override for bundle root may have been set
      String bundleOverrideLocation =
          (String) _properties.get(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE);
      if (bundleOverrideLocation == null)
        bundleOverrideLocation =
            (String)
                _properties.get(OSGiWebappConstants.SERVICE_PROP_BUNDLE_INSTALL_LOCATION_OVERRIDE);

      // Location on filesystem of bundle or the bundle override location
      File bundleLocation =
          BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(_bundle);
      File root =
          (bundleOverrideLocation == null ? bundleLocation : new File(bundleOverrideLocation));
      Resource rootResource =
          Resource.newResource(
              BundleFileLocatorHelperFactory.getFactory()
                  .getHelper()
                  .getLocalURL(root.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;
      }

      // Set the base resource of the ContextHandler, if not already set, can also be overridden by
      // the context xml file
      if (_contextHandler != null && _contextHandler.getBaseResource() == null) {
        _contextHandler.setBaseResource(rootResource);
      }

      // Use a classloader that knows about the common jetty parent loader, and also the bundle
      OSGiClassLoader classLoader =
          new OSGiClassLoader(getServerInstanceWrapper().getParentClassLoaderForWebapps(), _bundle);

      // if there is a context file, find it and apply it
      if (_contextFile == null && _contextHandler == null)
        throw new IllegalStateException("No context file or ContextHandler");

      if (_contextFile != null) {
        // apply the contextFile, creating the ContextHandler, the DeploymentManager will register
        // it in the ContextHandlerCollection
        Resource res = null;

        // try to find the context file in the filesystem
        if (_contextFile.startsWith("/")) res = getFileAsResource(_contextFile);

        // try to find it relative to jetty home
        if (res == null) {
          // See if the specific server we are related to has jetty.home set
          String jettyHome =
              (String)
                  getServerInstanceWrapper()
                      .getServer()
                      .getAttribute(OSGiServerConstants.JETTY_HOME);
          if (jettyHome != null) res = getFileAsResource(jettyHome, _contextFile);

          // try to see if a SystemProperty for jetty.home is set
          if (res == null) {
            jettyHome = System.getProperty(OSGiServerConstants.JETTY_HOME);

            if (jettyHome != null) {
              if (jettyHome.startsWith("\"") || jettyHome.startsWith("'"))
                jettyHome = jettyHome.substring(1);
              if (jettyHome.endsWith("\"") || (jettyHome.endsWith("'")))
                jettyHome = jettyHome.substring(0, jettyHome.length() - 1);

              res = getFileAsResource(jettyHome, _contextFile);
              if (LOG.isDebugEnabled()) LOG.debug("jetty home context file:" + res);
            }
          }
        }

        // try to find it relative to an override location that has been specified
        if (res == null) {
          if (bundleOverrideLocation != null) {
            res =
                getFileAsResource(
                    Resource.newResource(bundleOverrideLocation).getFile(), _contextFile);
            if (LOG.isDebugEnabled()) LOG.debug("Bundle override location context file:" + res);
          }
        }

        // try to find it relative to the bundle in which it is being deployed
        if (res == null) {
          if (_contextFile.startsWith("./")) _contextFile = _contextFile.substring(1);

          if (!_contextFile.startsWith("/")) _contextFile = "/" + _contextFile;

          URL contextURL = _bundle.getEntry(_contextFile);
          if (contextURL != null) res = Resource.newResource(contextURL);
        }

        // apply the context xml file, either to an existing ContextHandler, or letting the
        // it create the ContextHandler as necessary
        if (res != null) {
          ClassLoader cl = Thread.currentThread().getContextClassLoader();

          LOG.debug("Context classloader = " + cl);
          try {
            Thread.currentThread().setContextClassLoader(classLoader);

            XmlConfiguration xmlConfiguration = new XmlConfiguration(res.getInputStream());
            HashMap properties = new HashMap();
            // put the server instance in
            properties.put("Server", getServerInstanceWrapper().getServer());
            // put in the location of the bundle root
            properties.put("bundle.root", rootResource.toString());

            // insert the bundle's location as a property.
            xmlConfiguration.getProperties().putAll(properties);

            if (_contextHandler == null)
              _contextHandler = (ContextHandler) xmlConfiguration.configure();
            else xmlConfiguration.configure(_contextHandler);
          } finally {
            Thread.currentThread().setContextClassLoader(cl);
          }
        }
      }

      // Set up the class loader we created
      _contextHandler.setClassLoader(classLoader);

      // If a bundle/service property specifies context path, let it override the context xml
      String contextPath = (String) _properties.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH);
      if (contextPath == null)
        contextPath = (String) _properties.get(OSGiWebappConstants.SERVICE_PROP_CONTEXT_PATH);
      if (contextPath != null) _contextHandler.setContextPath(contextPath);

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

      // make sure we protect also the osgi dirs specified by OSGi Enterprise spec
      String[] targets = _contextHandler.getProtectedTargets();
      int length = (targets == null ? 0 : targets.length);

      String[] updatedTargets = null;
      if (targets != null) {
        updatedTargets =
            new String[length + OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length];
        System.arraycopy(targets, 0, updatedTargets, 0, length);

      } else updatedTargets = new String[OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length];
      System.arraycopy(
          OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS,
          0,
          updatedTargets,
          length,
          OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length);
      _contextHandler.setProtectedTargets(updatedTargets);
    }
Exemplo n.º 21
0
  public static void main(String[] args) throws Exception {
    int timeout = (int) Duration.ONE_HOUR.getMilliseconds();

    Server server = new Server();
    SocketConnector connector = new SocketConnector();

    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(timeout);
    connector.setSoLingerTime(-1);
    connector.setPort(8080);
    server.addConnector(connector);

    Resource keystore = Resource.newClassPathResource("/keystore");
    if (keystore != null && keystore.exists()) {
      // if a keystore for a SSL certificate is available, start a SSL
      // connector on port 8443.
      // By default, the quickstart comes with a Apache Wicket Quickstart
      // Certificate that expires about half way september 2021. Do not
      // use this certificate anywhere important as the passwords are
      // available in the source.

      connector.setConfidentialPort(8443);

      SslContextFactory factory = new SslContextFactory();
      factory.setKeyStoreResource(keystore);
      factory.setKeyStorePassword("wicket");
      factory.setTrustStoreResource(keystore);
      factory.setKeyManagerPassword("wicket");
      SslSocketConnector sslConnector = new SslSocketConnector(factory);
      sslConnector.setMaxIdleTime(timeout);
      sslConnector.setPort(8443);
      sslConnector.setAcceptors(4);
      server.addConnector(sslConnector);

      System.out.println("SSL access to the quickstart has been enabled on port 8443");
      System.out.println("You can access the application using SSL on https://localhost:8443");
      System.out.println();
    }

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");
    bb.setWar("src/main/webapp");

    // START JMX SERVER
    // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    // server.getContainer().addEventListener(mBeanContainer);
    // mBeanContainer.start();

    server.setHandler(bb);

    try {
      System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
      server.start();
      System.in.read();
      System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
      server.stop();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Exemplo n.º 22
0
  public static void main(final String[] args) throws Exception {
    final int timeout = (int) Duration.ONE_HOUR.getMilliseconds();

    int port = 8080;
    final CommandLineParser parser = new BasicParser();
    final Options options = new Options();
    options.addOption("h", "help", false, "Prints usage information");
    options.addOption("p", "port", true, "Server port");
    options.addOption("v", "version", false, "Version");
    options.addOption("f", "file", true, "kMyMoney file path");
    // Parse the program arguments
    final CommandLine commandLine = parser.parse(options, args);
    boolean isBadArgs = false;
    String file = null;

    if (commandLine.hasOption('h')) {
      isBadArgs = true;
    }
    if (commandLine.hasOption('v')) {
      System.out.println("kMyMoneyScripter version 0.01");
      System.exit(0);
    }
    if (!commandLine.hasOption('f')) {
      isBadArgs = true;
    }
    if (commandLine.hasOption('p')) {
      try {
        System.out.println(commandLine.getOptionValue('p'));
        port = Integer.parseInt(commandLine.getOptionValue('p'));
      } catch (final Exception e) {
        isBadArgs = true;
        System.err.println("Not a proper port number:" + commandLine.getOptionValue('p'));
      }
    }
    if (commandLine.hasOption('f')) {
      file = commandLine.getOptionValue('f');
      if (file == null) {
        isBadArgs = true;
      } else {
        final File f = new File(file);
        if (f.exists() == false) {
          System.err.println("File " + file + " does not exist.");
          isBadArgs = true;
        }
      }
    }

    if (isBadArgs) {
      final HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("kMymoneyScripter", options);
      System.exit(1);
    }
    final Server server = new Server();
    final SocketConnector connector = new SocketConnector();

    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(timeout);
    connector.setSoLingerTime(-1);
    connector.setPort(port);
    server.addConnector(connector);

    // check if a keystore for a SSL certificate is available, and
    // if so, start a SSL connector on port 8443. By default, the
    // quickstart comes with a Apache Wicket Quickstart Certificate
    // that expires about half way september 2021. Do not use this
    // certificate anywhere important as the passwords are available
    // in the source.

    final Resource keystore = Resource.newClassPathResource("/keystore");
    if (keystore != null && keystore.exists()) {
      connector.setConfidentialPort(8443);

      final SslContextFactory factory = new SslContextFactory();
      factory.setKeyStoreResource(keystore);
      factory.setKeyStorePassword("wicket");
      factory.setTrustStore(keystore);
      factory.setKeyManagerPassword("wicket");
      final SslSocketConnector sslConnector = new SslSocketConnector(factory);
      sslConnector.setMaxIdleTime(timeout);
      sslConnector.setPort(8443);
      sslConnector.setAcceptors(4);
      server.addConnector(sslConnector);

      System.out.println("SSL access to the quickstart has been enabled on port 8443");
      System.out.println("You can access the application using SSL on https://localhost:8443");
      System.out.println();
    }

    final WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");

    new WicketFilter();
    final FilterHolder filterHolder = new FilterHolder(WicketFilter.class);
    filterHolder.setInitParameter(
        ContextParamWebApplicationFactory.APP_CLASS_PARAM, WICKET_WEBAPP_CLASS_NAME);
    filterHolder.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, "/*");
    // filterHolder.setInitParameter(param, value)
    bb.addFilter(filterHolder, "/*", 1);

    bb.setWar(Start.class.getClassLoader().getResource("webapp").toExternalForm());
    // START JMX SERVER
    // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    // server.getContainer().addEventListener(mBeanContainer);
    // mBeanContainer.start();

    server.setHandler(bb);
    createDB(file);

    try {
      System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
      server.start();
      System.in.read();
      System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
      server.stop();
      server.join();
      WicketApplication.db.close();
    } catch (final Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
  /**
   * @param context
   * @param descriptor
   * @param node
   */
  public void visitContextParam(WebAppContext context, Descriptor descriptor, XmlParser.Node node)
      throws Exception {
    String name = node.getString("param-name", false, true);
    String value = node.getString("param-value", false, true);
    List<String> values = new ArrayList<>();

    // extract values
    switch (name) {
      case ServletContext.ORDERED_LIBS:
      case AnnotationConfiguration.CONTAINER_INITIALIZERS:
      case MetaInfConfiguration.METAINF_TLDS:
      case MetaInfConfiguration.METAINF_RESOURCES:
        context.removeAttribute(name);

        QuotedStringTokenizer tok = new QuotedStringTokenizer(value, ",");
        while (tok.hasMoreElements()) values.add(tok.nextToken().trim());

        break;

      default:
        values.add(value);
    }

    // handle values
    switch (name) {
      case ServletContext.ORDERED_LIBS:
        {
          List<Object> libs = new ArrayList<>();
          Object o = context.getAttribute(ServletContext.ORDERED_LIBS);
          if (o instanceof Collection<?>) libs.addAll((Collection<?>) o);
          libs.addAll(values);
          if (libs.size() > 0) context.setAttribute(ServletContext.ORDERED_LIBS, libs);

          break;
        }

      case AnnotationConfiguration.CONTAINER_INITIALIZERS:
        {
          for (String i : values)
            visitContainerInitializer(
                context,
                new ContainerInitializer(Thread.currentThread().getContextClassLoader(), i));
          break;
        }

      case MetaInfConfiguration.METAINF_TLDS:
        {
          List<Object> tlds = new ArrayList<>();
          String war = context.getBaseResource().getURI().toString();
          Object o = context.getAttribute(MetaInfConfiguration.METAINF_TLDS);
          if (o instanceof Collection<?>) tlds.addAll((Collection<?>) o);
          for (String i : values) {
            Resource r = Resource.newResource(i.replace("${WAR}/", war));
            if (r.exists()) tlds.add(r.getURL());
            else throw new IllegalArgumentException("TLD not found: " + r);
          }

          if (tlds.size() > 0) context.setAttribute(MetaInfConfiguration.METAINF_TLDS, tlds);
          break;
        }

      case MetaInfConfiguration.METAINF_RESOURCES:
        {
          String war = context.getBaseResource().getURI().toString();
          for (String i : values) {
            Resource r = Resource.newResource(i.replace("${WAR}/", war));
            if (r.exists()) visitMetaInfResource(context, r);
            else throw new IllegalArgumentException("Resource not found: " + r);
          }
          break;
        }

      default:
    }
  }
Exemplo n.º 24
0
  /** @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#configureWebApplication() */
  public void configureWebApplication() throws Exception {
    super.configureWebApplication();

    // Set up the location of the webapp.
    // There are 2 parts to this: setWar() and setBaseResource(). On standalone jetty,
    // the former could be the location of a packed war, while the latter is the location
    // after any unpacking. With this mojo, you are running an unpacked, unassembled webapp,
    // so the two locations should be equal.
    Resource webAppSourceDirectoryResource =
        Resource.newResource(webAppSourceDirectory.getCanonicalPath());
    if (webApp.getWar() == null) webApp.setWar(webAppSourceDirectoryResource.toString());

    if (webApp.getBaseResource() == null) webApp.setBaseResource(webAppSourceDirectoryResource);

    if (classesDirectory != null) webApp.setClasses(classesDirectory);
    if (useTestScope && (testClassesDirectory != null)) webApp.setTestClasses(testClassesDirectory);

    webApp.setWebInfLib(getDependencyFiles());

    // get copy of a list of war artifacts
    Set<Artifact> matchedWarArtifacts = new HashSet<Artifact>();

    // make sure each of the war artifacts is added to the scanner
    for (Artifact a : getWarArtifacts()) extraScanTargets.add(a.getFile());

    // process any overlays and the war type artifacts
    List<Overlay> overlays = new ArrayList<Overlay>();
    for (OverlayConfig config : warPluginInfo.getMavenWarOverlayConfigs()) {
      // overlays can be individually skipped
      if (config.isSkip()) continue;

      // an empty overlay refers to the current project - important for ordering
      if (config.isCurrentProject()) {
        Overlay overlay = new Overlay(config, null);
        overlays.add(overlay);
        continue;
      }

      // if a war matches an overlay config
      Artifact a = getArtifactForOverlay(config, getWarArtifacts());
      if (a != null) {
        matchedWarArtifacts.add(a);
        SelectiveJarResource r =
            new SelectiveJarResource(
                new URL("jar:" + Resource.toURL(a.getFile()).toString() + "!/"));
        r.setIncludes(config.getIncludes());
        r.setExcludes(config.getExcludes());
        Overlay overlay = new Overlay(config, r);
        overlays.add(overlay);
      }
    }

    // iterate over the left over war artifacts and unpack them (without include/exclude processing)
    // as necessary
    for (Artifact a : getWarArtifacts()) {
      if (!matchedWarArtifacts.contains(a)) {
        Overlay overlay =
            new Overlay(
                null,
                Resource.newResource(
                    new URL("jar:" + Resource.toURL(a.getFile()).toString() + "!/")));
        overlays.add(overlay);
      }
    }

    webApp.setOverlays(overlays);

    // if we have not already set web.xml location, need to set one up
    if (webApp.getDescriptor() == null) {
      // Has an explicit web.xml file been configured to use?
      if (webXml != null) {
        Resource r = Resource.newResource(webXml);
        if (r.exists() && !r.isDirectory()) {
          webApp.setDescriptor(r.toString());
        }
      }

      // Still don't have a web.xml file: try the resourceBase of the webapp, if it is set
      if (webApp.getDescriptor() == null && webApp.getBaseResource() != null) {
        Resource r = webApp.getBaseResource().addPath("WEB-INF/web.xml");
        if (r.exists() && !r.isDirectory()) {
          webApp.setDescriptor(r.toString());
        }
      }

      // Still don't have a web.xml file: finally try the configured static resource directory if
      // there is one
      if (webApp.getDescriptor() == null && (webAppSourceDirectory != null)) {
        File f = new File(new File(webAppSourceDirectory, "WEB-INF"), "web.xml");
        if (f.exists() && f.isFile()) {
          webApp.setDescriptor(f.getCanonicalPath());
        }
      }
    }
    getLog().info("web.xml file = " + webApp.getDescriptor());
    getLog().info("Webapp directory = " + webAppSourceDirectory.getCanonicalPath());
  }
Exemplo n.º 25
0
  public void unpack(WebAppContext context) throws IOException {
    Resource web_app = context.getBaseResource();
    _preUnpackBaseResource = context.getBaseResource();

    if (web_app == null) {
      String war = context.getWar();
      if (war != null && war.length() > 0) web_app = context.newResource(war);
      else web_app = context.getBaseResource();

      // Accept aliases for WAR files
      if (web_app.getAlias() != null) {
        LOG.debug(web_app + " anti-aliased to " + web_app.getAlias());
        web_app = context.newResource(web_app.getAlias());
      }

      if (LOG.isDebugEnabled())
        LOG.debug(
            "Try webapp="
                + web_app
                + ", exists="
                + web_app.exists()
                + ", directory="
                + web_app.isDirectory()
                + " file="
                + (web_app.getFile()));
      // Is the WAR usable directly?
      if (web_app.exists() && !web_app.isDirectory() && !web_app.toString().startsWith("jar:")) {
        // No - then lets see if it can be turned into a jar URL.
        Resource jarWebApp = JarResource.newJarResource(web_app);
        if (jarWebApp.exists() && jarWebApp.isDirectory()) web_app = jarWebApp;
      }

      // If we should extract or the URL is still not usable
      if (web_app.exists()
          && ((context.isCopyWebDir()
                  && web_app.getFile() != null
                  && web_app.getFile().isDirectory())
              || (context.isExtractWAR()
                  && web_app.getFile() != null
                  && !web_app.getFile().isDirectory())
              || (context.isExtractWAR() && web_app.getFile() == null)
              || !web_app.isDirectory())) {
        // Look for sibling directory.
        File extractedWebAppDir = null;

        if (war != null) {
          // look for a sibling like "foo/" to a "foo.war"
          File warfile = Resource.newResource(war).getFile();
          if (warfile != null && warfile.getName().toLowerCase(Locale.ENGLISH).endsWith(".war")) {
            File sibling =
                new File(
                    warfile.getParent(),
                    warfile.getName().substring(0, warfile.getName().length() - 4));
            if (sibling.exists() && sibling.isDirectory() && sibling.canWrite())
              extractedWebAppDir = sibling;
          }
        }

        if (extractedWebAppDir == null)
          // Then extract it if necessary to the temporary location
          extractedWebAppDir = new File(context.getTempDirectory(), "webapp");

        if (web_app.getFile() != null && web_app.getFile().isDirectory()) {
          // Copy directory
          LOG.info("Copy " + web_app + " to " + extractedWebAppDir);
          web_app.copyTo(extractedWebAppDir);
        } else {
          // Use a sentinel file that will exist only whilst the extraction is taking place.
          // This will help us detect interrupted extractions.
          File extractionLock = new File(context.getTempDirectory(), ".extract_lock");

          if (!extractedWebAppDir.exists()) {
            // it hasn't been extracted before so extract it
            extractionLock.createNewFile();
            extractedWebAppDir.mkdir();
            LOG.info("Extract " + web_app + " to " + extractedWebAppDir);
            Resource jar_web_app = JarResource.newJarResource(web_app);
            jar_web_app.copyTo(extractedWebAppDir);
            extractionLock.delete();
          } else {
            // only extract if the war file is newer, or a .extract_lock file is left behind meaning
            // a possible partial extraction
            if (web_app.lastModified() > extractedWebAppDir.lastModified()
                || extractionLock.exists()) {
              extractionLock.createNewFile();
              IO.delete(extractedWebAppDir);
              extractedWebAppDir.mkdir();
              LOG.info("Extract " + web_app + " to " + extractedWebAppDir);
              Resource jar_web_app = JarResource.newJarResource(web_app);
              jar_web_app.copyTo(extractedWebAppDir);
              extractionLock.delete();
            }
          }
        }
        web_app = Resource.newResource(extractedWebAppDir.getCanonicalPath());
      }

      // Now do we have something usable?
      if (!web_app.exists() || !web_app.isDirectory()) {
        LOG.warn("Web application not found " + war);
        throw new java.io.FileNotFoundException(war);
      }

      context.setBaseResource(web_app);

      if (LOG.isDebugEnabled()) LOG.debug("webapp=" + web_app);
    }

    // Do we need to extract WEB-INF/lib?
    if (context.isCopyWebInf() && !context.isCopyWebDir()) {
      Resource web_inf = web_app.addPath("WEB-INF/");

      File extractedWebInfDir = new File(context.getTempDirectory(), "webinf");
      if (extractedWebInfDir.exists()) IO.delete(extractedWebInfDir);
      extractedWebInfDir.mkdir();
      Resource web_inf_lib = web_inf.addPath("lib/");
      File webInfDir = new File(extractedWebInfDir, "WEB-INF");
      webInfDir.mkdir();

      if (web_inf_lib.exists()) {
        File webInfLibDir = new File(webInfDir, "lib");
        if (webInfLibDir.exists()) IO.delete(webInfLibDir);
        webInfLibDir.mkdir();

        LOG.info("Copying WEB-INF/lib " + web_inf_lib + " to " + webInfLibDir);
        web_inf_lib.copyTo(webInfLibDir);
      }

      Resource web_inf_classes = web_inf.addPath("classes/");
      if (web_inf_classes.exists()) {
        File webInfClassesDir = new File(webInfDir, "classes");
        if (webInfClassesDir.exists()) IO.delete(webInfClassesDir);
        webInfClassesDir.mkdir();
        LOG.info(
            "Copying WEB-INF/classes from "
                + web_inf_classes
                + " to "
                + webInfClassesDir.getAbsolutePath());
        web_inf_classes.copyTo(webInfClassesDir);
      }

      web_inf = Resource.newResource(extractedWebInfDir.getCanonicalPath());

      ResourceCollection rc = new ResourceCollection(web_inf, web_app);

      if (LOG.isDebugEnabled()) LOG.debug("context.resourcebase = " + rc);

      context.setBaseResource(rc);
    }
  }
  public JettyWebAppContext configureWebApplication(MavenProject project, Log log)
      throws Exception {
    JettyWebAppContext webAppConfig = new JettyWebAppContext();

    Plugin plugin = project.getPlugin("com.polopoly.jetty:jetty-maven-plugin");
    Xpp3Dom config = (Xpp3Dom) plugin.getConfiguration();
    applyPOMWebAppConfig(config, webAppConfig);

    if (webAppConfig.getContextPath() == null || webAppConfig.getContextPath().length() < 1) {
      webAppConfig.setContextPath("/" + project.getArtifactId());
    }

    final File baseDir = project.getBasedir();
    final File webAppSourceDirectory = new File(baseDir, "src/main/webapp");
    final File classesDirectory = new File(baseDir, "target/classes");

    Resource webAppSourceDirectoryResource =
        Resource.newResource(webAppSourceDirectory.getCanonicalPath());
    if (webAppConfig.getWar() == null) {
      webAppConfig.setWar(webAppSourceDirectoryResource.toString());
    }

    if (webAppConfig.getBaseResource() == null) {
      webAppConfig.setBaseResource(webAppSourceDirectoryResource);
    }

    webAppConfig.setWebInfClasses(
        new ArrayList<File>() {
          {
            add(classesDirectory);
          }
        });
    addDependencies(project, webAppConfig);

    // if we have not already set web.xml location, need to set one up
    if (webAppConfig.getDescriptor() == null) {
      // Still don't have a web.xml file: try the resourceBase of the webapp, if it is set
      if (webAppConfig.getDescriptor() == null && webAppConfig.getBaseResource() != null) {
        Resource r = webAppConfig.getBaseResource().addPath("WEB-INF/web.xml");
        if (r.exists() && !r.isDirectory()) {
          webAppConfig.setDescriptor(r.toString());
        }
      }

      // Still don't have a web.xml file: finally try the configured static resource directory if
      // there is one
      if (webAppConfig.getDescriptor() == null && (webAppSourceDirectory != null)) {
        File f = new File(new File(webAppSourceDirectory, "WEB-INF"), "web.xml");
        if (f.exists() && f.isFile()) {
          webAppConfig.setDescriptor(f.getCanonicalPath());
        }
      }
    }

    // Turn off some default settings in jetty
    URL overrideWebXMLUrl = this.getClass().getResource("/com/polopoly/web_override.xml");
    if (overrideWebXMLUrl != null) {
      webAppConfig.addOverrideDescriptor(overrideWebXMLUrl.toExternalForm());
    }

    return webAppConfig;
  }
Exemplo n.º 27
0
  /**
   * Main function, starts the jetty server.
   *
   * @param args
   */
  public static void main(String[] args) {
    System.setProperty("wicket.configuration", "development");

    Server server = new Server();

    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);

    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(8080);
    http.setIdleTimeout(1000 * 60 * 60);

    server.addConnector(http);

    Resource keystore = Resource.newClassPathResource("/keystore");
    if (keystore != null && keystore.exists()) {
      // if a keystore for a SSL certificate is available, start a SSL
      // connector on port 8443.
      // By default, the quickstart comes with a Apache Wicket Quickstart
      // Certificate that expires about half way september 2021. Do not
      // use this certificate anywhere important as the passwords are
      // available in the source.

      SslContextFactory sslContextFactory = new SslContextFactory();
      sslContextFactory.setKeyStoreResource(keystore);
      sslContextFactory.setKeyStorePassword("wicket");
      sslContextFactory.setKeyManagerPassword("wicket");

      HttpConfiguration https_config = new HttpConfiguration(http_config);
      https_config.addCustomizer(new SecureRequestCustomizer());

      ServerConnector https =
          new ServerConnector(
              server,
              new SslConnectionFactory(sslContextFactory, "http/1.1"),
              new HttpConnectionFactory(https_config));
      https.setPort(8443);
      https.setIdleTimeout(500000);

      server.addConnector(https);
      System.out.println("SSL access to the examples has been enabled on port 8443");
      System.out.println("You can access the application using SSL on https://localhost:8443");
      System.out.println();
    }

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");
    bb.setWar("src/main/webapp");

    // uncomment next line if you want to test with JSESSIONID encoded in the urls
    // ((AbstractSessionManager)
    // bb.getSessionHandler().getSessionManager()).setUsingCookies(false);

    server.setHandler(bb);

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    server.addEventListener(mBeanContainer);
    server.addBean(mBeanContainer);

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
Exemplo n.º 28
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;
  }
Exemplo n.º 29
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);
    }
  }
Exemplo n.º 30
0
 public void addPath(Resource path) {
   if (path == null || !path.exists()) throw new IllegalStateException("No such path: " + path);
   _classpath.add(path.getURL());
 }