/**
   * Scan the given resource to receive a full files list to work on. It should consist only of the
   * files explicitly (or implicitly) included and excluded via plugin configuration. See {@link
   * Resource} for details. Additionally, this method will filters resulted target file names via
   * provided RegExp filter.
   *
   * @param resource a {@link Resource} entry to scan
   * @return list of files with source and target info
   */
  public final Map<File, File> getFileList(
      final Resource resource, final boolean excludeDefaults, final FileRenameRegexp fRenameRegxp) {
    final Map<File, File> workingFiles = new HashMap<File, File>();

    final DirectoryScanner dirScanner = new DirectoryScanner();
    dirScanner.setBasedir(resource.getDirectory());

    if (resource.getIncludes().size() > 0) {
      dirScanner.setIncludes(
          resource.getIncludes().toArray(new String[resource.getIncludes().size()]));
    }
    if (resource.getExcludes().size() > 0) {
      if (excludeDefaults) {
        final String[] resourceExcludes =
            resource.getExcludes().toArray(new String[resource.getExcludes().size()]);
        final String[] excludes = ArrayUtils.addAll(resourceExcludes, getDefaultExcludes());
        dirScanner.setExcludes(excludes);
      } else {
        dirScanner.setExcludes(
            resource.getExcludes().toArray(new String[resource.getExcludes().size()]));
      }
    } else {
      if (excludeDefaults) {
        dirScanner.setExcludes(getDefaultExcludes());
      }
    }

    dirScanner.addDefaultExcludes();
    dirScanner.scan();

    final String[] includedFiles = dirScanner.getIncludedFiles();
    for (final String file : includedFiles) {
      if (logger.isDebugEnabled()) {
        logger.debug("-- adding file: " + file);
      }

      String outputFileName;
      if (fRenameRegxp != null) {
        outputFileName =
            file.replaceAll(
                fRenameRegxp.getPattern(),
                fRenameRegxp.getReplace() != null ? fRenameRegxp.getReplace() : "");
      } else {
        outputFileName = file;
      }

      if (resource.getTargetPath() != null || resource.getTargetPath().length() == 0) { // NOPMD
        workingFiles.put(
            new File(resource.getDirectory() + "/" + file),
            new File(resource.getTargetPath() + "/" + outputFileName)); // NOPMD
      } else {
        workingFiles.put(
            new File(resource.getDirectory() + "/" + file),
            new File(resource.getDirectory() + "/" + outputFileName)); // NOPMD
      }
    }

    return workingFiles;
  }
Example #2
0
  /**
   * Copies all found resource files, including test resources to the <code>targetFolder</code>.
   *
   * <p>Resource files to be copied are filtered or included according to the configurations inside
   * <code>project</code>'s pom.xml file.
   *
   * @param project project whose resource files to be copied
   * @param targetFolder matching resource files are stored in this directory
   */
  public static void copyResourcesTo(MavenProject project, String targetFolder) {
    File targetFolderFile = new File(targetFolder);
    String includes;
    String excludes;
    List allResources = project.getResources();
    allResources.addAll(project.getTestResources());
    LOG.info("Copying resource files to runner.jar");

    for (Object res : allResources) {
      if (!(res instanceof Resource)) {
        continue;
      }
      try {
        Resource resource = (Resource) res;
        File baseDir = new File(resource.getDirectory());
        includes =
            resource.getIncludes().toString().replace("[", "").replace("]", "").replace(" ", "");
        excludes =
            resource.getExcludes().toString().replace("[", "").replace("]", "").replace(" ", "");
        List<String> resFiles = FileUtils.getFileNames(baseDir, includes, excludes, true, true);
        for (String resFile : resFiles) {
          File resourceFile = new File(resFile);
          LOG.info("Copying {} to {}", resourceFile.getName(), targetFolder);
          FileUtils.copyFileToDirectory(resourceFile, targetFolderFile);
        }
      } catch (IOException e) {
        LOG.warn("Error while trying to copy resource files", e);
      }
    }
  }
  /**
   * Returns a list of filenames that should be copied over to the destination directory.
   *
   * @param resource the resource to be scanned
   * @return the array of filenames, relative to the sourceDir
   */
  private String[] getWarFiles(Resource resource) {
    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(resource.getDirectory());
    if (resource.getIncludes() != null && !resource.getIncludes().isEmpty()) {
      scanner.setIncludes((String[]) resource.getIncludes().toArray(EMPTY_STRING_ARRAY));
    } else {
      scanner.setIncludes(DEFAULT_INCLUDES);
    }
    if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) {
      scanner.setExcludes((String[]) resource.getExcludes().toArray(EMPTY_STRING_ARRAY));
    }

    scanner.addDefaultExcludes();

    scanner.scan();

    return scanner.getIncludedFiles();
  }
