@SuppressWarnings("unchecked")
 @Before
 public void setup() throws ClassNotFoundException, DependencyResolutionRequiredException {
   MockitoAnnotations.initMocks(this);
   when(project.getCompileClasspathElements()).thenReturn(Arrays.asList("foo", "bar"));
   when(project.getName()).thenReturn(PROJECT_NAME);
 }
  /**
   * DOCUMENT ME!
   *
   * @throws MojoExecutionException DOCUMENT ME!
   */
  public void execute() throws MojoExecutionException {
    MavenLogWrapper.setLog(getLog());

    LogFactory.getFactory()
        .setAttribute(
            "org.apache.commons.logging.Log", "net.sourceforge.floggy.maven.MavenLogWrapper");

    Weaver weaver = new Weaver();

    try {
      List list = project.getCompileClasspathElements();
      File temp =
          new File(project.getBuild().getDirectory(), String.valueOf(System.currentTimeMillis()));
      FileUtils.forceMkdir(temp);
      weaver.setOutputFile(temp);
      weaver.setInputFile(input);
      weaver.setClasspath((String[]) list.toArray(new String[list.size()]));

      if (configurationFile == null) {
        Configuration configuration = new Configuration();
        configuration.setAddDefaultConstructor(addDefaultConstructor);
        configuration.setGenerateSource(generateSource);
        weaver.setConfiguration(configuration);
      } else {
        weaver.setConfigurationFile(configurationFile);
      }

      weaver.execute();
      FileUtils.copyDirectory(temp, output);
      FileUtils.forceDelete(temp);
    } catch (Exception e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
  protected String[] buildClasspath() throws Exception {
    List paths = project.getCompileClasspathElements();

    paths.add(new File(classesPath).getAbsolutePath() + "/");

    return (String[]) paths.toArray(new String[0]);
  }
  protected List<File> createElements() {
    try {
      List<File> files = Lists.newArrayList();
      if (pom.getCompileClasspathElements() != null) {
        for (String classPathString : (List<String>) pom.getCompileClasspathElements()) {
          files.add(new File(classPathString));
        }
      }

      if (pom.getBuild().getOutputDirectory() != null) {
        File outputDirectoryFile = new File(pom.getBuild().getOutputDirectory());
        if (outputDirectoryFile.exists()) {
          files.add(outputDirectoryFile);
        }
      }
      return files;
    } catch (DependencyResolutionRequiredException e) {
      throw new SonarException("Fail to create the project classloader", e);
    }
  }
  private List<String> getClasspathForScope(
      ProjectBuildingResult projectBuildingResult, String scope)
      throws DependencyResolutionRequiredException {
    MavenProject project = projectBuildingResult.getProject();

    if ("compile".equalsIgnoreCase(scope)) {
      return project.getCompileClasspathElements();
    } else if ("runtime".equalsIgnoreCase(scope)) {
      return project.getRuntimeClasspathElements();
    }
    return project.getTestClasspathElements();
  }
Beispiel #6
0
  protected void generateDescriptor(String scope, File outputFile) throws MojoExecutionException {
    ExtractorConfiguration ec = new ExtractorConfiguration();

    try {
      if (scope.equals(COMPILE_SCOPE)) {
        ec.classpath = mavenProject.getCompileClasspathElements();
        ec.outputDirectory = new File(mavenProject.getBuild().getOutputDirectory());
        ec.sourceDirectories = mavenProject.getCompileSourceRoots();
      } else if (scope.equals(TEST_SCOPE)) {
        ec.classpath = mavenProject.getTestClasspathElements();
        ec.outputDirectory = new File(mavenProject.getBuild().getTestOutputDirectory());
        ec.sourceDirectories = mavenProject.getTestCompileSourceRoots();
      }

      metadataGenerator.generateDescriptor(ec, outputFile);
    } catch (Exception e) {
      throw new MojoExecutionException("Error generating metadata: ", e);
    }
  }
Beispiel #7
0
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("Copying javascript files from dependencies to this artifact");

    try {
      FilenameFilter skipClasses =
          new FilenameFilter() {
            public boolean accept(File dir, String name) {
              name = name.toLowerCase();
              return !name.endsWith(".class");
            }
          };

      @SuppressWarnings("unchecked")
      List<String> runtimeClasspathElements = project.getCompileClasspathElements();
      for (int i = 0; i < runtimeClasspathElements.size(); i++) {
        String element = runtimeClasspathElements.get(i);
        URL dep = new File(element).toURI().toURL();
        try {
          if (dep.getPath().endsWith(".jar")) { // TODO: is this enough !?
            Manifest manifest = new JarInputStream(dep.openStream()).getManifest();
            if (manifest != null) {
              String isStjsLibrary = manifest.getMainAttributes().getValue(STJS_LIBRARY_ENTRY);
              if ("true".equals(isStjsLibrary)) {
                // these are directories relative to the jar's root
                URL jsDirectoryURL = new URL("jar:" + dep + "!/");
                getLog().info("Copy directory:" + jsDirectoryURL);
                FileCopier.copyResourcesRecursively(
                    jsDirectoryURL, generatedSourcesDirectory, skipClasses);
              }
            }
          }
        } catch (IOException notfound) {
          // skip to the next
        }
      }
    } catch (Exception ex) {
      throw new MojoExecutionException("Cannot get builtProjectClassLoader:" + ex, ex);
    }
  }
  @SuppressWarnings({"unchecked"})
  public final void execute(final Callback callback)
      throws MojoExecutionException, MojoFailureException {
    if (!skip) {
      if (header == null) {
        warn("No header file specified to check for license");
        return;
      }
      if (!strictCheck) {
        warn(
            "Property 'strictCheck' is not enabled. Please consider adding <strictCheck>true</strictCheck> in your pom.xml file.");
        warn("See http://mycila.github.io/license-maven-plugin for more information.");
      }

      finder = new ResourceFinder(basedir);
      try {
        finder.setCompileClassPath(project.getCompileClasspathElements());
      } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
      }
      finder.setPluginClassPath(getClass().getClassLoader());

      final Header h = new Header(finder.findResource(this.header), encoding, headerSections);
      debug("Header %s:\n%s", h.getLocation(), h);

      if (this.validHeaders == null) {
        this.validHeaders = new String[0];
      }
      final List<Header> validHeaders = new ArrayList<Header>(this.validHeaders.length);
      for (String validHeader : this.validHeaders) {
        validHeaders.add(new Header(finder.findResource(validHeader), encoding, headerSections));
      }

      final List<PropertiesProvider> propertiesProviders = new LinkedList<PropertiesProvider>();
      for (PropertiesProvider provider :
          ServiceLoader.load(
              PropertiesProvider.class, Thread.currentThread().getContextClassLoader())) {
        propertiesProviders.add(provider);
      }
      final DocumentPropertiesLoader propertiesLoader =
          new DocumentPropertiesLoader() {
            @Override
            public Properties load(Document document) {
              Properties props = new Properties();

              for (Map.Entry<String, String> entry : mergeProperties(document).entrySet()) {
                if (entry.getValue() != null) {
                  props.setProperty(entry.getKey(), entry.getValue());
                } else {
                  props.remove(entry.getKey());
                }
              }
              for (PropertiesProvider provider : propertiesProviders) {
                try {
                  final Map<String, String> providerProperties =
                      provider.getAdditionalProperties(AbstractLicenseMojo.this, props, document);
                  if (getLog().isDebugEnabled()) {
                    getLog()
                        .debug(
                            "provider: "
                                + provider.getClass()
                                + " brought new properties\n"
                                + providerProperties);
                  }
                  for (Map.Entry<String, String> entry : providerProperties.entrySet()) {
                    if (entry.getValue() != null) {
                      props.setProperty(entry.getKey(), entry.getValue());
                    } else {
                      props.remove(entry.getKey());
                    }
                  }
                } catch (Exception e) {
                  getLog().warn("failure occured while calling " + provider.getClass(), e);
                }
              }
              return props;
            }
          };

      final DocumentFactory documentFactory =
          new DocumentFactory(
              basedir,
              buildMapping(),
              buildHeaderDefinitions(),
              encoding,
              keywords,
              propertiesLoader);

      int nThreads = (int) (Runtime.getRuntime().availableProcessors() * concurrencyFactor);
      ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
      CompletionService completionService = new ExecutorCompletionService(executorService);
      int count = 0;
      debug("Number of execution threads: %s", nThreads);

      try {
        for (final String file : listSelectedFiles()) {
          completionService.submit(
              new Runnable() {
                @Override
                public void run() {
                  Document document = documentFactory.createDocuments(file);
                  debug(
                      "Selected file: %s [header style: %s]",
                      document.getFilePath(), document.getHeaderDefinition());
                  if (document.isNotSupported()) {
                    callback.onUnknownFile(document, h);
                  } else if (document.is(h)) {
                    debug("Skipping header file: %s", document.getFilePath());
                  } else if (document.hasHeader(h, strictCheck)) {
                    callback.onExistingHeader(document, h);
                  } else {
                    boolean headerFound = false;
                    for (Header validHeader : validHeaders) {
                      if (headerFound = document.hasHeader(validHeader, strictCheck)) {
                        callback.onExistingHeader(document, h);
                        break;
                      }
                    }
                    if (!headerFound) {
                      callback.onHeaderNotFound(document, h);
                    }
                  }
                }
              },
              null);
          count++;
        }

        while (count-- > 0) {
          try {
            completionService.take().get();
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof Error) {
              throw (Error) cause;
            }
            if (cause instanceof MojoExecutionException) {
              throw (MojoExecutionException) cause;
            }
            if (cause instanceof MojoFailureException) {
              throw (MojoFailureException) cause;
            }
            if (cause instanceof RuntimeException) {
              throw (RuntimeException) cause;
            }
            throw new RuntimeException(cause.getMessage(), cause);
          }
        }

      } finally {
        executorService.shutdownNow();
      }
    }
  }
 @Override
 public List<String> getClasspathElements(final MavenProject project)
     throws DependencyResolutionRequiredException {
   return project.getCompileClasspathElements();
 }