org.apache.maven.artifact.DependencyResolutionRequiredException Java Examples

The following examples show how to use org.apache.maven.artifact.DependencyResolutionRequiredException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MainInstrumentMojo.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();

    File mainOutputFolder = new File(getProject().getBuild().getOutputDirectory());
    if (!mainOutputFolder.isDirectory()) {
        log.warn("Main folder doesn't exist -- nothing to instrument");
        return;
    }
    
    List<String> classpath;
    try {
        classpath = getProject().getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Dependency resolution problem", ex);
    }

    log.debug("Processing main output folder ... ");
    instrumentPath(log, classpath, mainOutputFolder);
}
 
Example #2
Source File: AntTaskUtils.java    From was-maven-plugin with Apache License 2.0 6 votes vote down vote up
private static Path getPathFromArtifacts(Collection<Artifact> artifacts, Project antProject)
    throws DependencyResolutionRequiredException {
  if (artifacts == null) {
    return new Path(antProject);
  }

  List<String> list = new ArrayList<String>(artifacts.size());
  for (Artifact a : artifacts) {
    File file = a.getFile();
    if (file == null) {
      throw new DependencyResolutionRequiredException(a);
    }
    list.add(file.getPath());
  }

  Path p = new Path(antProject);
  p.setPath(StringUtils.join(list.iterator(), File.pathSeparator));

  return p;
}
 
Example #3
Source File: GenerateConnectorInspectionsMojo.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private DataShape generateInspections(Connector connector, DataShape shape) throws IOException, DependencyResolutionRequiredException, ClassNotFoundException {
    if (DataShapeKinds.JAVA != shape.getKind() || StringUtils.isEmpty(shape.getType())) {
        return shape;
    }

    getLog().info("Generating inspections for connector: " + connector.getId().get() + ", and type: " + shape.getType());

    final List<String> elements = project.getRuntimeClasspathElements();
    final URL[] classpath = new URL[elements.size()];

    for (int i = 0; i < elements.size(); i++) {
        classpath[i] = new File(elements.get(i)).toURI().toURL();
    }

    return generateInspections(classpath, shape);
}
 
Example #4
Source File: MojoToReportOptionsConverterTest.java    From pitest with Apache License 2.0 6 votes vote down vote up
public void testParsesExcludedClasspathElements()
    throws DependencyResolutionRequiredException {
  final String sep = File.pathSeparator;

  final Set<Artifact> artifacts = new HashSet<>();
  final Artifact dependency = Mockito.mock(Artifact.class);
  when(dependency.getGroupId()).thenReturn("group");
  when(dependency.getArtifactId()).thenReturn("artifact");
  when(dependency.getFile()).thenReturn(
      new File("group" + sep + "artifact" + sep + "1.0.0" + sep
          + "group-artifact-1.0.0.jar"));
  artifacts.add(dependency);
  when(this.project.getArtifacts()).thenReturn(artifacts);
  when(this.project.getTestClasspathElements()).thenReturn(
      Arrays.asList("group" + sep + "artifact" + sep + "1.0.0" + sep
          + "group-artifact-1.0.0.jar"));

  final ReportOptions actual = parseConfig("<classpathDependencyExcludes>"
      + "										<param>group:artifact</param>"
      + "									</classpathDependencyExcludes>");
  assertFalse(actual.getClassPathElements().contains(
      "group" + sep + "artifact" + sep + "1.0.0" + sep
      + "group-artifact-1.0.0.jar"));
}
 
Example #5
Source File: Parse.java    From Java2PlantUML with Apache License 2.0 6 votes vote down vote up
/**
 * Send thePackage and a convenient fixed set of filters to Parser and outputs Parser's result
 *
 * Todo: allow filters to be set from CLI
 *
 * <code>
 * // A very permisive filter configuration:
 * getLog().info("Following is the PlantUML src: \n" + Parser.parse(
 *         thePackage, Filters.FILTER_ALLOW_ALL_RELATIONS, Filters.FILTER_ALLOW_ALL_CLASSES, loader,
 *         Filters.FILTER_RELATION_ALLOW_ALL));

 * </code>
 * @throws MojoExecutionException
 * @throws MojoFailureException
 */
@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException {
    filterParamsSanityCheck();
    prepareCustomFilters();
    try {
        URLClassLoader loader = getLoader();
        getLog().debug("loader URLs: " + Arrays.toString(loader.getURLs()));

        getLog().info("Following is the PlantUML src: \n" + Parser.parse(
                thePackage, FILTERS.get(this.relationTypeFilter), FILTERS.get(this.classesFilter),
                FILTERS.get(this.relationsFilter), loader));

    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Something went wrong", e);
    }
}
 