Example #4
0
  @SuppressWarnings("unchecked")
  public void execute() throws MojoExecutionException, MojoFailureException {
    try {
      if (failOnWarning) {
        jswarn = true;
      }

      jsErrorReporter_ = new ErrorReporter4Mojo(getLog(), jswarn);
      beforeProcess();
      processDir(sourceDirectory, outputDirectory, null, null, true);

      for (Resource resource : resources) {
        File destRoot = outputDirectory;

        if (resource.getTargetPath() != null) {
          destRoot = new File(outputDirectory, resource.getTargetPath());
        }

        processDir(
            new File(resource.getDirectory()),
            destRoot,
            resource.getIncludes(),
            resource.getExcludes(),
            true);
      }

      processDir(warSourceDirectory, webappDirectory, null, null, false);
      afterProcess();
      getLog()
          .info(
              String.format(
                  "nb warnings: %d, nb errors: %d",
                  jsErrorReporter_.getWarningCnt(), jsErrorReporter_.getErrorCnt()));

      if (failOnWarning && (jsErrorReporter_.getWarningCnt() > 0)) {
        throw new MojoFailureException(
            "warnings on " + this.getClass().getSimpleName() + "=> failure ! (see log)");
      }
    } catch (RuntimeException exc) {
      throw exc;
    } catch (MojoFailureException exc) {
      throw exc;
    } catch (MojoExecutionException exc) {
      throw exc;
    } catch (Exception exc) {
      throw new MojoExecutionException("wrap: " + exc.getMessage(), exc);
    }
  }
