Java Code Examples for org.gradle.api.artifacts.ResolvedArtifact#getFile()

The following examples show how to use org.gradle.api.artifacts.ResolvedArtifact#getFile() . 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: MavenHelper.java    From cyclonedx-gradle-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the parent pom for an artifact (if any). The parent pom may contain license,
 * description, and other metadata whereas the artifact itself may not.
 * @param artifact the artifact to retrieve the parent pom for
 * @param project the maven project the artifact is part of
 */
private MavenProject retrieveParentProject(ResolvedArtifact artifact, MavenProject project) {
    if (artifact.getFile() == null || artifact.getFile().getParentFile() == null || !isDescribedArtifact(artifact)) {
        return null;
    }
    final Model model = project.getModel();
    if (model.getParent() != null) {
        final Parent parent = model.getParent();
        // Navigate out of version, artifactId, and first (possibly only) level of groupId
        final StringBuilder getout = new StringBuilder("../../../");
        final ModuleVersionIdentifier mid = artifact.getModuleVersion().getId();
        final int periods = mid.getGroup().length() - mid.getGroup().replace(".", "").length();
        for (int i= 0; i< periods; i++) {
            getout.append("../");
        }
        final File parentFile = new File(artifact.getFile().getParentFile(), getout + parent.getGroupId().replace(".", "/") + "/" + parent.getArtifactId() + "/" + parent.getVersion() + "/" + parent.getArtifactId() + "-" + parent.getVersion() + ".pom");
        if (parentFile.exists() && parentFile.isFile()) {
            try {
                return readPom(parentFile.getCanonicalFile());
            } catch (Exception e) {
                logger.error("An error occurred retrieving an artifacts parent pom", e);
            }
        }
    }
    return null;
}
 
Example 2
Source File: MavenHelper.java    From cyclonedx-gradle-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts a pom from an artifacts jar file and creates a MavenProject from it.
 * @param artifact the artifact to extract the pom from
 * @return a Maven project
 */
MavenProject extractPom(ResolvedArtifact artifact) {
    if (!isDescribedArtifact(artifact)) {
        return null;
    }
    if (artifact.getFile() != null) {
        try {
            final JarFile jarFile = new JarFile(artifact.getFile());
            final ModuleVersionIdentifier mid = artifact.getModuleVersion().getId();
            final JarEntry entry = jarFile.getJarEntry("META-INF/maven/"+ mid.getGroup() + "/" + mid.getName() + "/pom.xml");
            if (entry != null) {
                try (final InputStream input = jarFile.getInputStream(entry)) {
                    return readPom(input);
                }
            }
        } catch (IOException e) {
            logger.error("An error occurred attempting to extract POM from artifact", e);
        }
    }
    return null;
}
 
Example 3
Source File: GradleDependencyResolutionHelper.java    From thorntail with Apache License 2.0 6 votes vote down vote up
/**
 * Translate the given {@link ResolvedDependency resolved dependency} in to a {@link DependencyDescriptor} reference.
 *
 * @param scope      the scope to assign to the descriptor.
 * @param dependency the resolved dependency reference.
 * @return an instance of {@link DependencyDescriptor}.
 */
private static DependencyDescriptor asDescriptor(String scope, ResolvedDependency dependency) {

    Set<ResolvedArtifact> artifacts = dependency.getModuleArtifacts();

    // Let us use the first artifact's type for determining the type.
    // I am not sure under what circumstances, would we need to check for multiple artifacts.
    String type = "jar";
    String classifier = null;
    File file = null;

    if (!artifacts.isEmpty()) {
        ResolvedArtifact ra = artifacts.iterator().next();
        type = ra.getType();
        classifier = ra.getClassifier();
        file = ra.getFile();
    }
    return new DefaultDependencyDescriptor(scope, dependency.getModuleGroup(), dependency.getModuleName(),
                                           dependency.getModuleVersion(), type, classifier, file);
}
 
Example 4
Source File: SoLibrary.java    From atlas with Apache License 2.0 5 votes vote down vote up
public SoLibrary(ResolvedDependencyInfo resolvedDependencyInfo) {
    ResolvedArtifact artifact = resolvedDependencyInfo.getResolvedArtifact();

    this.mResolvedCoordinates = DependencyConvertUtils.convert(artifact, DependencyConvertUtils.Type.SOLIB);
    this.mSoLibFile = artifact.getFile();
    this.mSoLibFolder = resolvedDependencyInfo.getExplodedDir();
}
 
Example 5
Source File: DependencyConvertUtils.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Convert to jar dependency
 *
 * @param resolvedDependencyInfo
 * @return
 */
public static JavaLibrary toJavaLib(ResolvedDependencyInfo resolvedDependencyInfo) {

    ResolvedArtifact artifact = resolvedDependencyInfo.getResolvedArtifact();

    JavaLibrary jarInfo = new JavaLibraryImpl(artifact.getFile(),
                                              null,
                                              ImmutableList.<JavaLibrary>of(),
                                              null,
                                              convert(artifact,Type.JAR),
                                              false,
                                              false);
    return jarInfo;
}
 
Example 6
Source File: DependencyConvertUtils.java    From atlas with Apache License 2.0 5 votes vote down vote up
public static ApLibrary toApLibrary(ResolvedDependencyInfo resolvedDependencyInfo) {
    assertType(Type.AP, resolvedDependencyInfo);
    ResolvedArtifact artifact = resolvedDependencyInfo.getResolvedArtifact();
    ApLibrary apLibrary = new ApLibrary(convert(artifact,Type.AP),
                                        artifact.getFile(),
                                        resolvedDependencyInfo.getExplodedDir());
    return apLibrary;
}
 
Example 7
Source File: DependencyOrder.java    From pygradle with Apache License 2.0 5 votes vote down vote up
/**
 * Collects configuration files in post-order.
 *
 * @param configuration Gradle configuration to work with
 * @return set of files corresponding to post-order of dependency tree
 */
public static Collection<File> configurationPostOrderFiles(Configuration configuration) {
    Map<ModuleVersionIdentifier, File> idToFileMap = new HashMap<>();
    Set<File> files = new LinkedHashSet<>();
    Set<File> configurationFiles = configuration.getFiles();

    // Create an id:file mapping.
    Set<ResolvedArtifact> artifacts = configuration.getResolvedConfiguration().getResolvedArtifacts();
    for (ResolvedArtifact artifact : artifacts) {
        ModuleVersionIdentifier id = artifact.getModuleVersion().getId();
        File file = artifact.getFile();
        idToFileMap.put(id, file);
    }

    // Prepare an ordered set of files in post-order.
    for (ResolvedComponentResult d : configurationPostOrderDependencies(configuration)) {
        if (!idToFileMap.containsKey(d.getModuleVersion())) {
            logger.warn("***** WARNING Missing resolved artifact for " + d);
        } else {
            files.add(idToFileMap.get(d.getModuleVersion()));
        }
    }

    // Make sure the files set is a subset of configuration files.
    if (!configurationFiles.containsAll(files)) {
        throw new GradleException("Could not find matching dependencies for all configuration files");
    }

    /*
     * Our rest.li generated packages will extend configuration and
     * will not appear in the resolved results. We are going to add
     * them at the end in the same order they were added to
     * configuration files.
     */
    if (files.size() != configurationFiles.size()) {
        files.addAll(difference(configurationFiles, files));
    }

    return files;
}
 
Example 8
Source File: LinkageCheckTask.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
/** Returns true iff {@code configuration}'s artifacts contain linkage errors. */
private boolean findLinkageErrors(Configuration configuration) throws IOException {
  ImmutableList.Builder<ClassPathEntry> classPathBuilder = ImmutableList.builder();

  // TODO(suztomo): Should this include optional dependencies?
  //  Once we decide what to do with the optional dependencies, let's revisit this logic.
  for (ResolvedArtifact resolvedArtifact :
      configuration.getResolvedConfiguration().getResolvedArtifacts()) {
    ModuleVersionIdentifier moduleVersionId = resolvedArtifact.getModuleVersion().getId();
    DefaultArtifact artifact =
        new DefaultArtifact(
            moduleVersionId.getGroup(),
            moduleVersionId.getName(),
            null,
            null,
            moduleVersionId.getVersion(),
            null,
            resolvedArtifact.getFile());
    classPathBuilder.add(new ClassPathEntry(artifact));
  }

  ImmutableList<ClassPathEntry> classPath = classPathBuilder.build();

  if (!classPath.isEmpty()) {
    String exclusionFileName = extension.getExclusionFile();
    Path exclusionFile = exclusionFileName == null ? null : Paths.get(exclusionFileName);
    if (exclusionFile != null && !exclusionFile.isAbsolute()) {
      // Relative path from the project root
      Path projectRoot = getProject().getRootDir().toPath();
      exclusionFile = projectRoot.resolve(exclusionFile).toAbsolutePath();
    }

    // TODO(suztomo): Specify correct entry points if reportOnlyReachable is true.
    LinkageChecker linkageChecker = LinkageChecker.create(classPath, classPath, exclusionFile);

    ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
        linkageChecker.findSymbolProblems();

    int errorCount = symbolProblems.keySet().size();

    // TODO(suztomo): Show the dependency paths to the problematic artifacts.
    if (errorCount > 0) {
      getLogger().error(
          "Linkage Checker rule found {} error{}. Linkage error report:\n{}",
          errorCount,
          errorCount > 1 ? "s" : "",
          SymbolProblem.formatSymbolProblems(symbolProblems));

      ResolutionResult result = configuration.getIncoming().getResolutionResult();
      ResolvedComponentResult root = result.getRoot();
      String dependencyPaths = dependencyPathsOfProblematicJars(root, symbolProblems);
      getLogger().error(dependencyPaths);
      getLogger()
          .info(
              "For the details of the linkage errors, see "
                  + "https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/Linkage-Checker-Messages");
    }
    return errorCount > 0;
  }
  // When the configuration does not have any artifacts, there's no linkage error.
  return false;
}
 
Example 9
Source File: DependencyConvertUtils.java    From atlas with Apache License 2.0 4 votes vote down vote up
public static ApkLibrary toApkLibrary(ResolvedDependencyInfo resolvedDependencyInfo) {
    assertType(Type.APK, resolvedDependencyInfo);
    ResolvedArtifact artifact = resolvedDependencyInfo.getResolvedArtifact();
    ApkLibrary apkLibrary = new ApkLibrary(convert(artifact,Type.APK), artifact.getFile());
    return apkLibrary;
}
 
Example 10
Source File: GradleDependencyResolutionHelper.java    From thorntail with Apache License 2.0 2 votes vote down vote up
/**
 * Translate the given {@link ResolvedArtifact resolved artifact} in to a {@link DependencyDescriptor} reference.
 *
 * @param scope    the scope to assign to the descriptor.
 * @param artifact the resolved artifact reference.
 * @return an instance of {@link DependencyDescriptor}.
 */
private static DependencyDescriptor asDescriptor(String scope, ResolvedArtifact artifact) {
    ModuleVersionIdentifier id = artifact.getModuleVersion().getId();
    return new DefaultDependencyDescriptor(scope, id.getGroup(), id.getName(), id.getVersion(),
                                           artifact.getType(), artifact.getClassifier(), artifact.getFile());
}