Example #6
Source File: EclipselinkStaticWeaveMojo.java    From eclipselink-maven-plugin with Apache License 2.0 6 votes vote down vote up
private File[] getClassPathFiles()
{
    final List<File> files = new ArrayList<>();
    List<?> classpathElements;
    try
    {
        classpathElements = project.getTestClasspathElements();
    }
    catch (DependencyResolutionRequiredException e)
    {
        throw new RuntimeException(e.getMessage(), e);
    }

    for (final Object o : classpathElements)
    {
        if (o != null)
        {
            final File file = new File(o.toString());
            if (file.canRead())
            {
                files.add(file);
            }
        }
    }
    return files.toArray(new File[0]);
}
 
Example #7
Source File: DefaultContractsGeneratorTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckConfig() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException,
    DependencyResolutionRequiredException {
  DefaultContractsGenerator defaultContractsGenerator = new DefaultContractsGenerator();
  Method method = defaultContractsGenerator.getClass().getDeclaredMethod("checkConfig", new Class[] {});
  method.setAccessible(true);

  defaultContractsGenerator.configure(null);
  assertThat(method.invoke(defaultContractsGenerator), is(false));

  Map<String, Object> config = new HashMap<>();
  config.put("classpathUrls", null);
  defaultContractsGenerator.configure(config);
  assertThat(method.invoke(defaultContractsGenerator), is(false));

  MavenProject project = new MavenProject();
  config.put("classpathUrls", project.getRuntimeClasspathElements());
  defaultContractsGenerator.configure(config);
  assertThat(method.invoke(defaultContractsGenerator), is(true));
}
 
Example #8
Source File: DefaultContractsGeneratorTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerate()
    throws DependencyResolutionRequiredException, IOException, TimeoutException, InterruptedException {

  File demoPath = this.resources.getBasedir(TEST_PROJECT);
  ClassMaker.compile(demoPath.getCanonicalPath());
  MavenProject project = mock(MavenProject.class);

  List<String> runtimeUrlPath = new ArrayList<>();
  runtimeUrlPath.add(demoPath + File.separator + "target/classes");

  Map<String, Object> config = new HashMap<>();
  given(project.getRuntimeClasspathElements()).willReturn(runtimeUrlPath);
  config.put("classpathUrls", project.getRuntimeClasspathElements());
  config.put("outputDir", "target");
  config.put("contractfileType", "yaml");

  DefaultContractsGenerator defaultContractsGenerator = new DefaultContractsGenerator();
  defaultContractsGenerator.configure(config);
  try {
    defaultContractsGenerator.generate();
  } catch (RuntimeException e) {
    fail("Run 'testGenerate' failed and unexpected to catch RuntimeException: " + e.getMessage());
  }
}
 
Example #9
Source File: GenerateUtil.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
public static void generateContract(MavenProject project, String contractOutput, String contractFileType,
    String type) {

  Map<String, Object> contractConfig = new HashMap<>();
  try {
    contractConfig.put("classpathUrls", project.getRuntimeClasspathElements());
  } catch (DependencyResolutionRequiredException e) {
    throw new RuntimeException("Failed to get runtime class elements", e);
  }
  contractConfig.put("outputDir", contractOutput);
  contractConfig.put("contractFileType", contractFileType);

  // TODO: support users to addParamCtx other getGenerator type soon
  ContractsGenerator contractGenerator = GeneratorFactory.getGenerator(ContractsGenerator.class, type);
  Objects.requireNonNull(contractGenerator).configure(contractConfig);

  contractGenerator.generate();
}
 
Example #10
Source File: GenerateUtilTest.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testGenerateContract() throws DependencyResolutionRequiredException {

  MavenProject project = mock(MavenProject.class);

  String contractOutput = "target/GenerateUtilTest/contract";
  when(project.getRuntimeClasspathElements()).thenThrow(DependencyResolutionRequiredException.class);
  try {
    generateContract(project, contractOutput, "yaml", "default");

    fail("Run 'testGenerateContract' failed, expected to occur RuntimeException but not");
  } catch (RuntimeException e) {
    assertEquals("Failed to get runtime class elements", e.getMessage());
  }
}
 