Example #5
0
  public void execute() throws MojoExecutionException, MojoFailureException {
    String pkg = project.getPackaging();
    if (pkg != null && pkg.equals("pom")) return; // skip POM modules

    Generator g =
        new Generator(
            outputDirectory,
            new Reporter() {
              public void debug(String msg) {
                getLog().debug(msg);
              }
            });

    for (Resource res : (List<Resource>) project.getResources()) {
      File baseDir = new File(res.getDirectory());
      if (!baseDir.exists())
        continue; // this happens for example when POM inherits the default resource folder but no
                  // such folder exists.

      FileSet fs = new FileSet();
      fs.setDir(baseDir);
      for (String name : (List<String>) res.getIncludes()) fs.createInclude().setName(name);
      for (String name : (List<String>) res.getExcludes()) fs.createExclude().setName(name);

      for (String relPath : fs.getDirectoryScanner(new Project()).getIncludedFiles()) {
        File f = new File(baseDir, relPath);
        if (!f.getName().endsWith(".properties") || f.getName().contains("_")) continue;
        if (fileMask != null && !f.getName().equals(fileMask)) continue;

        try {
          g.generate(f, relPath);
        } catch (IOException e) {
          throw new MojoExecutionException("Failed to generate a class from " + f, e);
        }
      }
    }

    try {
      g.build();
    } catch (IOException e) {
      throw new MojoExecutionException("Failed to generate source files", e);
    }

    project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
  }
  @Override
  public void execute() throws MojoExecutionException {

    Path warExecFile = Paths.get(buildDirectory, finalName);
    try {
      Files.deleteIfExists(warExecFile);
      Files.createDirectories(warExecFile.getParent());

      try (OutputStream os = Files.newOutputStream(warExecFile);
          ArchiveOutputStream aos =
              new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR, os)) {

        // If project is a war project add the war to the project
        if ("war".equalsIgnoreCase(project.getPackaging())) {
          File projectArtifact = project.getArtifact().getFile();
          if (projectArtifact != null && Files.exists(projectArtifact.toPath())) {
            aos.putArchiveEntry(new JarArchiveEntry(projectArtifact.getName()));
            try (InputStream is = Files.newInputStream(projectArtifact.toPath())) {
              IOUtils.copy(is, aos);
            }
            aos.closeArchiveEntry();
          }
        }

        // Add extraWars into the jar
        if (extraWars != null) {
          for (Dependency extraWarDependency : extraWars) {
            ArtifactRequest request = new ArtifactRequest();
            request.setArtifact(
                new DefaultArtifact(
                    extraWarDependency.getGroupId(),
                    extraWarDependency.getArtifactId(),
                    extraWarDependency.getType(),
                    extraWarDependency.getVersion()));
            request.setRepositories(projectRepos);
            ArtifactResult result;
            try {
              result = repoSystem.resolveArtifact(repoSession, request);
            } catch (ArtifactResolutionException e) {
              throw new MojoExecutionException(e.getMessage(), e);
            }

            File extraWarFile = result.getArtifact().getFile();
            aos.putArchiveEntry(new JarArchiveEntry(extraWarFile.getName()));
            try (InputStream is = Files.newInputStream(extraWarFile.toPath())) {
              IOUtils.copy(is, aos);
            }
            aos.closeArchiveEntry();
          }
        }

        // Add extraResources into the jar. Folder /extra
        if (extraResources != null) {
          for (Resource extraResource : extraResources) {
            DirectoryScanner directoryScanner = new DirectoryScanner();
            directoryScanner.setBasedir(extraResource.getDirectory());

            directoryScanner.setExcludes(
                extraResource
                    .getExcludes()
                    .toArray(new String[extraResource.getExcludes().size()]));

            if (!extraResource.getIncludes().isEmpty()) {
              directoryScanner.setIncludes(
                  extraResource
                      .getIncludes()
                      .toArray(new String[extraResource.getIncludes().size()]));
            } else {
              // include everything by default
              directoryScanner.setIncludes(new String[] {"**"});
            }

            directoryScanner.scan();
            for (String includeFile : directoryScanner.getIncludedFiles()) {
              aos.putArchiveEntry(
                  new JarArchiveEntry(Runner.EXTRA_RESOURCES_DIR + "/" + includeFile));

              Path extraFile = Paths.get(extraResource.getDirectory(), includeFile);
              try (InputStream is = Files.newInputStream(extraFile)) {
                IOUtils.copy(is, aos);
              }
              aos.closeArchiveEntry();
            }
          }
        }

        Set<String> includeArtifacts = new HashSet<>();
        includeArtifacts.add("org.apache.tomcat:tomcat-jdbc");
        includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-core");
        includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-logging-juli");
        includeArtifacts.add("org.yaml:snakeyaml");
        includeArtifacts.add("com.beust:jcommander");

        if (includeJSPSupport) {
          includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-jasper");
          includeArtifacts.add("org.eclipse.jdt.core.compiler:ecj");
        }

        for (Artifact pluginArtifact : pluginArtifacts) {
          String artifactName = pluginArtifact.getGroupId() + ":" + pluginArtifact.getArtifactId();
          if (includeArtifacts.contains(artifactName)) {
            try (JarFile jarFile = new JarFile(pluginArtifact.getFile())) {
              extractJarToArchive(jarFile, aos);
            }
          }
        }

        if (extraDependencies != null) {
          for (Dependency dependency : extraDependencies) {

            ArtifactRequest request = new ArtifactRequest();
            request.setArtifact(
                new DefaultArtifact(
                    dependency.getGroupId(),
                    dependency.getArtifactId(),
                    dependency.getType(),
                    dependency.getVersion()));
            request.setRepositories(projectRepos);
            ArtifactResult result;
            try {
              result = repoSystem.resolveArtifact(repoSession, request);
            } catch (ArtifactResolutionException e) {
              throw new MojoExecutionException(e.getMessage(), e);
            }

            try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) {
              extractJarToArchive(jarFile, aos);
            }
          }
        }

        if (includeJSPSupport) {
          addFile(aos, "/conf/web.xml", "conf/web.xml");
        } else {
          addFile(aos, "/conf/web_wo_jsp.xml", "conf/web.xml");
        }
        addFile(aos, "/conf/logging.properties", "conf/logging.properties");

        if (includeTcNativeWin32 != null) {
          aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.32"));
          Files.copy(Paths.get(includeTcNativeWin32), aos);
          aos.closeArchiveEntry();
        }

        if (includeTcNativeWin64 != null) {
          aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.64"));
          Files.copy(Paths.get(includeTcNativeWin64), aos);
          aos.closeArchiveEntry();
        }

        String[] runnerClasses = {
          "ch.rasc.embeddedtc.runner.CheckConfig$CheckConfigOptions",
          "ch.rasc.embeddedtc.runner.CheckConfig",
          "ch.rasc.embeddedtc.runner.Config",
          "ch.rasc.embeddedtc.runner.Shutdown",
          "ch.rasc.embeddedtc.runner.Context",
          "ch.rasc.embeddedtc.runner.DeleteDirectory",
          "ch.rasc.embeddedtc.runner.ObfuscateUtil$ObfuscateOptions",
          "ch.rasc.embeddedtc.runner.ObfuscateUtil",
          "ch.rasc.embeddedtc.runner.Runner$1",
          "ch.rasc.embeddedtc.runner.Runner$2",
          "ch.rasc.embeddedtc.runner.Runner$StartOptions",
          "ch.rasc.embeddedtc.runner.Runner$StopOptions",
          "ch.rasc.embeddedtc.runner.Runner$RunnerShutdownHook",
          "ch.rasc.embeddedtc.runner.Runner"
        };

        for (String rc : runnerClasses) {
          String classAsPath = rc.replace('.', '/') + ".class";

          try (InputStream is = getClass().getResourceAsStream("/" + classAsPath)) {
            aos.putArchiveEntry(new JarArchiveEntry(classAsPath));
            IOUtils.copy(is, aos);
            aos.closeArchiveEntry();
          }
        }

        Manifest manifest = new Manifest();

        Manifest.Attribute mainClassAtt = new Manifest.Attribute();
        mainClassAtt.setName("Main-Class");
        mainClassAtt.setValue(Runner.class.getName());
        manifest.addConfiguredAttribute(mainClassAtt);

        aos.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
        manifest.write(aos);
        aos.closeArchiveEntry();

        aos.putArchiveEntry(new JarArchiveEntry(Runner.TIMESTAMP_FILENAME));
        aos.write(String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8));
        aos.closeArchiveEntry();
      }
    } catch (IOException | ArchiveException | ManifestException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }