public List<File> initScanFiles() {
    List<File> scanList = new ArrayList<File>();

    if (getDescriptor() != null) {
      try {
        Resource r = Resource.newResource(getDescriptor());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new BuildException(e);
      }
    }

    if (getJettyEnvXml() != null) {
      try {
        Resource r = Resource.newResource(getJettyEnvXml());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new BuildException("Problem configuring scanner for jetty-env.xml", e);
      }
    }

    if (getDefaultsDescriptor() != null) {
      try {
        if (!AntWebAppContext.WEB_DEFAULTS_XML.equals(getDefaultsDescriptor())) {
          Resource r = Resource.newResource(getDefaultsDescriptor());
          scanList.add(r.getFile());
        }
      } catch (IOException e) {
        throw new BuildException("Problem configuring scanner for webdefaults.xml", e);
      }
    }

    if (getOverrideDescriptor() != null) {
      try {
        Resource r = Resource.newResource(getOverrideDescriptor());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new BuildException("Problem configuring scanner for webdefaults.xml", e);
      }
    }

    // add any extra classpath and libs
    List<File> cpFiles = getClassPathFiles();
    if (cpFiles != null) scanList.addAll(cpFiles);

    // any extra scan targets
    @SuppressWarnings("unchecked")
    List<File> scanFiles = (List<File>) getScanTargetFiles();
    if (scanFiles != null) scanList.addAll(scanFiles);

    return scanList;
  }
  /* ------------------------------------------------------------ */
  protected ByteBuffer getDirectBuffer(Resource resource) {
    // Only use file mapped buffers for cached resources, otherwise too much virtual memory
    // commitment for
    // a non shared resource.  Also ignore max buffer size
    try {
      if (_useFileMappedBuffer
          && resource.getFile() != null
          && resource.length() < Integer.MAX_VALUE)
        return BufferUtil.toMappedBuffer(resource.getFile());

      return BufferUtil.toBuffer(resource, true);
    } catch (IOException | IllegalArgumentException e) {
      LOG.warn(e);
      return null;
    }
  }
Example #3
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());
 }
Example #4
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;
 }
Example #5
0
  /* ------------------------------------------------------------ */
  protected Buffer getDirectBuffer(Resource resource) {
    try {
      if (_useFileMappedBuffer && resource.getFile() != null)
        return new DirectNIOBuffer(resource.getFile());

      int len = (int) resource.length();
      if (len < 0) {
        LOG.warn("invalid resource: " + String.valueOf(resource) + " " + len);
        return null;
      }
      Buffer buffer = new DirectNIOBuffer(len);
      InputStream is = resource.getInputStream();
      buffer.readFrom(is, len);
      is.close();
      return buffer;
    } catch (IOException e) {
      LOG.warn(e);
      return null;
    }
  }