Example #11
Source File: RemoveMetricFiltersMojo.java    From lambda-monitoring with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    MetricFilterPublisher publisher =
            dryRun ? new DryRunMetricFilterPublisher(getLog()) : new CloudwatchMetricFilterPublisher(getLog());

    // Get a map of fully-namespaced metric names mapped to the metric fields in classes that extend LambdaMetricSet
    Map<String, Field> metricFields = new HashMap<>();
    try {
        metricFields.putAll(new MetricsFinder(project).find());
    } catch (DependencyResolutionRequiredException | MalformedURLException e) {
        throw new MojoExecutionException("Could not scan classpath for metric fields", e);
    }

    if (!metricFields.isEmpty()) {
        getLog().info(String.format("Found [%d] metric fields in classpath.", metricFields.size()));

        int removed = publisher.removeMetricFilters(getMetricFilters(metricFields));
        getLog().info(String.format("Removed [%d] metric filters.", removed));
    } else {
        getLog().warn("Did not find any metric fields in classpath.");
    }

}
 
Example #12
Source File: AbstractSarlBatchCompilerMojo.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the classpath for the test code.
 *
 * @return the current classpath.
 * @throws MojoExecutionException on failure.
 * @since 0.8
 * @see #getClassPath()
 */
protected List<File> getTestClassPath() throws MojoExecutionException {
	final Set<String> classPath = new LinkedHashSet<>();
	final MavenProject project = getProject();
	classPath.add(project.getBuild().getTestSourceDirectory());
	try {
		classPath.addAll(project.getTestClasspathElements());
	} catch (DependencyResolutionRequiredException e) {
		throw new MojoExecutionException(e.getLocalizedMessage(), e);
	}
	for (final Artifact dep : project.getArtifacts()) {
		classPath.add(dep.getFile().getAbsolutePath());
	}
	final List<File> files = new ArrayList<>();
	for (final String filename : classPath) {
		final File file = new File(filename);
		if (file.exists()) {
			files.add(file);
		} else {
			getLog().warn(MessageFormat.format(Messages.AbstractSarlBatchCompilerMojo_10, filename));
		}
	}
	return files;
}
 
Example #13
Source File: WatchMojo.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
protected WatchService.WatchContext getWatchContext() throws IOException, DependencyResolutionRequiredException {
    final ServiceHub hub = jkubeServiceHub.getDockerServiceHub();
    return WatchService.WatchContext.builder()
            .watchInterval(watchInterval)
            .watchMode(watchMode)
            .watchPostGoal(watchPostGoal)
            .watchPostExec(watchPostExec)
            .autoCreateCustomNetworks(autoCreateCustomNetworks)
            .keepContainer(keepContainer)
            .keepRunning(keepRunning)
            .removeVolumes(removeVolumes)
            .containerNamePattern(containerNamePattern)
            .buildTimestamp(getBuildTimestamp())
            .gavLabel(getGavLabel())
            .buildContext(initJKubeConfiguration())
            .follow(follow())
            .showLogs(showLogs())
            .serviceHubFactory(serviceHubFactory)
            .hub(hub)
            .dispatcher(getLogDispatcher(hub))
            .build();
}
 
Example #14
Source File: AbstractDocumentationMojo.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the current classpath.
 *
 * @return the current classpath.
 * @throws IOException on failure.
 */
protected List<File> getClassPath() throws IOException {
	final Set<String> classPath = new LinkedHashSet<>();
	final MavenProject curProj = this.session.getCurrentProject();
	classPath.add(curProj.getBuild().getSourceDirectory());
	try {
		classPath.addAll(curProj.getCompileClasspathElements());
	} catch (DependencyResolutionRequiredException e) {
		throw new IOException(e.getLocalizedMessage(), e);
	}
	for (final Artifact dep : curProj.getArtifacts()) {
		classPath.add(dep.getFile().getAbsolutePath());
	}
	classPath.remove(curProj.getBuild().getOutputDirectory());
	final List<File> files = new ArrayList<>();
	for (final String filename : classPath) {
		final File file = new File(filename);
		if (file.exists()) {
			files.add(file);
		}
	}
	return files;
}
 
