List of usage examples for org.apache.maven.artifact Artifact getVersion
String getVersion();
From source file:at.yawk.mdep.AntArtifactMatcher.java
@Override public boolean matches(Artifact artifact) { List<String> parts = Arrays.asList(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getClassifier());//from w w w .ja v a 2s . com for (int i = 0; i < this.patterns.size(); i++) { if (i > parts.size()) { // too specific return false; } if (!patternMatches(patterns.get(i), parts.get(i))) { return false; } } return true; }
From source file:at.yawk.mdep.GenerateMojo.java
private Dependency findArtifact(Artifact artifact) throws MojoExecutionException { // all are scanned, the first is used to store the dependency List<Path> cacheSearchLocations = new ArrayList<>(); List<String> coordinateComponents = Arrays.asList(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getScope()); // in 1.0, we used only ':' as the separator. This does not work on windows, and the following code fixes // that problem. for (String separator : Arrays.asList(":", "/")) { try {// w w w . j a v a 2s.c o m cacheSearchLocations.add(cacheStore.resolve(String.join(separator, coordinateComponents))); } catch (InvalidPathException ignored) { } } // check local cache if (cacheHours > 0) { for (Path searchLocation : cacheSearchLocations) { if (Files.exists(searchLocation)) { Instant cacheDeadline = Instant.now().minusSeconds((long) (60 * 60 * cacheHours)); try { if (Files.getLastModifiedTime(searchLocation).toInstant().isAfter(cacheDeadline)) { try (InputStream in = Files.newInputStream(searchLocation)) { Dependency dependency = (Dependency) JAXBContext.newInstance(Dependency.class) .createUnmarshaller().unmarshal(in); getLog().info("Checksum was present in local cache: " + artifact); return dependency; } } } catch (IOException | JAXBException e) { throw new MojoExecutionException("Failed to read local cache", e); } } } } for (ArtifactRepository repository : remoteArtifactRepositories) { // only scan configured repositories if (this.repositories != null && !this.repositories.contains(repository.getId())) { continue; } Dependency dependency = findArtifactInRepository(artifact, repository); if (dependency != null) { if (cacheHours > 0) { try { Path target = cacheSearchLocations.get(0); if (!Files.isDirectory(target.getParent())) { Files.createDirectories(target.getParent()); } try (OutputStream out = Files.newOutputStream(target)) { JAXBContext.newInstance(Dependency.class).createMarshaller().marshal(dependency, out); } } catch (IOException | JAXBException e) { getLog().warn("Could not save dependency to local cache", e); } } return dependency; } } throw new MojoExecutionException("Could not find " + artifact + " in configured repositories"); }
From source file:at.yawk.mdep.GenerateMojo.java
@Nullable
@SneakyThrows({ MalformedURLException.class, NoSuchAlgorithmException.class })
@VisibleForTesting/* w ww . j a va 2 s . c o m*/
Dependency findArtifactInRepository(Artifact artifact, ArtifactRepository repository)
throws MojoExecutionException {
String artifactPath = getArtifactPath(artifact, artifact.getVersion());
if (artifact.isSnapshot()) {
ArtifactRepositoryMetadata metadata = new ArtifactRepositoryMetadata(artifact) {
// maven is weird - i have yet to find a better solution.
@Override
public boolean storedInArtifactVersionDirectory() {
return true;
}
@Override
public String getBaseVersion() {
return artifact.getBaseVersion();
}
};
// try to load maven-metadata.xml in case we need to use a different version for snapshots
URL metaUrl = new URL(repository.getUrl() + '/' + repository.pathOfRemoteRepositoryMetadata(metadata));
Metadata loadedMetadata;
try (InputStream input = openStream(metaUrl)) {
loadedMetadata = new MetadataXpp3Reader().read(input, true);
} catch (IOException e) {
// could not find metadata
loadedMetadata = null;
} catch (XmlPullParserException e) {
throw new MojoExecutionException("Failed to parse metadata", e);
}
if (loadedMetadata != null) {
Snapshot snapshot = loadedMetadata.getVersioning().getSnapshot();
String versionWithoutSuffix = artifact.getVersion().substring(0,
artifact.getBaseVersion().lastIndexOf('-'));
artifactPath = getArtifactPath(artifact,
versionWithoutSuffix + '-' + snapshot.getTimestamp() + '-' + snapshot.getBuildNumber());
}
}
URL url = new URL(repository.getUrl() + '/' + artifactPath);
try (InputStream input = openStream(url)) {
getLog().info("Getting checksum for " + artifact);
MessageDigest digest = MessageDigest.getInstance("SHA-512");
byte[] buf = new byte[4096];
int len;
while ((len = input.read(buf)) >= 0) {
digest.update(buf, 0, len);
}
Dependency dependency = new Dependency();
dependency.setUrl(url);
dependency.setSha512sum(digest.digest());
return dependency;
} catch (IOException ignored) {
// not in this repo
return null;
}
}
From source file:au.net.coldeq.enforcer.BanDuplicateClasses.java
License:Apache License
private void assertThatAllDuplicatesAreOfClassesThatMatchToTheByte(Map<String, Set<Artifact>> duplicates) throws EnforcerRuleException { int errorCount = 0; for (Map.Entry<String, Set<Artifact>> entry : duplicates.entrySet()) { String className = entry.getKey(); Iterator<Artifact> iter = entry.getValue().iterator(); Artifact artifactA = iter.next(); byte[] artifactABytes = readBytesForClassFromArtifact(className, artifactA); while (iter.hasNext()) { Artifact artifactB = iter.next(); byte[] artifactBBytes = readBytesForClassFromArtifact(className, artifactB); if (areByteArraysDifferent(artifactABytes, artifactBBytes)) { errorCount++;// w ww .jav a 2 s.co m log.error(String.format("Multiple differing copies of %s found in %s:%s:%s and %s:%s:%s", StringUtils.replace(className.substring(0, className.indexOf(".class")), "/", "."), artifactA.getGroupId(), artifactA.getArtifactId(), artifactA.getVersion(), artifactB.getGroupId(), artifactB.getArtifactId(), artifactB.getVersion())); break; } } } if (errorCount > 0) { throw new EnforcerRuleException( "Duplicate classes found on classpath. " + errorCount + " instances detected."); } }
From source file:au.net.coldeq.enforcer.BanDuplicateClasses.java
License:Apache License
private byte[] readBytesForClassFromArtifact(String className, Artifact artifact) throws EnforcerRuleException { try {/*w w w. j a v a 2 s. c o m*/ JarFile jar = new JarFile(artifact.getFile()); try { for (JarEntry entry : Collections.<JarEntry>list(jar.entries())) { if (className.equals(entry.getName())) { return convertInputStreamToByteArray(jar.getInputStream(entry)); } } throw new RuntimeException(String.format("Expected to find %s in artifact: %s:%s:%s", className, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion())); } finally { try { jar.close(); } catch (IOException e) { } } } catch (IOException e) { throw new EnforcerRuleException("Unable to process dependency " + artifact.getFile().getAbsolutePath() + " due to " + e.getMessage(), e); } }
From source file:biz.gabrys.maven.plugin.util.classpath.ContextClassLoaderExtender.java
License:Open Source License
/** * Creates a text representation of the {@link Artifact}. * @param artifact the artifact.//ww w . j a v a2 s.co m * @return the text representation of the {@link Artifact}. * @since 1.4.0 */ protected String createDisplayText(final Artifact artifact) { return String.format("%s:%s-%s.%s (%s)", artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getType(), artifact.getScope()); }
From source file:biz.vidal.maven.plugins.uberjar.UberjarMojo.java
License:Apache License
private File uberjarArtifactFileWithClassifier() { Artifact artifact = project.getArtifact(); String classifier2 = classifier != null ? classifier : "uberjar"; final String uberjarName = artifact.getArtifactId() + "-" + artifact.getVersion() + "-" + classifier2 + "." + artifact.getArtifactHandler().getExtension(); return new File(outputDirectory, uberjarName); }
From source file:br.com.anteros.restdoc.maven.plugin.util.ResourceResolver.java
License:Apache License
private static Artifact createResourceArtifact(final Artifact artifact, final String classifier, final SourceResolverConfig config) { final DefaultArtifact a = (DefaultArtifact) config.artifactFactory().createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), "jar", classifier); a.setRepository(artifact.getRepository()); return a;/*w w w .j av a 2 s. c om*/ }
From source file:br.com.anteros.restdoc.maven.plugin.util.ResourceResolver.java
License:Apache License
@SuppressWarnings("unchecked") private static List<String> resolveAndUnpack(final List<Artifact> artifacts, final SourceResolverConfig config, final List<String> validClassifiers, final boolean propagateErrors) throws ArtifactResolutionException, ArtifactNotFoundException { // NOTE: Since these are '-sources' and '-test-sources' artifacts, they won't actually // resolve transitively...this is just used to aggregate resolution failures into a single // exception. final Set<Artifact> artifactSet = new LinkedHashSet<Artifact>(artifacts); final Artifact pomArtifact = config.project().getArtifact(); final ArtifactRepository localRepo = config.localRepository(); final List<ArtifactRepository> remoteRepos = config.project().getRemoteArtifactRepositories(); final ArtifactMetadataSource metadataSource = config.artifactMetadataSource(); final ArtifactFilter filter = config.filter(); ArtifactFilter resolutionFilter = null; if (filter != null) { // Wrap the filter in a ProjectArtifactFilter in order to always include the pomArtifact for resolution. // NOTE that this is necessary, b/c the -sources artifacts are added dynamically to the pomArtifact // and the resolver also checks the dependency trail with the given filter, thus the pomArtifact has // to be explicitly included by the filter, otherwise the -sources artifacts won't be resolved. resolutionFilter = new ProjectArtifactFilter(pomArtifact, filter); }/*from w w w. j a va 2s.co m*/ final ArtifactResolver resolver = config.artifactResolver(); @SuppressWarnings("rawtypes") Map managed = config.project().getManagedVersionMap(); final ArtifactResolutionResult resolutionResult = resolver.resolveTransitively(artifactSet, pomArtifact, managed, localRepo, remoteRepos, metadataSource, resolutionFilter); final List<String> result = new ArrayList<String>(artifacts.size()); for (final Artifact a : (Collection<Artifact>) resolutionResult.getArtifacts()) { if (!validClassifiers.contains(a.getClassifier()) || (filter != null && !filter.include(a))) { continue; } final File d = new File(config.outputBasedir(), a.getArtifactId() + "-" + a.getVersion() + "-" + a.getClassifier()); if (!d.exists()) { d.mkdirs(); } try { final UnArchiver unArchiver = config.archiverManager().getUnArchiver(a.getType()); unArchiver.setDestDirectory(d); unArchiver.setSourceFile(a.getFile()); unArchiver.extract(); result.add(d.getAbsolutePath()); } catch (final NoSuchArchiverException e) { if (propagateErrors) { throw new ArtifactResolutionException( "Failed to retrieve valid un-archiver component: " + a.getType(), a, e); } } catch (final ArchiverException e) { if (propagateErrors) { throw new ArtifactResolutionException("Failed to unpack: " + a.getId(), a, e); } } } return result; }
From source file:br.com.uggeri.maven.builder.mojo.ArtifactUtil.java
public final static String artifactName(Artifact artifact) { StringBuilder sb = new StringBuilder(); sb.append(artifact.getArtifactId()).append('-'); if (artifact.getVersion().isEmpty()) { sb.append(artifact.getBaseVersion()); } else {/*from w w w.j a v a2 s .com*/ sb.append(artifact.getVersion()); } if (artifact.hasClassifier()) { sb.append('-').append(artifact.getClassifier()); } sb.append('.').append(artifact.getType()); return sb.toString(); }