Example #6
0
  /**
   * 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;
    }
  }
  public AttributeNormalizer(Resource baseResource) {
    try {
      // Track path attributes for expansion
      attributes.add(
          new PathAttribute("WAR", baseResource == null ? null : baseResource.getFile().toPath())
              .weight(10));
      attributes.add(new PathAttribute("jetty.base", "jetty.base").weight(9));
      attributes.add(new PathAttribute("jetty.home", "jetty.home").weight(8));
      attributes.add(new PathAttribute("user.home", "user.home").weight(7));
      attributes.add(new PathAttribute("user.dir", "user.dir").weight(6));

      Collections.sort(attributes, new PathAttributeComparator());
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
  }
Example #8
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());
  }
Example #9
0
  public Resource getResourceFromMavenOrSuper(String uriContext) throws IOException {

    String relativePath = null;

    if (uriContext.startsWith(URIUtil.SLASH)) {
      relativePath = uriContext.substring(1);
    } else {
      relativePath = uriContext;
    }

    /** maven generated resource directory not exists */
    if (mavenResourceTargetDirectory == null || !mavenResourceTargetDirectory.exists()) {
      return super.getResource(uriContext);
    }

    File targetFile = new File(mavenResourceTargetDirectory, relativePath);

    if (targetFile.exists()) { // get file from maven resource and ori resource

      String mavenResourcePath = targetFile.getAbsolutePath(); // maven generated resource file
      Resource oriResource = super.getResource(uriContext); // ori resource file
      File oriFile = oriResource.getFile();

      if (Utils.isBinary(oriFile) || !Utils.hasPlaceholder(oriFile)) { // ignore the binary file
        return oriResource;
      }

      if (FileUtils.contentEquals(targetFile, oriFile)) {
        return oriResource;
      } else {
        if (oriFile.lastModified() >= targetFile.lastModified()) {
          return oriResource;
        } else {
          if (logger.isDebugEnabled())
            logger.debug(uriContext + " maven replaced resource:" + mavenResourcePath);
          return Resource.newResource(mavenResourcePath);
        }
      }
    }
    return super.getResource(uriContext);
  }
    protected String getSystemClassPath(ClassLoader loader) throws Exception {
      StringBuilder classpath = new StringBuilder();
      while (loader != null) {
        if (loader instanceof URLClassLoader) {
          URL[] urls = ((URLClassLoader) loader).getURLs();
          if (urls != null) {
            for (int i = 0; i < urls.length; i++) {
              Resource resource = Resource.newResource(urls[i]);
              File file = resource.getFile();
              if (file != null && file.exists()) {
                if (classpath.length() > 0) classpath.append(File.pathSeparatorChar);
                classpath.append(file.getAbsolutePath());
              }
            }
          }
        } else if (loader instanceof AntClassLoader) {
          classpath.append(((AntClassLoader) loader).getClasspath());
        }

        loader = loader.getParent();
      }

      return classpath.toString();
    }
Example #11
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());
  }
  /**
   * 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);
      }
    }
  }
  /** @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#configureScanner() */
  public void configureScanner() throws MojoExecutionException {
    // start the scanner thread (if necessary) on the main webapp
    scanList = new ArrayList<File>();
    if (webApp.getDescriptor() != null) {
      try {
        Resource r = Resource.newResource(webApp.getDescriptor());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new MojoExecutionException("Problem configuring scanner for web.xml", e);
      }
    }

    if (webApp.getJettyEnvXml() != null) {
      try {
        Resource r = Resource.newResource(webApp.getJettyEnvXml());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new MojoExecutionException("Problem configuring scanner for jetty-env.xml", e);
      }
    }

    if (webApp.getDefaultsDescriptor() != null) {
      try {
        if (!WebAppContext.WEB_DEFAULTS_XML.equals(webApp.getDefaultsDescriptor())) {
          Resource r = Resource.newResource(webApp.getDefaultsDescriptor());
          scanList.add(r.getFile());
        }
      } catch (IOException e) {
        throw new MojoExecutionException("Problem configuring scanner for webdefaults.xml", e);
      }
    }

    if (webApp.getOverrideDescriptor() != null) {
      try {
        Resource r = Resource.newResource(webApp.getOverrideDescriptor());
        scanList.add(r.getFile());
      } catch (IOException e) {
        throw new MojoExecutionException("Problem configuring scanner for webdefaults.xml", e);
      }
    }

    File jettyWebXmlFile = findJettyWebXmlFile(new File(webAppSourceDirectory, "WEB-INF"));
    if (jettyWebXmlFile != null) scanList.add(jettyWebXmlFile);
    scanList.addAll(extraScanTargets);
    scanList.add(project.getFile());
    if (webApp.getTestClasses() != null) scanList.add(webApp.getTestClasses());
    if (webApp.getClasses() != null) scanList.add(webApp.getClasses());
    scanList.addAll(webApp.getWebInfLib());

    scannerListeners = new ArrayList<Scanner.BulkListener>();
    scannerListeners.add(
        new Scanner.BulkListener() {
          public void filesChanged(List changes) {
            try {
              boolean reconfigure = changes.contains(project.getFile().getCanonicalPath());
              restartWebApp(reconfigure);
            } catch (Exception e) {
              getLog()
                  .error("Error reconfiguring/restarting webapp after change in watched files", e);
            }
          }
        });
  }
Example #14
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);
    }
  }
Example #15
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;
  }