Example #15
Source File: WatchMojo.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private WatcherContext getWatcherContext() throws MojoExecutionException {
    try {
        JKubeConfiguration buildContext = initJKubeConfiguration();
        WatchService.WatchContext watchContext = jkubeServiceHub.getDockerServiceHub() != null ? getWatchContext() : null;

        return WatcherContext.builder()
                .buildContext(buildContext)
                .watchContext(watchContext)
                .config(extractWatcherConfig())
                .logger(log)
                .newPodLogger(createLogger("[[C]][NEW][[C]] "))
                .oldPodLogger(createLogger("[[R]][OLD][[R]] "))
                .useProjectClasspath(useProjectClasspath)
                .jKubeServiceHub(jkubeServiceHub)
                .build();
    } catch (IOException exception) {
        throw new MojoExecutionException(exception.getMessage());
    } catch (DependencyResolutionRequiredException dependencyException) {
        throw new MojoExecutionException("Instructed to use project classpath, but cannot. Continuing build if we can: " + dependencyException.getMessage());
    }
}
 
Example #16
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Set<String> collectClasspaths(Project prj) throws DependencyResolutionRequiredException {
    Set<String> toRet = new HashSet<String>();
    NbMavenProject watcher = prj.getLookup().lookup(NbMavenProject.class);
    MavenProject mproject = watcher.getMavenProject();
    //TODO this ought to be really configurable based on what class gets debugged.
    toRet.addAll(mproject.getTestClasspathElements());
    //for poms also include all module projects recursively..
    boolean isPom = NbMavenProject.TYPE_POM.equals(watcher.getPackagingType());
    if (isPom) {
        ProjectContainerProvider subs = prj.getLookup().lookup(ProjectContainerProvider.class);
        ProjectContainerProvider.Result res = subs.getContainedProjects();
        for (Project pr : res.getProjects()) {
            toRet.addAll(collectClasspaths(pr));
        }
    }
    return toRet;
}
 
Example #17
Source File: JarMojo.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the archetype JAR file.
 *
 * @param archetypeDir the exploded archetype directory
 * @return created file
 * @throws MojoExecutionException if an error occurs
 */
private File generateArchetypeJar(Path archetypeDir) throws MojoExecutionException {
    File jarFile = new File(outputDirectory, finalName + ".jar");

    MavenArchiver archiver = new MavenArchiver();
    archiver.setCreatedBy("Helidon Archetype Plugin", "io.helidon.build-tools.archetype",
            "helidon-archetype-maven-plugin");
    archiver.setOutputFile(jarFile);
    archiver.setArchiver((JarArchiver) archivers.get("jar"));
    archiver.configureReproducible(outputTimestamp);

    try {
        archiver.getArchiver().addDirectory(archetypeDir.toFile());
        archiver.createArchive(session, project, archive);
    } catch (IOException | DependencyResolutionRequiredException | ArchiverException | ManifestException e) {
        throw new MojoExecutionException("Error assembling archetype jar " + jarFile, e);
    }
    return jarFile;
}
 
Example #18
Source File: TestInstrumentMojo.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();

    File testOutputFolder = new File(getProject().getBuild().getTestOutputDirectory());
    if (!testOutputFolder.isDirectory()) {
        log.warn("Test folder doesn't exist -- nothing to instrument");
        return;
    }
    
    List<String> classpath;
    try {
        classpath = getProject().getTestClasspathElements();
    } catch (DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Dependency resolution problem", ex);
    }
    
    log.debug("Processing test output folder ... ");
    instrumentPath(log, classpath, testOutputFolder);
}
 
Example #19
Source File: PackageMojo.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (siteArchiveSkip) {
        getLog().info("processing is skipped.");
        return;
    }
    getLog().info("Assembling site JAR [" + project.getArtifactId() + "]");

    final File jarFile = new File(siteArchiveOutputDirectory, siteArchiveFinalName + ".jar");
    final MavenArchiver mvnArchiver = new MavenArchiver();
    mvnArchiver.setArchiver(jarArchiver);
    mvnArchiver.setOutputFile(jarFile);
    mvnArchiver.getArchiver().addDirectory(siteOutputDirectory, getIncludes(), getExcludes());

    try {
        mvnArchiver.createArchive(session, project, new MavenArchiveConfiguration());
    } catch (ManifestException
            | IOException
            | DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Error assembling site archive", ex);
    }

    project.getArtifact().setFile(jarFile);
}
 
Example #20
Source File: SpringMvcEndpointGeneratorMojo.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private ClassRealm getClassRealm() throws DependencyResolutionRequiredException, MalformedURLException {
	if (classRealm == null) {
		List<String> runtimeClasspathElements = project.getRuntimeClasspathElements();

		classRealm = descriptor.getClassRealm();

		if (classRealm == null) {
			classRealm = project.getClassRealm();
		}

		for (String element : runtimeClasspathElements) {
			File elementFile = new File(element);
			classRealm.addURL(elementFile.toURI().toURL());
		}
	}
	return classRealm;
}
 
Example #21
Source File: MojoUtil.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static Set<URL> getProjectFiles(final MavenProject mavenProject, final List<InternalKieModule> kmoduleDeps)
        throws DependencyResolutionRequiredException, IOException {
    final Set<URL> urls = new HashSet<>();
    for (final String element : mavenProject.getCompileClasspathElements()) {
        urls.add(new File(element).toURI().toURL());
    }

    mavenProject.setArtifactFilter(new CumulativeScopeArtifactFilter(Arrays.asList("compile", "runtime")));
    for (final Artifact artifact : mavenProject.getArtifacts()) {
        final File file = artifact.getFile();
        if (file != null && file.isFile()) {
            urls.add(file.toURI().toURL());
            final KieModuleModel depModel = getDependencyKieModel(file);
            if (kmoduleDeps != null && depModel != null) {
                final ReleaseId releaseId = new ReleaseIdImpl(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
                kmoduleDeps.add(new ZipKieModule(releaseId, depModel, file));
            }
        }
    }
    return urls;
}
 
Example #22
Source File: FuzzGoal.java    From javafuzz with Apache License 2.0 6 votes vote down vote up
public void execute()
    {
        try {
            List<URL> pathUrls = new ArrayList<>();
            for(String mavenCompilePath: project.getTestClasspathElements()) {
                pathUrls.add(new File(mavenCompilePath).toURI().toURL());
            }

            URL[] urlsForClassLoader = pathUrls.toArray(new URL[pathUrls.size()]);
            System.out.println("urls for URLClassLoader: " + Arrays.asList(urlsForClassLoader));

// need to define parent classloader which knows all dependencies of the plugin
            URLClassLoader classLoader = new URLClassLoader(urlsForClassLoader, FuzzGoal.class.getClassLoader());
            AbstractFuzzTarget fuzzTarget =
                    (AbstractFuzzTarget) classLoader.loadClass(className).getDeclaredConstructor().newInstance();
            Fuzzer fuzzer = new Fuzzer(fuzzTarget, this.dirs);
            fuzzer.start();
        } catch (InstantiationException | IllegalAccessException | MalformedURLException | DependencyResolutionRequiredException
                | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        System.out.println("hello mojo");
    }
 
Example #23
Source File: SchemaGenerationMojo.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected List<URL> getCompiledClassNames() {

    List<Filter<File>> excludeFilters = schemaSourceExcludeFilters == null
            ? STANDARD_BYTECODE_EXCLUDE_FILTERS
            : schemaSourceExcludeFilters;
    Filters.initialize(getLog(), excludeFilters);

    try {
        return FileSystemUtilities.filterFiles(
                getProject().getBasedir(),
                null,
                getProject().getCompileClasspathElements(),
                getLog(),
                "compiled bytecode",
                excludeFilters);
    } catch (DependencyResolutionRequiredException e) {
        throw new IllegalStateException("Could not resolve dependencies.", e);
    }
}
 
Example #24
Source File: MavenUtilTest.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testJKubeProjectConversion() throws DependencyResolutionRequiredException {
  MavenProject mavenProject = getMavenProject();

  JavaProject project = MavenUtil.convertMavenProjectToJKubeProject(mavenProject, getMavenSession());
  assertEquals("testProject", project.getName());
  assertEquals("org.eclipse.jkube", project.getGroupId());
  assertEquals("test-project", project.getArtifactId());
  assertEquals("0.1.0", project.getVersion());
  assertEquals("test description", project.getDescription());
  assertEquals("target", project.getOutputDirectory().getName());
  assertEquals(".", project.getBuildDirectory().getName());
  assertEquals("https://www.eclipse.org/jkube/", project.getDocumentationUrl());
  assertEquals(1, mavenProject.getCompileClasspathElements().size());
  assertEquals("./target", mavenProject.getCompileClasspathElements().get(0));
  assertEquals("bar", project.getProperties().get("foo"));
}
 
Example #25
Source File: FlowPluginFrontendUtils.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a <code>ClassFinder</code> for the maven project.
 *
 * @param project
 *            a maven project instance used as source for the
 *            <code>ClassFinder</code>.
 * @return a <code>ClassFinder</code> instance.
 */
public static ClassFinder getClassFinder(MavenProject project) {
    final Stream<String> classpathElements;
    try {
        classpathElements = Stream.concat(
                project.getRuntimeClasspathElements().stream(),
                project.getCompileClasspathElements().stream()
                    .filter(s -> s.matches(INCLUDE_FROM_COMPILE_DEPS_REGEX)));
    } catch (DependencyResolutionRequiredException e) {
        throw new IllegalStateException(String.format(
                "Failed to retrieve runtime classpath elements from project '%s'",
                project), e);
    }
    URL[] urls = classpathElements.distinct().map(File::new)
            .map(FlowFileUtils::convertToUrl).toArray(URL[]::new);

    return new ReflectionsClassFinder(urls);
}
 
Example #26
Source File: MyBatisGeneratorMojo.java    From mybatis-generator-plus with Apache License 2.0 5 votes vote down vote up
private void calculateClassPath() throws MojoExecutionException {
    if (includeCompileDependencies || includeAllDependencies) {
        try {
            // add the project compile classpath to the plugin classpath,
            // so that the project dependency classes can be found
            // directly, without adding the classpath to configuration's classPathEntries
            // repeatedly.Examples are JDBC drivers, root classes, root interfaces, etc.
            Set<String> entries = new HashSet<>();
            if (includeCompileDependencies) {
                entries.addAll(project.getCompileClasspathElements());
            }
            
            if (includeAllDependencies) {
                entries.addAll(project.getTestClasspathElements());
            }
            
            // remove the output directories (target/classes and target/test-classes)
            // because this mojo runs in the generate-sources phase and
            // those directories have not been created yet (typically)
            entries.remove(project.getBuild().getOutputDirectory());
            entries.remove(project.getBuild().getTestOutputDirectory());

            ClassLoader contextClassLoader = ClassloaderUtility.getCustomClassloader(entries);
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("Dependency Resolution Required", e);
        }
    }
}
 
Example #27
Source File: XtendCompile.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
protected List<String> getClassPath() {
	Set<String> classPath = Sets.newLinkedHashSet();
	classPath.add(project.getBuild().getSourceDirectory());
	try {
		classPath.addAll(project.getCompileClasspathElements());
	} catch (DependencyResolutionRequiredException e) {
		throw new WrappedException(e);
	}
	addDependencies(classPath, project.getCompileArtifacts());
	classPath.remove(project.getBuild().getOutputDirectory());
	return newArrayList(filter(classPath, FILE_EXISTS));
}
 
Example #28
Source File: ConfigurationMetadataDocumentationMojo.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Override
public List<Archive> getNestedArchives(EntryFilter ignored) throws IOException {
	try {
		List<Archive> archives = new ArrayList<>(mavenProject.getRuntimeClasspathElements().size());
		for (String dep : mavenProject.getRuntimeClasspathElements()) {
			File file = new File(dep);
			archives.add(file.isDirectory() ? new ExplodedArchive(file) : new JarFileArchive(file));
		}
		return archives;
	}
	catch (DependencyResolutionRequiredException e) {
		throw new IOException("Could not create boot archive", e);
	}

}
 
Example #29
Source File: ActiveJdbcInstrumentationPlugin.java    From javalite with Apache License 2.0 5 votes vote down vote up
private void addProjectClassPathToPlugin() throws DependencyResolutionRequiredException, MalformedURLException {
    List runtimeClasspathElements = project.getRuntimeClasspathElements();
    for (Object runtimeClasspathElement : runtimeClasspathElements) {
        String element = (String) runtimeClasspathElement;
        URL url = new File(element).toURI().toURL();
        addUrlToPluginClasspath(url);
    }
}
 
Example #30
Source File: Parse.java    From Java2PlantUML with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches all project's class path elements and creates a URLClassLoader to be used by
 * Reflections.
 *
 * @return All class path's URLs in a ClassLoader
 * @throws DependencyResolutionRequiredException
 * @throws MojoExecutionException
 */
private URLClassLoader getLoader() throws DependencyResolutionRequiredException, MojoExecutionException {
    List<String> classpathElements = null;
    classpathElements = project.getCompileClasspathElements();
    List<URL> projectClasspathList = new ArrayList<>();
    for (String element : classpathElements) {
        try {
            projectClasspathList.add(new File(element).toURI().toURL());
        } catch (MalformedURLException e) {
            throw new MojoExecutionException(element + " is an invalid classpath element", e);
        }
    }
    URLClassLoader loader = new URLClassLoader(projectClasspathList.toArray(new URL[0]));
    return loader;
}