proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/DefaultModelResolver.java
|
DefaultModelResolver
|
resolveModel
|
class DefaultModelResolver implements ModelResolver {
private List<RemoteRepository> repositories;
private final List<RemoteRepository> externalRepositories;
private final RemoteRepositoryManager remoteRepositoryManager;
private final Set<String> repositoryIds;
@Inject
public DefaultModelResolver(RemoteRepositoryManager remoteRepositoryManager) {
this(remoteRepositoryManager, List.of());
}
public DefaultModelResolver(RemoteRepositoryManager remoteRepositoryManager, List<RemoteRepository> repositories) {
this.remoteRepositoryManager = remoteRepositoryManager;
this.repositories = repositories;
this.externalRepositories = Collections.unmodifiableList(new ArrayList<>(repositories));
this.repositoryIds = new HashSet<>();
}
private DefaultModelResolver(DefaultModelResolver original) {
this.remoteRepositoryManager = original.remoteRepositoryManager;
this.repositories = new ArrayList<>(original.repositories);
this.externalRepositories = original.externalRepositories;
this.repositoryIds = new HashSet<>(original.repositoryIds);
}
@Override
public void addRepository(@Nonnull Session session, Repository repository) {
addRepository(session, repository, false);
}
@Override
public void addRepository(Session session, Repository repository, boolean replace) {
RepositorySystemSession rsession = InternalSession.from(session).getSession();
if (rsession.isIgnoreArtifactDescriptorRepositories()) {
return;
}
if (!repositoryIds.add(repository.getId())) {
if (!replace) {
return;
}
removeMatchingRepository(repositories, repository.getId());
}
List<RemoteRepository> newRepositories =
Collections.singletonList(ArtifactDescriptorUtils.toRemoteRepository(repository));
this.repositories =
remoteRepositoryManager.aggregateRepositories(rsession, repositories, newRepositories, true);
}
private static void removeMatchingRepository(Iterable<RemoteRepository> repositories, final String id) {
Iterator<RemoteRepository> iterator = repositories.iterator();
while (iterator.hasNext()) {
RemoteRepository remoteRepository = iterator.next();
if (remoteRepository.getId().equals(id)) {
iterator.remove();
}
}
}
@Override
public ModelResolver newCopy() {
return new DefaultModelResolver(this);
}
@Override
public ModelSource resolveModel(Session session, String groupId, String artifactId, String version)
throws ModelResolverException {
try {
session = session.withRemoteRepositories(repositories.stream()
.map(InternalSession.from(session)::getRemoteRepository)
.toList());
Map.Entry<org.apache.maven.api.Artifact, Path> resolved =
session.resolveArtifact(session.createArtifactCoordinate(groupId, artifactId, version, "pom"));
return ModelSource.fromPath(resolved.getValue(), groupId + ":" + artifactId + ":" + version);
} catch (ArtifactResolverException e) {
throw new ModelResolverException(
e.getMessage() + " (remote repositories: "
+ session.getRemoteRepositories().stream()
.map(Object::toString)
.collect(Collectors.joining(", "))
+ ")",
groupId,
artifactId,
version,
e);
}
}
@Override
public ModelSource resolveModel(Session session, Parent parent, AtomicReference<Parent> modified)
throws ModelResolverException {
try {
session = session.withRemoteRepositories(repositories.stream()
.map(InternalSession.from(session)::getRemoteRepository)
.toList());
ArtifactCoordinate coord = session.createArtifactCoordinate(
parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), "pom");
if (coord.getVersion().getVersionRange() != null
&& coord.getVersion().getVersionRange().getUpperBoundary() == null) {
// Message below is checked for in the MNG-2199 core IT.
throw new ModelResolverException(
String.format(
"The requested parent version range '%s' does not specify an upper bound",
parent.getVersion()),
parent.getGroupId(),
parent.getArtifactId(),
parent.getVersion());
}
List<Version> versions = session.resolveVersionRange(coord);
if (versions.isEmpty()) {
throw new ModelResolverException(
String.format(
"No versions matched the requested parent version range '%s'", parent.getVersion()),
parent.getGroupId(),
parent.getArtifactId(),
parent.getVersion());
}
String newVersion = versions.get(versions.size() - 1).asString();
if (!parent.getVersion().equals(newVersion)) {
modified.set(parent.withVersion(newVersion));
}
return resolveModel(session, parent.getGroupId(), parent.getArtifactId(), newVersion);
} catch (final VersionRangeResolverException e) {
throw new ModelResolverException(
e.getMessage() + " (remote repositories: "
+ session.getRemoteRepositories().stream()
.map(Object::toString)
.collect(Collectors.joining(", "))
+ ")",
parent.getGroupId(),
parent.getArtifactId(),
parent.getVersion(),
e);
}
}
@Override
public ModelSource resolveModel(Session session, Dependency dependency, AtomicReference<Dependency> modified)
throws ModelResolverException {<FILL_FUNCTION_BODY>}
}
|
try {
session = session.withRemoteRepositories(repositories.stream()
.map(InternalSession.from(session)::getRemoteRepository)
.toList());
ArtifactCoordinate coord = session.createArtifactCoordinate(
dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), "pom");
if (coord.getVersion().getVersionRange() != null
&& coord.getVersion().getVersionRange().getUpperBoundary() == null) {
// Message below is checked for in the MNG-2199 core IT.
throw new ModelResolverException(
String.format(
"The requested dependency version range '%s' does not specify an upper bound",
dependency.getVersion()),
dependency.getGroupId(),
dependency.getArtifactId(),
dependency.getVersion());
}
List<Version> versions = session.resolveVersionRange(coord);
if (versions.isEmpty()) {
throw new ModelResolverException(
String.format(
"No versions matched the requested dependency version range '%s'",
dependency.getVersion()),
dependency.getGroupId(),
dependency.getArtifactId(),
dependency.getVersion());
}
String newVersion = versions.get(versions.size() - 1).toString();
if (!dependency.getVersion().equals(newVersion)) {
modified.set(dependency.withVersion(newVersion));
}
return resolveModel(session, dependency.getGroupId(), dependency.getArtifactId(), newVersion);
} catch (VersionRangeResolverException e) {
throw new ModelResolverException(
e.getMessage() + " (remote repositories: "
+ session.getRemoteRepositories().stream()
.map(Object::toString)
.collect(Collectors.joining(", "))
+ ")",
dependency.getGroupId(),
dependency.getArtifactId(),
dependency.getVersion(),
e);
}
| 1,441
| 488
| 1,929
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/DefaultVersionRangeResolver.java
|
DefaultVersionRangeResolver
|
readVersions
|
class DefaultVersionRangeResolver implements VersionRangeResolver {
private static final String MAVEN_METADATA_XML = "maven-metadata.xml";
private final MetadataResolver metadataResolver;
private final SyncContextFactory syncContextFactory;
private final RepositoryEventDispatcher repositoryEventDispatcher;
private final VersionScheme versionScheme;
@Inject
public DefaultVersionRangeResolver(
MetadataResolver metadataResolver,
SyncContextFactory syncContextFactory,
RepositoryEventDispatcher repositoryEventDispatcher,
VersionScheme versionScheme) {
this.metadataResolver = Objects.requireNonNull(metadataResolver, "metadataResolver cannot be null");
this.syncContextFactory = Objects.requireNonNull(syncContextFactory, "syncContextFactory cannot be null");
this.repositoryEventDispatcher =
Objects.requireNonNull(repositoryEventDispatcher, "repositoryEventDispatcher cannot be null");
this.versionScheme = Objects.requireNonNull(versionScheme, "versionScheme cannot be null");
}
@Override
public VersionRangeResult resolveVersionRange(RepositorySystemSession session, VersionRangeRequest request)
throws VersionRangeResolutionException {
VersionRangeResult result = new VersionRangeResult(request);
VersionConstraint versionConstraint;
try {
versionConstraint =
versionScheme.parseVersionConstraint(request.getArtifact().getVersion());
} catch (InvalidVersionSpecificationException e) {
result.addException(e);
throw new VersionRangeResolutionException(result);
}
result.setVersionConstraint(versionConstraint);
if (versionConstraint.getRange() == null) {
result.addVersion(versionConstraint.getVersion());
} else {
VersionRange.Bound lowerBound = versionConstraint.getRange().getLowerBound();
if (lowerBound != null
&& lowerBound.equals(versionConstraint.getRange().getUpperBound())) {
result.addVersion(lowerBound.getVersion());
} else {
Map<String, ArtifactRepository> versionIndex = getVersions(session, result, request);
List<Version> versions = new ArrayList<>();
for (Map.Entry<String, ArtifactRepository> v : versionIndex.entrySet()) {
try {
Version ver = versionScheme.parseVersion(v.getKey());
if (versionConstraint.containsVersion(ver)) {
versions.add(ver);
result.setRepository(ver, v.getValue());
}
} catch (InvalidVersionSpecificationException e) {
result.addException(e);
}
}
Collections.sort(versions);
result.setVersions(versions);
}
}
return result;
}
private Map<String, ArtifactRepository> getVersions(
RepositorySystemSession session, VersionRangeResult result, VersionRangeRequest request) {
RequestTrace trace = RequestTrace.newChild(request.getTrace(), request);
Map<String, ArtifactRepository> versionIndex = new HashMap<>();
Metadata metadata = new DefaultMetadata(
request.getArtifact().getGroupId(),
request.getArtifact().getArtifactId(),
MAVEN_METADATA_XML,
Metadata.Nature.RELEASE_OR_SNAPSHOT);
List<MetadataRequest> metadataRequests =
new ArrayList<>(request.getRepositories().size());
metadataRequests.add(new MetadataRequest(metadata, null, request.getRequestContext()));
for (RemoteRepository repository : request.getRepositories()) {
MetadataRequest metadataRequest = new MetadataRequest(metadata, repository, request.getRequestContext());
metadataRequest.setDeleteLocalCopyIfMissing(true);
metadataRequest.setTrace(trace);
metadataRequests.add(metadataRequest);
}
List<MetadataResult> metadataResults = metadataResolver.resolveMetadata(session, metadataRequests);
WorkspaceReader workspace = session.getWorkspaceReader();
if (workspace != null) {
List<String> versions = workspace.findVersions(request.getArtifact());
for (String version : versions) {
versionIndex.put(version, workspace.getRepository());
}
}
for (MetadataResult metadataResult : metadataResults) {
result.addException(metadataResult.getException());
ArtifactRepository repository = metadataResult.getRequest().getRepository();
if (repository == null) {
repository = session.getLocalRepository();
}
Versioning versioning = readVersions(session, trace, metadataResult.getMetadata(), repository, result);
versioning = filterVersionsByRepositoryType(
versioning, metadataResult.getRequest().getRepository());
for (String version : versioning.getVersions()) {
if (!versionIndex.containsKey(version)) {
versionIndex.put(version, repository);
}
}
}
return versionIndex;
}
private Versioning readVersions(
RepositorySystemSession session,
RequestTrace trace,
Metadata metadata,
ArtifactRepository repository,
VersionRangeResult result) {<FILL_FUNCTION_BODY>}
private Versioning filterVersionsByRepositoryType(Versioning versioning, RemoteRepository remoteRepository) {
if (remoteRepository == null) {
return versioning;
}
return versioning.withVersions(versioning.getVersions().stream()
.filter(version -> remoteRepository
.getPolicy(DefaultModelVersionParser.checkSnapshot(version))
.isEnabled())
.toList());
}
private void invalidMetadata(
RepositorySystemSession session,
RequestTrace trace,
Metadata metadata,
ArtifactRepository repository,
Exception exception) {
RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INVALID);
event.setTrace(trace);
event.setMetadata(metadata);
event.setException(exception);
event.setRepository(repository);
repositoryEventDispatcher.dispatch(event.build());
}
}
|
Versioning versioning = null;
try {
if (metadata != null) {
try (SyncContext syncContext = syncContextFactory.newInstance(session, true)) {
syncContext.acquire(null, Collections.singleton(metadata));
if (metadata.getPath() != null && Files.exists(metadata.getPath())) {
try (InputStream in = Files.newInputStream(metadata.getPath())) {
versioning =
new MetadataStaxReader().read(in, false).getVersioning();
}
}
}
}
} catch (Exception e) {
invalidMetadata(session, trace, metadata, repository, e);
result.addException(e);
}
return (versioning != null) ? versioning : Versioning.newInstance();
| 1,499
| 200
| 1,699
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/LocalSnapshotMetadata.java
|
LocalSnapshotMetadata
|
merge
|
class LocalSnapshotMetadata extends MavenMetadata {
private final Collection<Artifact> artifacts = new ArrayList<>();
LocalSnapshotMetadata(Artifact artifact, Date timestamp) {
super(createMetadata(artifact), (Path) null, timestamp);
}
LocalSnapshotMetadata(Metadata metadata, Path path, Date timestamp) {
super(metadata, path, timestamp);
}
private static Metadata createMetadata(Artifact artifact) {
Snapshot snapshot = Snapshot.newBuilder().localCopy(true).build();
Versioning versioning = Versioning.newBuilder().snapshot(snapshot).build();
Metadata metadata = Metadata.newBuilder()
.versioning(versioning)
.groupId(artifact.getGroupId())
.artifactId(artifact.getArtifactId())
.version(artifact.getBaseVersion())
.modelVersion("1.1.0")
.build();
return metadata;
}
public void bind(Artifact artifact) {
artifacts.add(artifact);
}
@Deprecated
@Override
public MavenMetadata setFile(File file) {
return new LocalSnapshotMetadata(metadata, file.toPath(), timestamp);
}
@Override
public MavenMetadata setPath(Path path) {
return new LocalSnapshotMetadata(metadata, path, timestamp);
}
public Object getKey() {
return getGroupId() + ':' + getArtifactId() + ':' + getVersion();
}
public static Object getKey(Artifact artifact) {
return artifact.getGroupId() + ':' + artifact.getArtifactId() + ':' + artifact.getBaseVersion();
}
@Override
protected void merge(Metadata recessive) {<FILL_FUNCTION_BODY>}
private String getKey(String classifier, String extension) {
return classifier + ':' + extension;
}
@Override
public String getGroupId() {
return metadata.getGroupId();
}
@Override
public String getArtifactId() {
return metadata.getArtifactId();
}
@Override
public String getVersion() {
return metadata.getVersion();
}
@Override
public Nature getNature() {
return Nature.SNAPSHOT;
}
}
|
metadata = metadata.withVersioning(metadata.getVersioning().withLastUpdated(fmt.format(timestamp)));
String lastUpdated = metadata.getVersioning().getLastUpdated();
Map<String, SnapshotVersion> versions = new LinkedHashMap<>();
for (Artifact artifact : artifacts) {
SnapshotVersion sv = SnapshotVersion.newBuilder()
.classifier(artifact.getClassifier())
.extension(artifact.getExtension())
.version(getVersion())
.updated(lastUpdated)
.build();
versions.put(getKey(sv.getClassifier(), sv.getExtension()), sv);
}
Versioning versioning = recessive.getVersioning();
if (versioning != null) {
for (SnapshotVersion sv : versioning.getSnapshotVersions()) {
String key = getKey(sv.getClassifier(), sv.getExtension());
if (!versions.containsKey(key)) {
versions.put(key, sv);
}
}
}
metadata = metadata.withVersioning(metadata.getVersioning().withSnapshotVersions(versions.values()));
artifacts.clear();
| 576
| 289
| 865
|
<methods>public java.io.File getFile() ,public java.nio.file.Path getPath() ,public Map<java.lang.String,java.lang.String> getProperties() ,public java.lang.String getType() ,public boolean isMerged() ,public void merge(java.io.File, java.io.File) throws RepositoryException,public void merge(java.nio.file.Path, java.nio.file.Path) throws RepositoryException,public org.eclipse.aether.metadata.Metadata setProperties(Map<java.lang.String,java.lang.String>) <variables>static final java.lang.String MAVEN_METADATA_XML,static java.text.DateFormat fmt,private boolean merged,protected Metadata metadata,private final non-sealed java.nio.file.Path path,protected final non-sealed java.util.Date timestamp
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/LocalSnapshotMetadataGenerator.java
|
LocalSnapshotMetadataGenerator
|
prepare
|
class LocalSnapshotMetadataGenerator implements MetadataGenerator {
private final Map<Object, LocalSnapshotMetadata> snapshots;
private final Date timestamp;
LocalSnapshotMetadataGenerator(RepositorySystemSession session, InstallRequest request) {
timestamp = (Date) ConfigUtils.getObject(session, new Date(), "maven.startTime");
snapshots = new LinkedHashMap<>();
}
@Override
public Collection<? extends Metadata> prepare(Collection<? extends Artifact> artifacts) {<FILL_FUNCTION_BODY>}
@Override
public Artifact transformArtifact(Artifact artifact) {
return artifact;
}
@Override
public Collection<? extends Metadata> finish(Collection<? extends Artifact> artifacts) {
return snapshots.values();
}
}
|
for (Artifact artifact : artifacts) {
if (artifact.isSnapshot()) {
Object key = LocalSnapshotMetadata.getKey(artifact);
LocalSnapshotMetadata snapshotMetadata = snapshots.get(key);
if (snapshotMetadata == null) {
snapshotMetadata = new LocalSnapshotMetadata(artifact, timestamp);
snapshots.put(key, snapshotMetadata);
}
snapshotMetadata.bind(artifact);
}
}
return Collections.emptyList();
| 200
| 119
| 319
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/MavenMetadata.java
|
MavenMetadata
|
write
|
class MavenMetadata extends AbstractMetadata implements MergeableMetadata {
static final String MAVEN_METADATA_XML = "maven-metadata.xml";
static DateFormat fmt;
static {
TimeZone timezone = TimeZone.getTimeZone("UTC");
fmt = new SimpleDateFormat("yyyyMMddHHmmss");
fmt.setTimeZone(timezone);
}
protected Metadata metadata;
private final Path path;
protected final Date timestamp;
private boolean merged;
@Deprecated
protected MavenMetadata(Metadata metadata, File file, Date timestamp) {
this(metadata, file != null ? file.toPath() : null, timestamp);
}
protected MavenMetadata(Metadata metadata, Path path, Date timestamp) {
this.metadata = metadata;
this.path = path;
this.timestamp = timestamp;
}
@Override
public String getType() {
return MAVEN_METADATA_XML;
}
@Deprecated
@Override
public File getFile() {
return path != null ? path.toFile() : null;
}
@Override
public Path getPath() {
return path;
}
public void merge(File existing, File result) throws RepositoryException {
merge(existing != null ? existing.toPath() : null, result != null ? result.toPath() : null);
}
@Override
public void merge(Path existing, Path result) throws RepositoryException {
Metadata recessive = read(existing);
merge(recessive);
write(result, metadata);
merged = true;
}
@Override
public boolean isMerged() {
return merged;
}
protected abstract void merge(Metadata recessive);
static Metadata read(Path metadataPath) throws RepositoryException {
if (!Files.exists(metadataPath)) {
return Metadata.newInstance();
}
try (InputStream input = Files.newInputStream(metadataPath)) {
return new MetadataStaxReader().read(input, false);
} catch (IOException | XMLStreamException e) {
throw new RepositoryException("Could not parse metadata " + metadataPath + ": " + e.getMessage(), e);
}
}
private void write(Path metadataPath, Metadata metadata) throws RepositoryException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, String> getProperties() {
return Collections.emptyMap();
}
@Override
public org.eclipse.aether.metadata.Metadata setProperties(Map<String, String> properties) {
return this;
}
}
|
try {
Files.createDirectories(metadataPath.getParent());
try (OutputStream output = Files.newOutputStream(metadataPath)) {
new MetadataStaxWriter().write(output, metadata);
}
} catch (IOException | XMLStreamException e) {
throw new RepositoryException("Could not write metadata " + metadataPath + ": " + e.getMessage(), e);
}
| 683
| 98
| 781
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/MavenSessionBuilderSupplier.java
|
MavenSessionBuilderSupplier
|
getArtifactTypeRegistry
|
class MavenSessionBuilderSupplier implements Supplier<SessionBuilder> {
protected final RepositorySystem repositorySystem;
protected final InternalScopeManager scopeManager;
public MavenSessionBuilderSupplier(RepositorySystem repositorySystem) {
this.repositorySystem = requireNonNull(repositorySystem);
this.scopeManager = new ScopeManagerImpl(Maven4ScopeManagerConfiguration.INSTANCE);
}
protected DependencyTraverser getDependencyTraverser() {
return new FatArtifactTraverser();
}
protected InternalScopeManager getScopeManager() {
return scopeManager;
}
protected DependencyManager getDependencyManager() {
return getDependencyManager(true); // same default as in Maven4
}
public DependencyManager getDependencyManager(boolean transitive) {
return new ClassicDependencyManager(transitive, getScopeManager());
}
protected DependencySelector getDependencySelector() {
return new AndDependencySelector(
ScopeDependencySelector.legacy(
null, Arrays.asList(DependencyScope.TEST.id(), DependencyScope.PROVIDED.id())),
OptionalDependencySelector.fromDirect(),
new ExclusionDependencySelector());
}
protected DependencyGraphTransformer getDependencyGraphTransformer() {
return new ChainedDependencyGraphTransformer(
new ConflictResolver(
new NearestVersionSelector(), new ManagedScopeSelector(getScopeManager()),
new SimpleOptionalitySelector(), new ManagedScopeDeriver(getScopeManager())),
new ManagedDependencyContextRefiner(getScopeManager()));
}
/**
* This method produces "surrogate" type registry that is static: it aims users that want to use
* Maven-Resolver without involving Maven Core and related things.
* <p>
* This type registry is NOT used by Maven Core: Maven replaces it during Session creation with a type registry
* that supports extending it (i.e. via Maven Extensions).
* <p>
* Important: this "static" list of types should be in-sync with core provided types.
*/
protected ArtifactTypeRegistry getArtifactTypeRegistry() {<FILL_FUNCTION_BODY>}
protected ArtifactDescriptorPolicy getArtifactDescriptorPolicy() {
return new SimpleArtifactDescriptorPolicy(true, true);
}
protected void configureSessionBuilder(SessionBuilder session) {
session.setDependencyTraverser(getDependencyTraverser());
session.setDependencyManager(getDependencyManager());
session.setDependencySelector(getDependencySelector());
session.setDependencyGraphTransformer(getDependencyGraphTransformer());
session.setArtifactTypeRegistry(getArtifactTypeRegistry());
session.setArtifactDescriptorPolicy(getArtifactDescriptorPolicy());
session.setScopeManager(getScopeManager());
}
/**
* Creates a new Maven-like repository system session by initializing the session with values typical for
* Maven-based resolution. In more detail, this method configures settings relevant for the processing of dependency
* graphs, most other settings remain at their generic default value. Use the various setters to further configure
* the session with authentication, mirror, proxy and other information required for your environment. At least,
* local repository manager needs to be configured to make session be able to create session instance.
*
* @return SessionBuilder configured with minimally required things for "Maven-based resolution". At least LRM must
* be set on builder to make it able to create session instances.
*/
@Override
public SessionBuilder get() {
requireNonNull(repositorySystem, "repositorySystem");
SessionBuilder builder = repositorySystem.createSessionBuilder();
configureSessionBuilder(builder);
return builder;
}
}
|
DefaultArtifactTypeRegistry stereotypes = new DefaultArtifactTypeRegistry();
new DefaultTypeProvider().types().forEach(stereotypes::add);
return stereotypes;
| 905
| 46
| 951
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/PluginsMetadata.java
|
PluginInfo
|
merge
|
class PluginInfo {
final String groupId;
private final String artifactId;
private final String goalPrefix;
private final String name;
PluginInfo(String groupId, String artifactId, String goalPrefix, String name) {
this.groupId = groupId;
this.artifactId = artifactId;
this.goalPrefix = goalPrefix;
this.name = name;
}
}
private final PluginInfo pluginInfo;
PluginsMetadata(PluginInfo pluginInfo, Date timestamp) {
super(createRepositoryMetadata(pluginInfo), (Path) null, timestamp);
this.pluginInfo = pluginInfo;
}
PluginsMetadata(PluginInfo pluginInfo, Path path, Date timestamp) {
super(createRepositoryMetadata(pluginInfo), path, timestamp);
this.pluginInfo = pluginInfo;
}
private static Metadata createRepositoryMetadata(PluginInfo pluginInfo) {
return Metadata.newBuilder()
.plugins(List.of(Plugin.newBuilder()
.prefix(pluginInfo.goalPrefix)
.artifactId(pluginInfo.artifactId)
.name(pluginInfo.name)
.build()))
.build();
}
@Override
protected void merge(Metadata recessive) {<FILL_FUNCTION_BODY>
|
List<Plugin> recessivePlugins = recessive.getPlugins();
List<Plugin> plugins = metadata.getPlugins();
if (!plugins.isEmpty()) {
LinkedHashMap<String, Plugin> mergedPlugins = new LinkedHashMap<>();
recessivePlugins.forEach(p -> mergedPlugins.put(p.getPrefix(), p));
plugins.forEach(p -> mergedPlugins.put(p.getPrefix(), p));
metadata = metadata.withPlugins(mergedPlugins.values());
}
| 325
| 144
| 469
|
<methods>public java.io.File getFile() ,public java.nio.file.Path getPath() ,public Map<java.lang.String,java.lang.String> getProperties() ,public java.lang.String getType() ,public boolean isMerged() ,public void merge(java.io.File, java.io.File) throws RepositoryException,public void merge(java.nio.file.Path, java.nio.file.Path) throws RepositoryException,public org.eclipse.aether.metadata.Metadata setProperties(Map<java.lang.String,java.lang.String>) <variables>static final java.lang.String MAVEN_METADATA_XML,static java.text.DateFormat fmt,private boolean merged,protected Metadata metadata,private final non-sealed java.nio.file.Path path,protected final non-sealed java.util.Date timestamp
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/PluginsMetadataGenerator.java
|
PluginsMetadataGenerator
|
extractPluginInfo
|
class PluginsMetadataGenerator implements MetadataGenerator {
private static final String PLUGIN_DESCRIPTOR_LOCATION = "META-INF/maven/plugin.xml";
private final Map<Object, PluginsMetadata> processedPlugins;
private final Date timestamp;
PluginsMetadataGenerator(RepositorySystemSession session, InstallRequest request) {
this(session, request.getMetadata());
}
PluginsMetadataGenerator(RepositorySystemSession session, DeployRequest request) {
this(session, request.getMetadata());
}
private PluginsMetadataGenerator(RepositorySystemSession session, Collection<? extends Metadata> metadatas) {
this.processedPlugins = new LinkedHashMap<>();
this.timestamp = (Date) ConfigUtils.getObject(session, new Date(), "maven.startTime");
/*
* NOTE: This should be considered a quirk to support interop with Maven's legacy ArtifactDeployer which
* processes one artifact at a time and hence cannot associate the artifacts from the same project to use the
* same version index. Allowing the caller to pass in metadata from a previous deployment allows to re-establish
* the association between the artifacts of the same project.
*/
for (Iterator<? extends Metadata> it = metadatas.iterator(); it.hasNext(); ) {
Metadata metadata = it.next();
if (metadata instanceof PluginsMetadata pluginMetadata) {
it.remove();
processedPlugins.put(pluginMetadata.getGroupId(), pluginMetadata);
}
}
}
@Override
public Collection<? extends Metadata> prepare(Collection<? extends Artifact> artifacts) {
return Collections.emptyList();
}
@Override
public Artifact transformArtifact(Artifact artifact) {
return artifact;
}
@Override
public Collection<? extends Metadata> finish(Collection<? extends Artifact> artifacts) {
LinkedHashMap<String, PluginsMetadata> plugins = new LinkedHashMap<>();
for (Artifact artifact : artifacts) {
PluginInfo pluginInfo = extractPluginInfo(artifact);
if (pluginInfo != null) {
String key = pluginInfo.groupId;
if (processedPlugins.get(key) == null) {
PluginsMetadata pluginMetadata = plugins.get(key);
if (pluginMetadata == null) {
pluginMetadata = new PluginsMetadata(pluginInfo, timestamp);
plugins.put(key, pluginMetadata);
}
}
}
}
return plugins.values();
}
private PluginInfo extractPluginInfo(Artifact artifact) {<FILL_FUNCTION_BODY>}
}
|
// sanity: jar, no classifier and file exists
if (artifact != null
&& "jar".equals(artifact.getExtension())
&& "".equals(artifact.getClassifier())
&& artifact.getPath() != null) {
Path artifactPath = artifact.getPath();
if (Files.isRegularFile(artifactPath)) {
try (JarFile artifactJar = new JarFile(artifactPath.toFile(), false)) {
ZipEntry pluginDescriptorEntry = artifactJar.getEntry(PLUGIN_DESCRIPTOR_LOCATION);
if (pluginDescriptorEntry != null) {
try (InputStream is = artifactJar.getInputStream(pluginDescriptorEntry)) {
// Note: using DOM instead of use of
// org.apache.maven.plugin.descriptor.PluginDescriptor
// as it would pull in dependency on:
// - maven-plugin-api (for model)
// - Plexus Container (for model supporting classes and exceptions)
XmlNode root = XmlNodeStaxBuilder.build(is, null);
String groupId = root.getChild("groupId").getValue();
String artifactId = root.getChild("artifactId").getValue();
String goalPrefix = root.getChild("goalPrefix").getValue();
String name = root.getChild("name").getValue();
return new PluginInfo(groupId, artifactId, goalPrefix, name);
}
}
} catch (Exception e) {
// here we can have: IO. ZIP or Plexus Conf Ex: but we should not interfere with user intent
}
}
}
return null;
| 675
| 397
| 1,072
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/RelocatedArtifact.java
|
RelocatedArtifact
|
getClassifier
|
class RelocatedArtifact extends AbstractArtifact {
private final Artifact artifact;
private final String groupId;
private final String artifactId;
private final String classifier;
private final String extension;
private final String version;
private final String message;
public RelocatedArtifact(
Artifact artifact,
String groupId,
String artifactId,
String classifier,
String extension,
String version,
String message) {
this.artifact = Objects.requireNonNull(artifact, "artifact cannot be null");
this.groupId = (groupId != null && !groupId.isEmpty()) ? groupId : null;
this.artifactId = (artifactId != null && !artifactId.isEmpty()) ? artifactId : null;
this.classifier = (classifier != null && !classifier.isEmpty()) ? classifier : null;
this.extension = (extension != null && !extension.isEmpty()) ? extension : null;
this.version = (version != null && !version.isEmpty()) ? version : null;
this.message = (message != null && !message.isEmpty()) ? message : null;
}
@Override
public String getGroupId() {
if (groupId != null) {
return groupId;
} else {
return artifact.getGroupId();
}
}
@Override
public String getArtifactId() {
if (artifactId != null) {
return artifactId;
} else {
return artifact.getArtifactId();
}
}
@Override
public String getClassifier() {<FILL_FUNCTION_BODY>}
@Override
public String getExtension() {
if (extension != null) {
return extension;
} else {
return artifact.getExtension();
}
}
@Override
public String getVersion() {
if (version != null) {
return version;
} else {
return artifact.getVersion();
}
}
// Revise these three methods when MRESOLVER-233 is delivered
@Override
public Artifact setVersion(String version) {
String current = getVersion();
if (current.equals(version) || (version == null && current.isEmpty())) {
return this;
}
return new RelocatedArtifact(artifact, groupId, artifactId, classifier, extension, version, message);
}
@Deprecated
@Override
public Artifact setFile(File file) {
File current = getFile();
if (Objects.equals(current, file)) {
return this;
}
return new RelocatedArtifact(
artifact.setFile(file), groupId, artifactId, classifier, extension, version, message);
}
@Override
public Artifact setPath(Path path) {
Path current = getPath();
if (Objects.equals(current, path)) {
return this;
}
return new RelocatedArtifact(
artifact.setPath(path), groupId, artifactId, classifier, extension, version, message);
}
@Override
public Artifact setProperties(Map<String, String> properties) {
Map<String, String> current = getProperties();
if (current.equals(properties) || (properties == null && current.isEmpty())) {
return this;
}
return new RelocatedArtifact(
artifact.setProperties(properties), groupId, artifactId, classifier, extension, version, message);
}
@Deprecated
@Override
public File getFile() {
return artifact.getFile();
}
@Override
public Path getPath() {
return artifact.getPath();
}
@Override
public String getProperty(String key, String defaultValue) {
return artifact.getProperty(key, defaultValue);
}
@Override
public Map<String, String> getProperties() {
return artifact.getProperties();
}
public String getMessage() {
return message;
}
}
|
if (classifier != null) {
return classifier;
} else {
return artifact.getClassifier();
}
| 1,018
| 37
| 1,055
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/RemoteSnapshotMetadata.java
|
RemoteSnapshotMetadata
|
merge
|
class RemoteSnapshotMetadata extends MavenSnapshotMetadata {
public static final String DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT = "yyyyMMdd.HHmmss";
public static final TimeZone DEFAULT_SNAPSHOT_TIME_ZONE = TimeZone.getTimeZone("Etc/UTC");
private final Map<String, SnapshotVersion> versions = new LinkedHashMap<>();
private final Integer buildNumber;
RemoteSnapshotMetadata(Artifact artifact, Date timestamp, Integer buildNumber) {
super(createRepositoryMetadata(artifact), null, timestamp);
this.buildNumber = buildNumber;
}
private RemoteSnapshotMetadata(Metadata metadata, Path path, Date timestamp, Integer buildNumber) {
super(metadata, path, timestamp);
this.buildNumber = buildNumber;
}
@Deprecated
@Override
public MavenMetadata setFile(File file) {
return new RemoteSnapshotMetadata(metadata, file.toPath(), timestamp, buildNumber);
}
@Override
public MavenMetadata setPath(Path path) {
return new RemoteSnapshotMetadata(metadata, path, timestamp, buildNumber);
}
public String getExpandedVersion(Artifact artifact) {
String key = getKey(artifact.getClassifier(), artifact.getExtension());
return versions.get(key).getVersion();
}
@Override
protected void merge(Metadata recessive) {<FILL_FUNCTION_BODY>}
private static int getBuildNumber(Metadata metadata) {
int number = 0;
Versioning versioning = metadata.getVersioning();
if (versioning != null) {
Snapshot snapshot = versioning.getSnapshot();
if (snapshot != null && snapshot.getBuildNumber() > 0) {
number = snapshot.getBuildNumber();
}
}
return number;
}
}
|
Snapshot snapshot;
String lastUpdated;
if (metadata.getVersioning() == null) {
DateFormat utcDateFormatter = new SimpleDateFormat(DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT);
utcDateFormatter.setCalendar(new GregorianCalendar());
utcDateFormatter.setTimeZone(DEFAULT_SNAPSHOT_TIME_ZONE);
snapshot = Snapshot.newBuilder()
.buildNumber(buildNumber != null ? buildNumber : getBuildNumber(recessive) + 1)
.timestamp(utcDateFormatter.format(this.timestamp))
.build();
lastUpdated = fmt.format(timestamp);
Versioning versioning = Versioning.newBuilder()
.snapshot(snapshot)
.lastUpdated(lastUpdated)
.build();
metadata = metadata.withVersioning(versioning);
} else {
snapshot = metadata.getVersioning().getSnapshot();
lastUpdated = metadata.getVersioning().getLastUpdated();
}
for (Artifact artifact : artifacts) {
String version = artifact.getVersion();
if (version.endsWith(SNAPSHOT)) {
String qualifier = snapshot.getTimestamp() + '-' + snapshot.getBuildNumber();
version = version.substring(0, version.length() - SNAPSHOT.length()) + qualifier;
}
SnapshotVersion sv = SnapshotVersion.newBuilder()
.classifier(artifact.getClassifier())
.extension(artifact.getExtension())
.version(version)
.updated(lastUpdated)
.build();
versions.put(getKey(sv.getClassifier(), sv.getExtension()), sv);
}
artifacts.clear();
Versioning versioning = recessive.getVersioning();
if (versioning != null) {
for (SnapshotVersion sv : versioning.getSnapshotVersions()) {
String key = getKey(sv.getClassifier(), sv.getExtension());
if (!versions.containsKey(key)) {
versions.put(key, sv);
}
}
}
metadata = metadata.withVersioning(metadata.getVersioning().withSnapshotVersions(versions.values()));
| 461
| 557
| 1,018
|
<methods>public void bind(Artifact) ,public java.lang.String getArtifactId() ,public java.lang.String getGroupId() ,public java.lang.Object getKey() ,public static java.lang.Object getKey(Artifact) ,public Nature getNature() ,public java.lang.String getVersion() <variables>static final java.lang.String SNAPSHOT,protected final Collection<Artifact> artifacts
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/RemoteSnapshotMetadataGenerator.java
|
RemoteSnapshotMetadataGenerator
|
transformArtifact
|
class RemoteSnapshotMetadataGenerator implements MetadataGenerator {
private final Map<Object, RemoteSnapshotMetadata> snapshots;
private final Date timestamp;
private final Integer buildNumber;
RemoteSnapshotMetadataGenerator(RepositorySystemSession session, DeployRequest request) {
timestamp = (Date) ConfigUtils.getObject(session, new Date(), "maven.startTime");
Object bn = ConfigUtils.getObject(session, null, "maven.buildNumber");
if (bn instanceof Integer) {
this.buildNumber = (Integer) bn;
} else if (bn instanceof String) {
this.buildNumber = Integer.valueOf((String) bn);
} else {
this.buildNumber = null;
}
snapshots = new LinkedHashMap<>();
/*
* NOTE: This should be considered a quirk to support interop with Maven's legacy ArtifactDeployer which
* processes one artifact at a time and hence cannot associate the artifacts from the same project to use the
* same timestamp+buildno for the snapshot versions. Allowing the caller to pass in metadata from a previous
* deployment allows to re-establish the association between the artifacts of the same project.
*/
for (Metadata metadata : request.getMetadata()) {
if (metadata instanceof RemoteSnapshotMetadata) {
RemoteSnapshotMetadata snapshotMetadata = (RemoteSnapshotMetadata) metadata;
snapshots.put(snapshotMetadata.getKey(), snapshotMetadata);
}
}
}
@Override
public Collection<? extends Metadata> prepare(Collection<? extends Artifact> artifacts) {
for (Artifact artifact : artifacts) {
if (artifact.isSnapshot()) {
Object key = RemoteSnapshotMetadata.getKey(artifact);
RemoteSnapshotMetadata snapshotMetadata = snapshots.get(key);
if (snapshotMetadata == null) {
snapshotMetadata = new RemoteSnapshotMetadata(artifact, timestamp, buildNumber);
snapshots.put(key, snapshotMetadata);
}
snapshotMetadata.bind(artifact);
}
}
return snapshots.values();
}
@Override
public Artifact transformArtifact(Artifact artifact) {<FILL_FUNCTION_BODY>}
@Override
public Collection<? extends Metadata> finish(Collection<? extends Artifact> artifacts) {
return Collections.emptyList();
}
}
|
if (artifact.isSnapshot() && artifact.getVersion().equals(artifact.getBaseVersion())) {
Object key = RemoteSnapshotMetadata.getKey(artifact);
RemoteSnapshotMetadata snapshotMetadata = snapshots.get(key);
if (snapshotMetadata != null) {
artifact = artifact.setVersion(snapshotMetadata.getExpandedVersion(artifact));
}
}
return artifact;
| 580
| 100
| 680
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/VersionsMetadata.java
|
VersionsMetadata
|
createRepositoryMetadata
|
class VersionsMetadata extends MavenMetadata {
private final Artifact artifact;
VersionsMetadata(Artifact artifact, Date timestamp) {
super(createRepositoryMetadata(artifact), (Path) null, timestamp);
this.artifact = artifact;
}
VersionsMetadata(Artifact artifact, Path path, Date timestamp) {
super(createRepositoryMetadata(artifact), path, timestamp);
this.artifact = artifact;
}
private static Metadata createRepositoryMetadata(Artifact artifact) {<FILL_FUNCTION_BODY>}
@Override
protected void merge(Metadata recessive) {
Versioning original = metadata.getVersioning();
Versioning.Builder versioning = Versioning.newBuilder(original);
versioning.lastUpdated(fmt.format(timestamp));
if (recessive.getVersioning() != null) {
if (original.getLatest() == null) {
versioning.latest(recessive.getVersioning().getLatest());
}
if (original.getRelease() == null) {
versioning.release(recessive.getVersioning().getRelease());
}
Collection<String> versions =
new LinkedHashSet<>(recessive.getVersioning().getVersions());
versions.addAll(original.getVersions());
versioning.versions(new ArrayList<>(versions));
}
metadata = metadata.withVersioning(versioning.build());
}
public Object getKey() {
return getGroupId() + ':' + getArtifactId();
}
public static Object getKey(Artifact artifact) {
return artifact.getGroupId() + ':' + artifact.getArtifactId();
}
@Deprecated
@Override
public MavenMetadata setFile(File file) {
return new VersionsMetadata(artifact, file.toPath(), timestamp);
}
@Override
public MavenMetadata setPath(Path path) {
return new VersionsMetadata(artifact, path, timestamp);
}
@Override
public String getGroupId() {
return artifact.getGroupId();
}
@Override
public String getArtifactId() {
return artifact.getArtifactId();
}
@Override
public String getVersion() {
return "";
}
@Override
public Nature getNature() {
return artifact.isSnapshot() ? Nature.RELEASE_OR_SNAPSHOT : Nature.RELEASE;
}
}
|
Metadata.Builder metadata = Metadata.newBuilder();
metadata.groupId(artifact.getGroupId());
metadata.artifactId(artifact.getArtifactId());
Versioning.Builder versioning = Versioning.newBuilder();
versioning.versions(List.of(artifact.getBaseVersion()));
if (!artifact.isSnapshot()) {
versioning.release(artifact.getBaseVersion());
}
if ("maven-plugin".equals(artifact.getProperty(ArtifactProperties.TYPE, ""))) {
versioning.latest(artifact.getBaseVersion());
}
metadata.versioning(versioning.build());
return metadata.build();
| 622
| 164
| 786
|
<methods>public java.io.File getFile() ,public java.nio.file.Path getPath() ,public Map<java.lang.String,java.lang.String> getProperties() ,public java.lang.String getType() ,public boolean isMerged() ,public void merge(java.io.File, java.io.File) throws RepositoryException,public void merge(java.nio.file.Path, java.nio.file.Path) throws RepositoryException,public org.eclipse.aether.metadata.Metadata setProperties(Map<java.lang.String,java.lang.String>) <variables>static final java.lang.String MAVEN_METADATA_XML,static java.text.DateFormat fmt,private boolean merged,protected Metadata metadata,private final non-sealed java.nio.file.Path path,protected final non-sealed java.util.Date timestamp
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/VersionsMetadataGenerator.java
|
VersionsMetadataGenerator
|
finish
|
class VersionsMetadataGenerator implements MetadataGenerator {
private final Map<Object, VersionsMetadata> versions;
private final Map<Object, VersionsMetadata> processedVersions;
private final Date timestamp;
VersionsMetadataGenerator(RepositorySystemSession session, InstallRequest request) {
this(session, request.getMetadata());
}
VersionsMetadataGenerator(RepositorySystemSession session, DeployRequest request) {
this(session, request.getMetadata());
}
private VersionsMetadataGenerator(RepositorySystemSession session, Collection<? extends Metadata> metadatas) {
versions = new LinkedHashMap<>();
processedVersions = new LinkedHashMap<>();
timestamp = (Date) ConfigUtils.getObject(session, new Date(), "maven.startTime");
/*
* NOTE: This should be considered a quirk to support interop with Maven's legacy ArtifactDeployer which
* processes one artifact at a time and hence cannot associate the artifacts from the same project to use the
* same version index. Allowing the caller to pass in metadata from a previous deployment allows to re-establish
* the association between the artifacts of the same project.
*/
for (Iterator<? extends Metadata> it = metadatas.iterator(); it.hasNext(); ) {
Metadata metadata = it.next();
if (metadata instanceof VersionsMetadata) {
it.remove();
VersionsMetadata versionsMetadata = (VersionsMetadata) metadata;
processedVersions.put(versionsMetadata.getKey(), versionsMetadata);
}
}
}
@Override
public Collection<? extends Metadata> prepare(Collection<? extends Artifact> artifacts) {
return Collections.emptyList();
}
@Override
public Artifact transformArtifact(Artifact artifact) {
return artifact;
}
@Override
public Collection<? extends Metadata> finish(Collection<? extends Artifact> artifacts) {<FILL_FUNCTION_BODY>}
}
|
for (Artifact artifact : artifacts) {
Object key = VersionsMetadata.getKey(artifact);
if (processedVersions.get(key) == null) {
VersionsMetadata versionsMetadata = versions.get(key);
if (versionsMetadata == null) {
versionsMetadata = new VersionsMetadata(artifact, timestamp);
versions.put(key, versionsMetadata);
}
}
}
return versions.values();
| 492
| 112
| 604
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/artifact/FatArtifactTraverser.java
|
FatArtifactTraverser
|
traverseDependency
|
class FatArtifactTraverser implements DependencyTraverser {
public FatArtifactTraverser() {}
@Override
public boolean traverseDependency(Dependency dependency) {<FILL_FUNCTION_BODY>}
@Override
public DependencyTraverser deriveChildTraverser(DependencyCollectionContext context) {
requireNonNull(context, "context cannot be null");
return this;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (null == obj || !getClass().equals(obj.getClass())) {
return false;
}
return true;
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
|
requireNonNull(dependency, "dependency cannot be null");
String prop = dependency.getArtifact().getProperty(MavenArtifactProperties.INCLUDES_DEPENDENCIES, "");
return !Boolean.parseBoolean(prop);
| 199
| 63
| 262
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/relocation/DistributionManagementArtifactRelocationSource.java
|
DistributionManagementArtifactRelocationSource
|
relocatedTarget
|
class DistributionManagementArtifactRelocationSource implements MavenArtifactRelocationSource {
public static final String NAME = "distributionManagement";
private static final Logger LOGGER = LoggerFactory.getLogger(DistributionManagementArtifactRelocationSource.class);
@Override
public Artifact relocatedTarget(
RepositorySystemSession session, ArtifactDescriptorResult artifactDescriptorResult, Model model) {<FILL_FUNCTION_BODY>}
}
|
DistributionManagement distMgmt = model.getDistributionManagement();
if (distMgmt != null) {
Relocation relocation = distMgmt.getRelocation();
if (relocation != null) {
Artifact result = new RelocatedArtifact(
artifactDescriptorResult.getRequest().getArtifact(),
relocation.getGroupId(),
relocation.getArtifactId(),
null,
null,
relocation.getVersion(),
relocation.getMessage());
LOGGER.debug(
"The artifact {} has been relocated to {}: {}",
artifactDescriptorResult.getRequest().getArtifact(),
result,
relocation.getMessage());
return result;
}
}
return null;
| 108
| 191
| 299
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/relocation/UserPropertiesArtifactRelocationSource.java
|
Relocations
|
parseRelocations
|
class Relocations {
private final List<Relocation> relocations;
private Relocations(List<Relocation> relocations) {
this.relocations = relocations;
}
private Relocation getRelocation(Artifact artifact) {
return relocations.stream()
.filter(r -> r.predicate.test(artifact))
.findFirst()
.orElse(null);
}
}
private Relocations parseRelocations(RepositorySystemSession session) {<FILL_FUNCTION_BODY>
|
String relocationsEntries = (String) session.getConfigProperties().get(CONFIG_PROP_RELOCATIONS_ENTRIES);
if (relocationsEntries == null) {
return null;
}
String[] entries = relocationsEntries.split(",");
try (Stream<String> lines = Arrays.stream(entries)) {
List<Relocation> relocationList = lines.filter(
l -> l != null && !l.trim().isEmpty())
.map(l -> {
boolean global;
String splitExpr;
if (l.contains(">>")) {
global = true;
splitExpr = ">>";
} else if (l.contains(">")) {
global = false;
splitExpr = ">";
} else {
throw new IllegalArgumentException("Unrecognized entry: " + l);
}
String[] parts = l.split(splitExpr);
if (parts.length < 1) {
throw new IllegalArgumentException("Unrecognized entry: " + l);
}
Artifact s = parseArtifact(parts[0]);
Artifact t;
if (parts.length > 1) {
t = parseArtifact(parts[1]);
} else {
t = SENTINEL;
}
return new Relocation(global, s, t);
})
.collect(Collectors.toList());
LOGGER.info("Parsed {} user relocations", relocationList.size());
return new Relocations(relocationList);
}
| 143
| 387
| 530
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/scopes/Maven3ScopeManagerConfiguration.java
|
Maven3ScopeManagerConfiguration
|
buildResolutionScopes
|
class Maven3ScopeManagerConfiguration implements ScopeManagerConfiguration {
public static final Maven3ScopeManagerConfiguration INSTANCE = new Maven3ScopeManagerConfiguration();
public static final String DS_COMPILE = "compile";
public static final String DS_RUNTIME = "runtime";
public static final String DS_PROVIDED = "provided";
public static final String DS_SYSTEM = "system";
public static final String DS_TEST = "test";
public static final String RS_NONE = "none";
public static final String RS_MAIN_COMPILE = "main-compile";
public static final String RS_MAIN_COMPILE_PLUS_RUNTIME = "main-compilePlusRuntime";
public static final String RS_MAIN_RUNTIME = "main-runtime";
public static final String RS_MAIN_RUNTIME_PLUS_SYSTEM = "main-runtimePlusSystem";
public static final String RS_TEST_COMPILE = "test-compile";
public static final String RS_TEST_RUNTIME = "test-runtime";
private Maven3ScopeManagerConfiguration() {}
@Override
public String getId() {
return "Maven3";
}
@Override
public boolean isStrictDependencyScopes() {
return false;
}
@Override
public boolean isStrictResolutionScopes() {
return false;
}
@Override
public BuildScopeSource getBuildScopeSource() {
return new BuildScopeMatrixSource(
Collections.singletonList(CommonBuilds.PROJECT_PATH_MAIN),
Arrays.asList(CommonBuilds.BUILD_PATH_COMPILE, CommonBuilds.BUILD_PATH_RUNTIME),
CommonBuilds.MAVEN_TEST_BUILD_SCOPE);
}
@Override
public Collection<DependencyScope> buildDependencyScopes(InternalScopeManager internalScopeManager) {
ArrayList<DependencyScope> result = new ArrayList<>();
result.add(internalScopeManager.createDependencyScope(DS_COMPILE, true, all()));
result.add(internalScopeManager.createDependencyScope(
DS_RUNTIME, true, byBuildPath(CommonBuilds.BUILD_PATH_RUNTIME)));
result.add(internalScopeManager.createDependencyScope(
DS_PROVIDED,
false,
union(
byBuildPath(CommonBuilds.BUILD_PATH_COMPILE),
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME))));
result.add(internalScopeManager.createDependencyScope(
DS_TEST, false, byProjectPath(CommonBuilds.PROJECT_PATH_TEST)));
result.add(internalScopeManager.createSystemDependencyScope(
DS_SYSTEM, false, all(), ArtifactProperties.LOCAL_PATH));
return result;
}
@Override
public Collection<ResolutionScope> buildResolutionScopes(InternalScopeManager internalScopeManager) {<FILL_FUNCTION_BODY>}
// ===
public static void main(String... args) {
ScopeManagerDump.dump(Maven3ScopeManagerConfiguration.INSTANCE);
}
}
|
Collection<DependencyScope> allDependencyScopes = internalScopeManager.getDependencyScopeUniverse();
Collection<DependencyScope> nonTransitiveDependencyScopes =
allDependencyScopes.stream().filter(s -> !s.isTransitive()).collect(Collectors.toSet());
DependencyScope system =
internalScopeManager.getDependencyScope(DS_SYSTEM).orElse(null);
ArrayList<ResolutionScope> result = new ArrayList<>();
result.add(internalScopeManager.createResolutionScope(
RS_NONE,
InternalScopeManager.Mode.REMOVE,
Collections.emptySet(),
Collections.emptySet(),
allDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_COMPILE,
InternalScopeManager.Mode.ELIMINATE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_COMPILE),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_COMPILE_PLUS_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
byProjectPath(CommonBuilds.PROJECT_PATH_MAIN),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.emptySet(),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_RUNTIME_PLUS_SYSTEM,
InternalScopeManager.Mode.ELIMINATE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_TEST_COMPILE,
InternalScopeManager.Mode.ELIMINATE,
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_COMPILE),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_TEST_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
return result;
| 791
| 694
| 1,485
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/scopes/Maven4ScopeManagerConfiguration.java
|
Maven4ScopeManagerConfiguration
|
buildDependencyScopes
|
class Maven4ScopeManagerConfiguration implements ScopeManagerConfiguration {
public static final Maven4ScopeManagerConfiguration INSTANCE = new Maven4ScopeManagerConfiguration();
public static final String RS_NONE = "none";
public static final String RS_MAIN_COMPILE = "main-compile";
public static final String RS_MAIN_COMPILE_PLUS_RUNTIME = "main-compilePlusRuntime";
public static final String RS_MAIN_RUNTIME = "main-runtime";
public static final String RS_MAIN_RUNTIME_PLUS_SYSTEM = "main-runtimePlusSystem";
public static final String RS_TEST_COMPILE = "test-compile";
public static final String RS_TEST_RUNTIME = "test-runtime";
private Maven4ScopeManagerConfiguration() {}
@Override
public String getId() {
return "Maven4";
}
@Override
public boolean isStrictDependencyScopes() {
return false;
}
@Override
public boolean isStrictResolutionScopes() {
return false;
}
@Override
public BuildScopeSource getBuildScopeSource() {
return new BuildScopeMatrixSource(
Arrays.asList(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.PROJECT_PATH_TEST),
Arrays.asList(CommonBuilds.BUILD_PATH_COMPILE, CommonBuilds.BUILD_PATH_RUNTIME));
}
@Override
public Collection<org.eclipse.aether.scope.DependencyScope> buildDependencyScopes(
InternalScopeManager internalScopeManager) {<FILL_FUNCTION_BODY>}
@Override
public Collection<org.eclipse.aether.scope.ResolutionScope> buildResolutionScopes(
InternalScopeManager internalScopeManager) {
Collection<org.eclipse.aether.scope.DependencyScope> allDependencyScopes =
internalScopeManager.getDependencyScopeUniverse();
Collection<org.eclipse.aether.scope.DependencyScope> nonTransitiveDependencyScopes =
allDependencyScopes.stream().filter(s -> !s.isTransitive()).collect(Collectors.toSet());
org.eclipse.aether.scope.DependencyScope system = internalScopeManager
.getDependencyScope(DependencyScope.SYSTEM.id())
.orElse(null);
ArrayList<org.eclipse.aether.scope.ResolutionScope> result = new ArrayList<>();
result.add(internalScopeManager.createResolutionScope(
RS_NONE,
InternalScopeManager.Mode.REMOVE,
Collections.emptySet(),
Collections.emptySet(),
allDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_COMPILE,
InternalScopeManager.Mode.ELIMINATE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_COMPILE),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_COMPILE_PLUS_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
byProjectPath(CommonBuilds.PROJECT_PATH_MAIN),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_RUNTIME,
InternalScopeManager.Mode.REMOVE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.emptySet(),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_MAIN_RUNTIME_PLUS_SYSTEM,
InternalScopeManager.Mode.REMOVE,
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_TEST_COMPILE,
InternalScopeManager.Mode.ELIMINATE,
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_COMPILE),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
result.add(internalScopeManager.createResolutionScope(
RS_TEST_RUNTIME,
InternalScopeManager.Mode.ELIMINATE,
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME),
Collections.singletonList(system),
nonTransitiveDependencyScopes));
return result;
}
// ===
public static void main(String... args) {
ScopeManagerDump.dump(Maven4ScopeManagerConfiguration.INSTANCE);
}
}
|
ArrayList<org.eclipse.aether.scope.DependencyScope> result = new ArrayList<>();
result.add(internalScopeManager.createDependencyScope(
DependencyScope.COMPILE.id(), DependencyScope.COMPILE.isTransitive(), all()));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.RUNTIME.id(),
DependencyScope.RUNTIME.isTransitive(),
byBuildPath(CommonBuilds.BUILD_PATH_RUNTIME)));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.PROVIDED.id(),
DependencyScope.PROVIDED.isTransitive(),
union(
byBuildPath(CommonBuilds.BUILD_PATH_COMPILE),
select(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME))));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.TEST.id(),
DependencyScope.TEST.isTransitive(),
byProjectPath(CommonBuilds.PROJECT_PATH_TEST)));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.NONE.id(), DependencyScope.NONE.isTransitive(), Collections.emptySet()));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.COMPILE_ONLY.id(),
DependencyScope.COMPILE_ONLY.isTransitive(),
singleton(CommonBuilds.PROJECT_PATH_MAIN, CommonBuilds.BUILD_PATH_COMPILE)));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.TEST_RUNTIME.id(),
DependencyScope.TEST_RUNTIME.isTransitive(),
singleton(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_RUNTIME)));
result.add(internalScopeManager.createDependencyScope(
DependencyScope.TEST_ONLY.id(),
DependencyScope.TEST_ONLY.isTransitive(),
singleton(CommonBuilds.PROJECT_PATH_TEST, CommonBuilds.BUILD_PATH_COMPILE)));
// system
result.add(internalScopeManager.createSystemDependencyScope(
DependencyScope.SYSTEM.id(),
DependencyScope.SYSTEM.isTransitive(),
all(),
MavenArtifactProperties.LOCAL_PATH));
// == sanity check
if (result.size() != DependencyScope.values().length - 1) { // sans "undefined"
throw new IllegalStateException("Maven4 API dependency scope mismatch");
}
return result;
| 1,231
| 668
| 1,899
|
<no_super_class>
|
apache_maven
|
maven/maven-api-impl/src/main/java/org/apache/maven/internal/impl/resolver/type/DefaultTypeProvider.java
|
DefaultTypeProvider
|
types
|
class DefaultTypeProvider implements TypeProvider {
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Collection<Type> provides() {
return (Collection) types();
}
public Collection<DefaultType> types() {<FILL_FUNCTION_BODY>}
}
|
return Arrays.asList(
// Maven types
new DefaultType(Type.POM, Language.NONE, "pom", null, false),
new DefaultType(Type.BOM, Language.NONE, "pom", null, false),
new DefaultType(Type.MAVEN_PLUGIN, Language.JAVA_FAMILY, "jar", null, false, JavaPathType.CLASSES),
// Java types
new DefaultType(
Type.JAR, Language.JAVA_FAMILY, "jar", null, false, JavaPathType.CLASSES, JavaPathType.MODULES),
new DefaultType(Type.JAVADOC, Language.JAVA_FAMILY, "jar", "javadoc", false, JavaPathType.CLASSES),
new DefaultType(Type.JAVA_SOURCE, Language.JAVA_FAMILY, "jar", "sources", false),
new DefaultType(
Type.TEST_JAR,
Language.JAVA_FAMILY,
"jar",
"tests",
false,
JavaPathType.CLASSES,
JavaPathType.PATCH_MODULE),
new DefaultType(Type.MODULAR_JAR, Language.JAVA_FAMILY, "jar", null, false, JavaPathType.MODULES),
new DefaultType(Type.CLASSPATH_JAR, Language.JAVA_FAMILY, "jar", null, false, JavaPathType.CLASSES),
// j2ee types
new DefaultType("ejb", Language.JAVA_FAMILY, "jar", null, false, JavaPathType.CLASSES),
new DefaultType("ejb-client", Language.JAVA_FAMILY, "jar", "client", false, JavaPathType.CLASSES),
new DefaultType("war", Language.JAVA_FAMILY, "war", null, true),
new DefaultType("ear", Language.JAVA_FAMILY, "ear", null, true),
new DefaultType("rar", Language.JAVA_FAMILY, "rar", null, true),
new DefaultType("par", Language.JAVA_FAMILY, "par", null, true));
| 78
| 570
| 648
|
<no_super_class>
|
apache_maven
|
maven/maven-artifact/src/main/java/org/apache/maven/artifact/ArtifactUtils.java
|
ArtifactUtils
|
copyArtifacts
|
class ArtifactUtils {
public static boolean isSnapshot(String version) {
if (version != null) {
if (version.regionMatches(
true,
version.length() - Artifact.SNAPSHOT_VERSION.length(),
Artifact.SNAPSHOT_VERSION,
0,
Artifact.SNAPSHOT_VERSION.length())) {
return true;
} else {
return Artifact.VERSION_FILE_PATTERN.matcher(version).matches();
}
}
return false;
}
public static String toSnapshotVersion(String version) {
notBlank(version, "version can neither be null, empty nor blank");
int lastHyphen = version.lastIndexOf('-');
if (lastHyphen > 0) {
int prevHyphen = version.lastIndexOf('-', lastHyphen - 1);
if (prevHyphen > 0) {
Matcher m = Artifact.VERSION_FILE_PATTERN.matcher(version);
if (m.matches()) {
return m.group(1) + "-" + Artifact.SNAPSHOT_VERSION;
}
}
}
return version;
}
public static String versionlessKey(Artifact artifact) {
return versionlessKey(artifact.getGroupId(), artifact.getArtifactId());
}
public static String versionlessKey(String groupId, String artifactId) {
notBlank(groupId, "groupId can neither be null, empty nor blank");
notBlank(artifactId, "artifactId can neither be null, empty nor blank");
return groupId + ":" + artifactId;
}
public static String key(Artifact artifact) {
return key(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
}
public static String key(String groupId, String artifactId, String version) {
notBlank(groupId, "groupId can neither be null, empty nor blank");
notBlank(artifactId, "artifactId can neither be null, empty nor blank");
notBlank(version, "version can neither be null, empty nor blank");
return groupId + ":" + artifactId + ":" + version;
}
private static void notBlank(String str, String message) {
final int strLen = str != null ? str.length() : 0;
if (strLen > 0) {
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return;
}
}
}
throw new IllegalArgumentException(message);
}
public static Map<String, Artifact> artifactMapByVersionlessId(Collection<Artifact> artifacts) {
Map<String, Artifact> artifactMap = new LinkedHashMap<>();
if (artifacts != null) {
for (Artifact artifact : artifacts) {
artifactMap.put(versionlessKey(artifact), artifact);
}
}
return artifactMap;
}
public static Artifact copyArtifactSafe(Artifact artifact) {
return (artifact != null) ? copyArtifact(artifact) : null;
}
public static Artifact copyArtifact(Artifact artifact) {
VersionRange range = artifact.getVersionRange();
// For some reason with the introduction of MNG-1577 we have the case in Yoko where a depMan section has
// something like the following:
//
// <dependencyManagement>
// <dependencies>
// <!-- Yoko modules -->
// <dependency>
// <groupId>org.apache.yoko</groupId>
// <artifactId>yoko-core</artifactId>
// <version>${version}</version>
// </dependency>
// ...
//
// And the range is not set so we'll check here and set it. jvz.
if (range == null) {
range = VersionRange.createFromVersion(artifact.getVersion());
}
DefaultArtifact clone = new DefaultArtifact(
artifact.getGroupId(),
artifact.getArtifactId(),
range,
artifact.getScope(),
artifact.getType(),
artifact.getClassifier(),
artifact.getArtifactHandler(),
artifact.isOptional());
clone.setRelease(artifact.isRelease());
clone.setResolvedVersion(artifact.getVersion());
clone.setResolved(artifact.isResolved());
clone.setFile(artifact.getFile());
clone.setAvailableVersions(copyList(artifact.getAvailableVersions()));
if (artifact.getVersion() != null) {
clone.setBaseVersion(artifact.getBaseVersion());
}
clone.setDependencyFilter(artifact.getDependencyFilter());
clone.setDependencyTrail(copyList(artifact.getDependencyTrail()));
clone.setDownloadUrl(artifact.getDownloadUrl());
clone.setRepository(artifact.getRepository());
return clone;
}
/**
* Copy artifact to a collection.
*
* @param <T> the target collection type
* @param from an artifact collection
* @param to the target artifact collection
* @return <code>to</code> collection
*/
public static <T extends Collection<Artifact>> T copyArtifacts(Collection<Artifact> from, T to) {<FILL_FUNCTION_BODY>}
public static <K, T extends Map<K, Artifact>> T copyArtifacts(Map<K, ? extends Artifact> from, T to) {
if (from != null) {
for (Map.Entry<K, ? extends Artifact> entry : from.entrySet()) {
to.put(entry.getKey(), ArtifactUtils.copyArtifact(entry.getValue()));
}
}
return to;
}
private static <T> List<T> copyList(List<T> original) {
List<T> copy = null;
if (original != null) {
copy = new ArrayList<>();
if (!original.isEmpty()) {
copy.addAll(original);
}
}
return copy;
}
}
|
for (Artifact artifact : from) {
to.add(ArtifactUtils.copyArtifact(artifact));
}
return to;
| 1,567
| 38
| 1,605
|
<no_super_class>
|
apache_maven
|
maven/maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryPolicy.java
|
ArtifactRepositoryPolicy
|
merge
|
class ArtifactRepositoryPolicy {
public static final String UPDATE_POLICY_NEVER = "never";
public static final String UPDATE_POLICY_ALWAYS = "always";
public static final String UPDATE_POLICY_DAILY = "daily";
public static final String UPDATE_POLICY_INTERVAL = "interval";
public static final String CHECKSUM_POLICY_FAIL = "fail";
public static final String CHECKSUM_POLICY_WARN = "warn";
public static final String CHECKSUM_POLICY_IGNORE = "ignore";
public static final String DEFAULT_CHECKSUM_POLICY = CHECKSUM_POLICY_FAIL;
private boolean enabled;
private String updatePolicy;
private String checksumPolicy;
public ArtifactRepositoryPolicy() {
this(true, null, null);
}
public ArtifactRepositoryPolicy(ArtifactRepositoryPolicy policy) {
this(policy.isEnabled(), policy.getUpdatePolicy(), policy.getChecksumPolicy());
}
public ArtifactRepositoryPolicy(boolean enabled, String updatePolicy, String checksumPolicy) {
this.enabled = enabled;
if (updatePolicy == null) {
updatePolicy = UPDATE_POLICY_DAILY;
}
this.updatePolicy = updatePolicy;
if (checksumPolicy == null) {
checksumPolicy = DEFAULT_CHECKSUM_POLICY;
}
this.checksumPolicy = checksumPolicy;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setUpdatePolicy(String updatePolicy) {
if (updatePolicy != null) {
this.updatePolicy = updatePolicy;
}
}
public void setChecksumPolicy(String checksumPolicy) {
if (checksumPolicy != null) {
this.checksumPolicy = checksumPolicy;
}
}
public boolean isEnabled() {
return enabled;
}
public String getUpdatePolicy() {
return updatePolicy;
}
public String getChecksumPolicy() {
return checksumPolicy;
}
public boolean checkOutOfDate(Date lastModified) {
boolean checkForUpdates = false;
if (UPDATE_POLICY_ALWAYS.equals(updatePolicy)) {
checkForUpdates = true;
} else if (UPDATE_POLICY_DAILY.equals(updatePolicy)) {
// Get local midnight boundary
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (cal.getTime().after(lastModified)) {
checkForUpdates = true;
}
} else if (updatePolicy.startsWith(UPDATE_POLICY_INTERVAL)) {
String s = updatePolicy.substring(UPDATE_POLICY_INTERVAL.length() + 1);
int minutes = Integer.parseInt(s);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -minutes);
if (cal.getTime().after(lastModified)) {
checkForUpdates = true;
}
}
// else assume "never"
return checkForUpdates;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder(64);
buffer.append("{enabled=");
buffer.append(enabled);
buffer.append(", checksums=");
buffer.append(checksumPolicy);
buffer.append(", updates=");
buffer.append(updatePolicy);
buffer.append('}');
return buffer.toString();
}
public void merge(ArtifactRepositoryPolicy policy) {<FILL_FUNCTION_BODY>}
private int ordinalOfCksumPolicy(String policy) {
if (ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL.equals(policy)) {
return 2;
} else if (ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE.equals(policy)) {
return 0;
} else {
return 1;
}
}
@SuppressWarnings("checkstyle:magicnumber")
private int ordinalOfUpdatePolicy(String policy) {
if (ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY.equals(policy)) {
return 1440;
} else if (ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS.equals(policy)) {
return 0;
} else if (policy != null && policy.startsWith(ArtifactRepositoryPolicy.UPDATE_POLICY_INTERVAL)) {
String s = policy.substring(UPDATE_POLICY_INTERVAL.length() + 1);
return Integer.parseInt(s);
} else {
return Integer.MAX_VALUE;
}
}
}
|
if (policy != null && policy.isEnabled()) {
setEnabled(true);
if (ordinalOfCksumPolicy(policy.getChecksumPolicy()) < ordinalOfCksumPolicy(getChecksumPolicy())) {
setChecksumPolicy(policy.getChecksumPolicy());
}
if (ordinalOfUpdatePolicy(policy.getUpdatePolicy()) < ordinalOfUpdatePolicy(getUpdatePolicy())) {
setUpdatePolicy(policy.getUpdatePolicy());
}
}
| 1,313
| 128
| 1,441
|
<no_super_class>
|
apache_maven
|
maven/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/MultipleArtifactsNotFoundException.java
|
MultipleArtifactsNotFoundException
|
constructMessage
|
class MultipleArtifactsNotFoundException extends ArtifactResolutionException {
private static final String LS = System.lineSeparator();
private final List<Artifact> resolvedArtifacts;
private final List<Artifact> missingArtifacts;
/**
* @param originatingArtifact the artifact that was being resolved
* @param missingArtifacts artifacts that could not be resolved
* @param remoteRepositories remote repositories where the missing artifacts were not found
* @deprecated use {@link #MultipleArtifactsNotFoundException(Artifact, List, List, List)}
*/
@Deprecated
public MultipleArtifactsNotFoundException(
Artifact originatingArtifact,
List<Artifact> missingArtifacts,
List<ArtifactRepository> remoteRepositories) {
this(originatingArtifact, new ArrayList<>(), missingArtifacts, remoteRepositories);
}
/**
* Create an instance of the exception with all required information.
*
* @param originatingArtifact the artifact that was being resolved
* @param resolvedArtifacts artifacts that could be resolved
* @param missingArtifacts artifacts that could not be resolved
* @param remoteRepositories remote repositories where the missing artifacts were not found
*/
public MultipleArtifactsNotFoundException(
Artifact originatingArtifact,
List<Artifact> resolvedArtifacts,
List<Artifact> missingArtifacts,
List<ArtifactRepository> remoteRepositories) {
super(constructMessage(missingArtifacts), originatingArtifact, remoteRepositories);
this.resolvedArtifacts = resolvedArtifacts;
this.missingArtifacts = missingArtifacts;
}
/**
* artifacts that could be resolved
*
* @return {@link List} of {@link Artifact}
*/
public List<Artifact> getResolvedArtifacts() {
return resolvedArtifacts;
}
/**
* artifacts that could NOT be resolved
*
* @return {@link List} of {@link Artifact}
*/
public List<Artifact> getMissingArtifacts() {
return missingArtifacts;
}
private static String constructMessage(List<Artifact> artifacts) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder(256);
buffer.append("Missing:").append(LS);
buffer.append("----------").append(LS);
int counter = 0;
for (Artifact artifact : artifacts) {
String message = (++counter) + ") " + artifact.getId();
buffer.append(constructMissingArtifactMessage(
message,
" ",
artifact.getGroupId(),
artifact.getArtifactId(),
artifact.getVersion(),
artifact.getType(),
artifact.getClassifier(),
artifact.getDownloadUrl(),
artifact.getDependencyTrail()));
}
buffer.append("----------").append(LS);
int size = artifacts.size();
buffer.append(size).append(" required artifact");
if (size > 1) {
buffer.append("s are");
} else {
buffer.append(" is");
}
buffer.append(" missing.").append(LS).append(LS).append("for artifact: ");
return buffer.toString();
| 589
| 267
| 856
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, List<org.apache.maven.artifact.repository.ArtifactRepository>, List<java.lang.String>, java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Throwable) ,public void <init>(java.lang.String, org.apache.maven.artifact.Artifact) ,public void <init>(java.lang.String, org.apache.maven.artifact.Artifact, List<org.apache.maven.artifact.repository.ArtifactRepository>) ,public void <init>(java.lang.String, org.apache.maven.artifact.Artifact, java.lang.Throwable) ,public void <init>(java.lang.String, org.apache.maven.artifact.Artifact, List<org.apache.maven.artifact.repository.ArtifactRepository>, java.lang.Throwable) <variables>
|
apache_maven
|
maven/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java
|
CombinationItem
|
compareTo
|
class CombinationItem implements Item {
StringItem stringPart;
Item digitPart;
CombinationItem(String value) {
int index = 0;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (Character.isDigit(c)) {
index = i;
break;
}
}
stringPart = new StringItem(value.substring(0, index), true);
digitPart = parseItem(true, value.substring(index));
}
@Override
public int compareTo(Item item) {<FILL_FUNCTION_BODY>}
public StringItem getStringPart() {
return stringPart;
}
public Item getDigitPart() {
return digitPart;
}
@Override
public int getType() {
return COMBINATION_ITEM;
}
@Override
public boolean isNull() {
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CombinationItem that = (CombinationItem) o;
return Objects.equals(stringPart, that.stringPart) && Objects.equals(digitPart, that.digitPart);
}
@Override
public int hashCode() {
return Objects.hash(stringPart, digitPart);
}
@Override
public String toString() {
return stringPart.toString() + digitPart.toString();
}
}
|
if (item == null) {
// 1-rc1 < 1, 1-ga1 > 1
return stringPart.compareTo(item);
}
int result = 0;
switch (item.getType()) {
case INT_ITEM:
case LONG_ITEM:
case BIGINTEGER_ITEM:
return -1;
case STRING_ITEM:
result = stringPart.compareTo(item);
if (result == 0) {
// X1 > X
return 1;
}
return result;
case LIST_ITEM:
return -1;
case COMBINATION_ITEM:
result = stringPart.compareTo(((CombinationItem) item).getStringPart());
if (result == 0) {
return digitPart.compareTo(((CombinationItem) item).getDigitPart());
}
return result;
default:
return 0;
}
| 429
| 247
| 676
|
<no_super_class>
|
apache_maven
|
maven/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/DefaultArtifactVersion.java
|
DefaultArtifactVersion
|
parseVersion
|
class DefaultArtifactVersion implements ArtifactVersion {
private Integer majorVersion;
private Integer minorVersion;
private Integer incrementalVersion;
private Integer buildNumber;
private String qualifier;
private ComparableVersion comparable;
public DefaultArtifactVersion(String version) {
parseVersion(version);
}
@Override
public int hashCode() {
return 11 + comparable.hashCode();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ArtifactVersion)) {
return false;
}
return compareTo((ArtifactVersion) other) == 0;
}
public int compareTo(ArtifactVersion otherVersion) {
if (otherVersion instanceof DefaultArtifactVersion) {
return this.comparable.compareTo(((DefaultArtifactVersion) otherVersion).comparable);
} else {
return compareTo(new DefaultArtifactVersion(otherVersion.toString()));
}
}
public int getMajorVersion() {
return majorVersion != null ? majorVersion : 0;
}
public int getMinorVersion() {
return minorVersion != null ? minorVersion : 0;
}
public int getIncrementalVersion() {
return incrementalVersion != null ? incrementalVersion : 0;
}
public int getBuildNumber() {
return buildNumber != null ? buildNumber : 0;
}
public String getQualifier() {
return qualifier;
}
public final void parseVersion(String version) {<FILL_FUNCTION_BODY>}
private static boolean isDigits(String cs) {
if (cs == null || cs.isEmpty()) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
private static Integer getNextIntegerToken(String s) {
if ((s.length() > 1) && s.startsWith("0")) {
return null;
}
return tryParseInt(s);
}
private static Integer tryParseInt(String s) {
// for performance, check digits instead of relying later on catching NumberFormatException
if (!isDigits(s)) {
return null;
}
try {
long longValue = Long.parseLong(s);
if (longValue > Integer.MAX_VALUE) {
return null;
}
return (int) longValue;
} catch (NumberFormatException e) {
// should never happen since checked isDigits(s) before
return null;
}
}
@Override
public String toString() {
return comparable.toString();
}
}
|
comparable = new ComparableVersion(version);
int index = version.indexOf('-');
String part1;
String part2 = null;
if (index < 0) {
part1 = version;
} else {
part1 = version.substring(0, index);
part2 = version.substring(index + 1);
}
if (part2 != null) {
if (part2.length() == 1 || !part2.startsWith("0")) {
buildNumber = tryParseInt(part2);
if (buildNumber == null) {
qualifier = part2;
}
} else {
qualifier = part2;
}
}
if ((!part1.contains(".")) && !part1.startsWith("0")) {
majorVersion = tryParseInt(part1);
if (majorVersion == null) {
// qualifier is the whole version, including "-"
qualifier = version;
buildNumber = null;
}
} else {
boolean fallback = false;
String[] tok = part1.split("\\.");
int idx = 0;
if (idx < tok.length) {
majorVersion = getNextIntegerToken(tok[idx++]);
if (majorVersion == null) {
fallback = true;
}
} else {
fallback = true;
}
if (idx < tok.length) {
minorVersion = getNextIntegerToken(tok[idx++]);
if (minorVersion == null) {
fallback = true;
}
}
if (idx < tok.length) {
incrementalVersion = getNextIntegerToken(tok[idx++]);
if (incrementalVersion == null) {
fallback = true;
}
}
if (idx < tok.length) {
qualifier = tok[idx++];
fallback = isDigits(qualifier);
}
// string tokenizer won't detect these and ignores them
if (part1.contains("..") || part1.startsWith(".") || part1.endsWith(".")) {
fallback = true;
}
if (fallback) {
// qualifier is the whole version, including "-"
qualifier = version;
majorVersion = null;
minorVersion = null;
incrementalVersion = null;
buildNumber = null;
}
}
| 751
| 612
| 1,363
|
<no_super_class>
|
apache_maven
|
maven/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/Restriction.java
|
Restriction
|
containsVersion
|
class Restriction {
private final ArtifactVersion lowerBound;
private final boolean lowerBoundInclusive;
private final ArtifactVersion upperBound;
private final boolean upperBoundInclusive;
public static final Restriction EVERYTHING = new Restriction(null, false, null, false);
public Restriction(
ArtifactVersion lowerBound,
boolean lowerBoundInclusive,
ArtifactVersion upperBound,
boolean upperBoundInclusive) {
this.lowerBound = lowerBound;
this.lowerBoundInclusive = lowerBoundInclusive;
this.upperBound = upperBound;
this.upperBoundInclusive = upperBoundInclusive;
}
public ArtifactVersion getLowerBound() {
return lowerBound;
}
public boolean isLowerBoundInclusive() {
return lowerBoundInclusive;
}
public ArtifactVersion getUpperBound() {
return upperBound;
}
public boolean isUpperBoundInclusive() {
return upperBoundInclusive;
}
public boolean containsVersion(ArtifactVersion version) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = 13;
if (lowerBound == null) {
result += 1;
} else {
result += lowerBound.hashCode();
}
result *= lowerBoundInclusive ? 1 : 2;
if (upperBound == null) {
result -= 3;
} else {
result -= upperBound.hashCode();
}
result *= upperBoundInclusive ? 2 : 3;
return result;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Restriction)) {
return false;
}
Restriction restriction = (Restriction) other;
if (lowerBound != null) {
if (!lowerBound.equals(restriction.lowerBound)) {
return false;
}
} else if (restriction.lowerBound != null) {
return false;
}
if (lowerBoundInclusive != restriction.lowerBoundInclusive) {
return false;
}
if (upperBound != null) {
if (!upperBound.equals(restriction.upperBound)) {
return false;
}
} else if (restriction.upperBound != null) {
return false;
}
return upperBoundInclusive == restriction.upperBoundInclusive;
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(isLowerBoundInclusive() ? '[' : '(');
if (getLowerBound() != null) {
buf.append(getLowerBound().toString());
}
buf.append(',');
if (getUpperBound() != null) {
buf.append(getUpperBound().toString());
}
buf.append(isUpperBoundInclusive() ? ']' : ')');
return buf.toString();
}
}
|
if (lowerBound != null) {
int comparison = lowerBound.compareTo(version);
if ((comparison == 0) && !lowerBoundInclusive) {
return false;
}
if (comparison > 0) {
return false;
}
}
if (upperBound != null) {
int comparison = upperBound.compareTo(version);
if ((comparison == 0) && !upperBoundInclusive) {
return false;
}
return comparison >= 0;
}
return true;
| 786
| 140
| 926
|
<no_super_class>
|
apache_maven
|
maven/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblem.java
|
DefaultProblem
|
getMessage
|
class DefaultProblem implements Problem {
private final String source;
private final int lineNumber;
private final int columnNumber;
private final String message;
private final Exception exception;
private final Severity severity;
/**
* Creates a new problem with the specified message and exception.
* Either {@code message} or {@code exception} is required
*
* @param message The message describing the problem, may be {@code null}.
* @param severity The severity level of the problem, may be {@code null} to default to
* {@link org.apache.maven.building.Problem.Severity#ERROR}.
* @param source A hint about the source of the problem like a file path, may be {@code null}.
* @param lineNumber The one-based index of the line containing the problem or {@code -1} if unknown.
* @param columnNumber The one-based index of the column containing the problem or {@code -1} if unknown.
* @param exception The exception that caused this problem, may be {@code null}.
*/
DefaultProblem(
String message, Severity severity, String source, int lineNumber, int columnNumber, Exception exception) {
this.message = message;
this.severity = (severity != null) ? severity : Severity.ERROR;
this.source = (source != null) ? source : "";
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.exception = exception;
}
public String getSource() {
return source;
}
public int getLineNumber() {
return lineNumber;
}
public int getColumnNumber() {
return columnNumber;
}
public String getLocation() {
StringBuilder buffer = new StringBuilder(256);
if (!getSource().isEmpty()) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(getSource());
}
if (getLineNumber() > 0) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append("line ").append(getLineNumber());
}
if (getColumnNumber() > 0) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append("column ").append(getColumnNumber());
}
return buffer.toString();
}
public Exception getException() {
return exception;
}
public String getMessage() {<FILL_FUNCTION_BODY>}
public Severity getSeverity() {
return severity;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder(128);
buffer.append('[').append(getSeverity()).append("] ");
buffer.append(getMessage());
String location = getLocation();
if (!location.isEmpty()) {
buffer.append(" @ ");
buffer.append(location);
}
return buffer.toString();
}
}
|
String msg;
if (message != null && !message.isEmpty()) {
msg = message;
} else {
msg = exception.getMessage();
if (msg == null) {
msg = "";
}
}
return msg;
| 782
| 70
| 852
|
<no_super_class>
|
apache_maven
|
maven/maven-builder-support/src/main/java/org/apache/maven/building/DefaultProblemCollector.java
|
DefaultProblemCollector
|
add
|
class DefaultProblemCollector implements ProblemCollector {
private final List<Problem> problems;
private String source;
DefaultProblemCollector(List<Problem> problems) {
this.problems = (problems != null) ? problems : new ArrayList<>();
}
@Override
public List<Problem> getProblems() {
return problems;
}
@Override
public void setSource(String source) {
this.source = source;
}
@Override
public void add(Problem.Severity severity, String message, int line, int column, Exception cause) {<FILL_FUNCTION_BODY>}
}
|
Problem problem = new DefaultProblem(message, severity, source, line, column, cause);
problems.add(problem);
| 172
| 35
| 207
|
<no_super_class>
|
apache_maven
|
maven/maven-builder-support/src/main/java/org/apache/maven/building/FileSource.java
|
FileSource
|
equals
|
class FileSource implements Source {
private final Path path;
private final int hashCode;
/**
* Creates a new source backed by the specified file.
*
* @param file The file, must not be {@code null}.
* @deprecated Use {@link #FileSource(Path)} instead.
*/
@Deprecated
public FileSource(File file) {
this(Objects.requireNonNull(file, "file cannot be null").toPath());
}
/**
* Creates a new source backed by the specified file.
*
* @param path The file, must not be {@code null}.
* @since 4.0.0
*/
public FileSource(Path path) {
this.path = Objects.requireNonNull(path, "path cannot be null").toAbsolutePath();
this.hashCode = Objects.hash(path);
}
@Override
public InputStream getInputStream() throws IOException {
return Files.newInputStream(path);
}
@Override
public String getLocation() {
return path.toString();
}
/**
* Gets the file of this source.
*
* @return The underlying file, never {@code null}.
* @deprecated Use {@link #getPath()} instead.
*/
@Deprecated
public File getFile() {
return path.toFile();
}
/**
* Gets the file of this source.
*
* @return The underlying file, never {@code null}.
* @since 4.0.0
*/
public Path getPath() {
return path;
}
@Override
public String toString() {
return getLocation();
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!FileSource.class.equals(obj.getClass())) {
return false;
}
FileSource other = (FileSource) obj;
return this.path.equals(other.path);
| 481
| 90
| 571
|
<no_super_class>
|
apache_maven
|
maven/maven-builder-support/src/main/java/org/apache/maven/building/StringSource.java
|
StringSource
|
equals
|
class StringSource implements Source {
private final String content;
private final String location;
private final int hashCode;
/**
* Creates a new source backed by the specified string.
*
* @param content The String representation, may be empty or {@code null}.
*/
public StringSource(CharSequence content) {
this(content, null);
}
/**
* Creates a new source backed by the specified string.
*
* @param content The String representation, may be empty or {@code null}.
* @param location The location to report for this use, may be {@code null}.
*/
public StringSource(CharSequence content, String location) {
this.content = (content != null) ? content.toString() : "";
this.location = (location != null) ? location : "(memory)";
this.hashCode = this.content.hashCode();
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
}
@Override
public String getLocation() {
return location;
}
/**
* Gets the content of this source.
*
* @return The underlying character stream, never {@code null}.
*/
public String getContent() {
return content;
}
@Override
public String toString() {
return getLocation();
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!StringSource.class.equals(obj.getClass())) {
return false;
}
StringSource other = (StringSource) obj;
return this.content.equals(other.content);
| 412
| 90
| 502
|
<no_super_class>
|
apache_maven
|
maven/maven-builder-support/src/main/java/org/apache/maven/building/UrlSource.java
|
UrlSource
|
equals
|
class UrlSource implements Source {
private final URL url;
private final int hashCode;
/**
* Creates a new source backed by the specified URL.
*
* @param url The file, must not be {@code null}.
*/
public UrlSource(URL url) {
this.url = Objects.requireNonNull(url, "url cannot be null");
this.hashCode = Objects.hashCode(url);
}
@Override
public InputStream getInputStream() throws IOException {
return url.openStream();
}
@Override
public String getLocation() {
return url.toString();
}
/**
* Gets the URL of this source.
*
* @return The underlying URL, never {@code null}.
*/
public URL getUrl() {
return url;
}
@Override
public String toString() {
return getLocation();
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!UrlSource.class.equals(obj.getClass())) {
return false;
}
UrlSource other = (UrlSource) obj;
return Objects.equals(url.toExternalForm(), other.url.toExternalForm());
| 288
| 100
| 388
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/DefaultArtifactFilterManager.java
|
DefaultArtifactFilterManager
|
getCoreArtifactExcludes
|
class DefaultArtifactFilterManager implements ArtifactFilterManager {
// this is a live injected collection
protected final List<ArtifactFilterManagerDelegate> delegates;
protected Set<String> excludedArtifacts;
private final Set<String> coreArtifacts;
@Inject
public DefaultArtifactFilterManager(List<ArtifactFilterManagerDelegate> delegates, CoreExports coreExports) {
this.delegates = delegates;
this.coreArtifacts = coreExports.getExportedArtifacts();
}
private synchronized Set<String> getExcludedArtifacts() {
if (excludedArtifacts == null) {
excludedArtifacts = new LinkedHashSet<>(coreArtifacts);
}
return excludedArtifacts;
}
/**
* Returns the artifact filter for the core + extension artifacts.
*
* @see org.apache.maven.ArtifactFilterManager#getArtifactFilter()
*/
public ArtifactFilter getArtifactFilter() {
Set<String> excludes = new LinkedHashSet<>(getExcludedArtifacts());
for (ArtifactFilterManagerDelegate delegate : delegates) {
delegate.addExcludes(excludes);
}
return new ExclusionSetFilter(excludes);
}
/**
* Returns the artifact filter for the standard core artifacts.
*
* @see org.apache.maven.ArtifactFilterManager#getCoreArtifactFilter()
*/
public ArtifactFilter getCoreArtifactFilter() {
return new ExclusionSetFilter(getCoreArtifactExcludes());
}
public void excludeArtifact(String artifactId) {
getExcludedArtifacts().add(artifactId);
}
public Set<String> getCoreArtifactExcludes() {<FILL_FUNCTION_BODY>}
}
|
Set<String> excludes = new LinkedHashSet<>(coreArtifacts);
for (ArtifactFilterManagerDelegate delegate : delegates) {
delegate.addCoreExcludes(excludes);
}
return excludes;
| 461
| 61
| 522
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/DefaultProjectDependenciesResolver.java
|
DefaultProjectDependenciesResolver
|
resolveImpl
|
class DefaultProjectDependenciesResolver implements ProjectDependenciesResolver {
private final RepositorySystem repositorySystem;
private final ResolutionErrorHandler resolutionErrorHandler;
@Inject
public DefaultProjectDependenciesResolver(
RepositorySystem repositorySystem, ResolutionErrorHandler resolutionErrorHandler) {
this.repositorySystem = repositorySystem;
this.resolutionErrorHandler = resolutionErrorHandler;
}
public Set<Artifact> resolve(MavenProject project, Collection<String> scopesToResolve, MavenSession session)
throws ArtifactResolutionException, ArtifactNotFoundException {
return resolve(Collections.singleton(project), scopesToResolve, session);
}
public Set<Artifact> resolve(
MavenProject project,
Collection<String> scopesToCollect,
Collection<String> scopesToResolve,
MavenSession session)
throws ArtifactResolutionException, ArtifactNotFoundException {
Set<MavenProject> mavenProjects = Collections.singleton(project);
return resolveImpl(
mavenProjects, scopesToCollect, scopesToResolve, session, getIgnorableArtifacts(mavenProjects));
}
public Set<Artifact> resolve(
Collection<? extends MavenProject> projects, Collection<String> scopesToResolve, MavenSession session)
throws ArtifactResolutionException, ArtifactNotFoundException {
return resolveImpl(projects, null, scopesToResolve, session, getIgnorableArtifacts(projects));
}
public Set<Artifact> resolve(
MavenProject project,
Collection<String> scopesToCollect,
Collection<String> scopesToResolve,
MavenSession session,
Set<Artifact> ignorableArtifacts)
throws ArtifactResolutionException, ArtifactNotFoundException {
return resolveImpl(
Collections.singleton(project),
scopesToCollect,
scopesToResolve,
session,
getIgnorableArtifacts(ignorableArtifacts));
}
private Set<Artifact> resolveImpl(
Collection<? extends MavenProject> projects,
Collection<String> scopesToCollect,
Collection<String> scopesToResolve,
MavenSession session,
Set<String> projectIds)
throws ArtifactResolutionException, ArtifactNotFoundException {<FILL_FUNCTION_BODY>}
private Set<String> getIgnorableArtifacts(Collection<? extends MavenProject> projects) {
Set<String> projectIds = new HashSet<>(projects.size() * 2);
for (MavenProject p : projects) {
String key = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion());
projectIds.add(key);
}
return projectIds;
}
private Set<String> getIgnorableArtifacts(Iterable<Artifact> artifactIterable) {
Set<String> projectIds = new HashSet<>();
for (Artifact artifact : artifactIterable) {
String key = ArtifactUtils.key(artifact);
projectIds.add(key);
}
return projectIds;
}
}
|
Set<Artifact> resolved = new LinkedHashSet<>();
if (projects == null || projects.isEmpty()) {
return resolved;
}
if ((scopesToCollect == null || scopesToCollect.isEmpty())
&& (scopesToResolve == null || scopesToResolve.isEmpty())) {
return resolved;
}
/*
Logic for transitive global exclusions
List<String> exclusions = new ArrayList<String>();
for ( Dependency d : project.getDependencies() )
{
if ( d.getExclusions() != null )
{
for ( Exclusion e : d.getExclusions() )
{
exclusions.add( e.getGroupId() + ":" + e.getArtifactId() );
}
}
}
ArtifactFilter scopeFilter = new ScopeArtifactFilter( scope );
ArtifactFilter filter;
if ( ! exclusions.isEmpty() )
{
filter = new AndArtifactFilter( Arrays.asList( new ArtifactFilter[]{
new ExcludesArtifactFilter( exclusions ), scopeFilter } ) );
}
else
{
filter = scopeFilter;
}
*/
CumulativeScopeArtifactFilter resolutionScopeFilter = new CumulativeScopeArtifactFilter(scopesToResolve);
CumulativeScopeArtifactFilter collectionScopeFilter = new CumulativeScopeArtifactFilter(scopesToCollect);
collectionScopeFilter = new CumulativeScopeArtifactFilter(collectionScopeFilter, resolutionScopeFilter);
ArtifactResolutionRequest request = new ArtifactResolutionRequest()
.setResolveRoot(false)
.setResolveTransitively(true)
.setCollectionFilter(collectionScopeFilter)
.setResolutionFilter(resolutionScopeFilter)
.setLocalRepository(session.getLocalRepository())
.setOffline(session.isOffline())
.setForceUpdate(session.getRequest().isUpdateSnapshots());
request.setServers(session.getRequest().getServers());
request.setMirrors(session.getRequest().getMirrors());
request.setProxies(session.getRequest().getProxies());
for (MavenProject project : projects) {
request.setArtifact(new ProjectArtifact(project));
request.setArtifactDependencies(project.getDependencyArtifacts());
request.setManagedVersionMap(project.getManagedVersionMap());
request.setRemoteRepositories(project.getRemoteArtifactRepositories());
ArtifactResolutionResult result = repositorySystem.resolve(request);
try {
resolutionErrorHandler.throwErrors(request, result);
} catch (MultipleArtifactsNotFoundException e) {
Collection<Artifact> missing = new HashSet<>(e.getMissingArtifacts());
for (Iterator<Artifact> it = missing.iterator(); it.hasNext(); ) {
String key = ArtifactUtils.key(it.next());
if (projectIds.contains(key)) {
it.remove();
}
}
if (!missing.isEmpty()) {
throw e;
}
}
resolved.addAll(result.getArtifacts());
}
return resolved;
| 788
| 818
| 1,606
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/ArtifactStatus.java
|
ArtifactStatus
|
valueOf
|
class ArtifactStatus implements Comparable<ArtifactStatus> {
/**
* No trust - no information about status.
*/
public static final ArtifactStatus NONE = new ArtifactStatus("none", 0);
/**
* No trust - information was generated with defaults.
*/
public static final ArtifactStatus GENERATED = new ArtifactStatus("generated", 1);
/**
* Low trust - was converted from the Maven 1.x repository.
*/
public static final ArtifactStatus CONVERTED = new ArtifactStatus("converted", 2);
/**
* Moderate trust - it was deployed directly from a partner.
*/
public static final ArtifactStatus PARTNER = new ArtifactStatus("partner", 3);
/**
* Moderate trust - it was deployed directly by a user.
*/
public static final ArtifactStatus DEPLOYED = new ArtifactStatus("deployed", 4);
/**
* Trusted, as it has had its data verified by hand.
*/
public static final ArtifactStatus VERIFIED = new ArtifactStatus("verified", 5);
private final int rank;
private final String key;
private static Map<String, ArtifactStatus> map;
private ArtifactStatus(String key, int rank) {
this.rank = rank;
this.key = key;
if (map == null) {
map = new HashMap<>();
}
map.put(key, this);
}
public static ArtifactStatus valueOf(String status) {<FILL_FUNCTION_BODY>}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ArtifactStatus that = (ArtifactStatus) o;
return rank == that.rank;
}
public int hashCode() {
return rank;
}
public String toString() {
return key;
}
public int compareTo(ArtifactStatus s) {
return rank - s.rank;
}
}
|
ArtifactStatus retVal = null;
if (status != null) {
retVal = map.get(status);
}
return retVal != null ? retVal : NONE;
| 555
| 54
| 609
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/deployer/DefaultArtifactDeployer.java
|
DefaultArtifactDeployer
|
deploy
|
class DefaultArtifactDeployer extends AbstractLogEnabled implements ArtifactDeployer {
@Inject
private RepositorySystem repoSystem;
@Inject
private LegacySupport legacySupport;
private Map<Object, MergeableMetadata> relatedMetadata = new ConcurrentHashMap<>();
/**
* @deprecated we want to use the artifact method only, and ensure artifact.file is set
* correctly.
*/
@Deprecated
public void deploy(
String basedir,
String finalName,
Artifact artifact,
ArtifactRepository deploymentRepository,
ArtifactRepository localRepository)
throws ArtifactDeploymentException {
String extension = artifact.getArtifactHandler().getExtension();
File source = new File(basedir, finalName + "." + extension);
deploy(source, artifact, deploymentRepository, localRepository);
}
public void deploy(
File source, Artifact artifact, ArtifactRepository deploymentRepository, ArtifactRepository localRepository)
throws ArtifactDeploymentException {<FILL_FUNCTION_BODY>}
}
|
RepositorySystemSession session =
LegacyLocalRepositoryManager.overlay(localRepository, legacySupport.getRepositorySession(), repoSystem);
DeployRequest request = new DeployRequest();
request.setTrace(RequestTrace.newChild(null, legacySupport.getSession().getCurrentProject()));
org.eclipse.aether.artifact.Artifact mainArtifact = RepositoryUtils.toArtifact(artifact);
mainArtifact = mainArtifact.setFile(source);
request.addArtifact(mainArtifact);
String versionKey = artifact.getGroupId() + ':' + artifact.getArtifactId();
String snapshotKey = null;
if (artifact.isSnapshot()) {
snapshotKey = versionKey + ':' + artifact.getBaseVersion();
request.addMetadata(relatedMetadata.get(snapshotKey));
}
request.addMetadata(relatedMetadata.get(versionKey));
for (ArtifactMetadata metadata : artifact.getMetadataList()) {
if (metadata instanceof ProjectArtifactMetadata) {
org.eclipse.aether.artifact.Artifact pomArtifact = new SubArtifact(mainArtifact, "", "pom");
pomArtifact = pomArtifact.setFile(((ProjectArtifactMetadata) metadata).getFile());
request.addArtifact(pomArtifact);
} else if (metadata instanceof SnapshotArtifactRepositoryMetadata
|| metadata instanceof ArtifactRepositoryMetadata) {
// eaten, handled by repo system
} else {
request.addMetadata(new MetadataBridge(metadata));
}
}
RemoteRepository remoteRepo = RepositoryUtils.toRepo(deploymentRepository);
/*
* NOTE: This provides backward-compat with maven-deploy-plugin:2.4 which bypasses the repository factory when
* using an alternative deployment location.
*/
if (deploymentRepository instanceof DefaultArtifactRepository
&& deploymentRepository.getAuthentication() == null) {
RemoteRepository.Builder builder = new RemoteRepository.Builder(remoteRepo);
builder.setAuthentication(session.getAuthenticationSelector().getAuthentication(remoteRepo));
builder.setProxy(session.getProxySelector().getProxy(remoteRepo));
remoteRepo = builder.build();
}
request.setRepository(remoteRepo);
DeployResult result;
try {
result = repoSystem.deploy(session, request);
} catch (DeploymentException e) {
throw new ArtifactDeploymentException(e.getMessage(), e);
}
for (Object metadata : result.getMetadata()) {
if (metadata.getClass().getName().endsWith(".internal.VersionsMetadata")) {
relatedMetadata.put(versionKey, (MergeableMetadata) metadata);
}
if (snapshotKey != null && metadata.getClass().getName().endsWith(".internal.RemoteSnapshotMetadata")) {
relatedMetadata.put(snapshotKey, (MergeableMetadata) metadata);
}
}
artifact.setResolvedVersion(result.getArtifacts().iterator().next().getVersion());
| 262
| 744
| 1,006
|
<methods>public void <init>() ,public void enableLogging(org.codehaus.plexus.logging.Logger) <variables>private org.codehaus.plexus.logging.Logger logger
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/installer/DefaultArtifactInstaller.java
|
DefaultArtifactInstaller
|
install
|
class DefaultArtifactInstaller extends AbstractLogEnabled implements ArtifactInstaller {
@Inject
private RepositorySystem repoSystem;
@Inject
private LegacySupport legacySupport;
/** @deprecated we want to use the artifact method only, and ensure artifact.file is set correctly. */
@Deprecated
public void install(String basedir, String finalName, Artifact artifact, ArtifactRepository localRepository)
throws ArtifactInstallationException {
String extension = artifact.getArtifactHandler().getExtension();
File source = new File(basedir, finalName + "." + extension);
install(source, artifact, localRepository);
}
public void install(File source, Artifact artifact, ArtifactRepository localRepository)
throws ArtifactInstallationException {<FILL_FUNCTION_BODY>}
}
|
RepositorySystemSession session =
LegacyLocalRepositoryManager.overlay(localRepository, legacySupport.getRepositorySession(), repoSystem);
InstallRequest request = new InstallRequest();
request.setTrace(RequestTrace.newChild(null, legacySupport.getSession().getCurrentProject()));
org.eclipse.aether.artifact.Artifact mainArtifact = RepositoryUtils.toArtifact(artifact);
mainArtifact = mainArtifact.setFile(source);
request.addArtifact(mainArtifact);
for (ArtifactMetadata metadata : artifact.getMetadataList()) {
if (metadata instanceof ProjectArtifactMetadata) {
org.eclipse.aether.artifact.Artifact pomArtifact = new SubArtifact(mainArtifact, "", "pom");
pomArtifact = pomArtifact.setFile(((ProjectArtifactMetadata) metadata).getFile());
request.addArtifact(pomArtifact);
} else if (metadata instanceof SnapshotArtifactRepositoryMetadata
|| metadata instanceof ArtifactRepositoryMetadata) {
// eaten, handled by repo system
} else {
request.addMetadata(new MetadataBridge(metadata));
}
}
try {
repoSystem.install(session, request);
} catch (InstallationException e) {
throw new ArtifactInstallationException(e.getMessage(), e);
}
/*
* NOTE: Not used by Maven core, only here to provide backward-compat with plugins like the Install Plugin.
*/
if (artifact.isSnapshot()) {
Snapshot snapshot = new Snapshot();
snapshot.setLocalCopy(true);
artifact.addMetadata(new SnapshotArtifactRepositoryMetadata(artifact, snapshot));
}
Versioning versioning = new Versioning();
// TODO Should this be changed for MNG-6754 too?
versioning.updateTimestamp();
versioning.addVersion(artifact.getBaseVersion());
if (artifact.isRelease()) {
versioning.setRelease(artifact.getBaseVersion());
}
artifact.addMetadata(new ArtifactRepositoryMetadata(artifact, versioning));
| 202
| 518
| 720
|
<methods>public void <init>() ,public void enableLogging(org.codehaus.plexus.logging.Logger) <variables>private org.codehaus.plexus.logging.Logger logger
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/manager/DefaultWagonManager.java
|
DefaultWagonManager
|
getAuthenticationInfo
|
class DefaultWagonManager extends org.apache.maven.repository.legacy.DefaultWagonManager
implements WagonManager {
// NOTE: This must use a different field name than in the super class or IoC has no chance to inject the loggers
@Inject
private Logger log;
@Inject
private LegacySupport legacySupport;
@Inject
private SettingsDecrypter settingsDecrypter;
@Inject
private MirrorSelector mirrorSelector;
@Inject
private ArtifactRepositoryFactory artifactRepositoryFactory;
public AuthenticationInfo getAuthenticationInfo(String id) {<FILL_FUNCTION_BODY>}
public ProxyInfo getProxy(String protocol) {
MavenSession session = legacySupport.getSession();
if (session != null && protocol != null) {
MavenExecutionRequest request = session.getRequest();
if (request != null) {
List<Proxy> proxies = request.getProxies();
if (proxies != null) {
for (Proxy proxy : proxies) {
if (proxy.isActive() && protocol.equalsIgnoreCase(proxy.getProtocol())) {
SettingsDecryptionResult result =
settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(proxy));
proxy = result.getProxy();
ProxyInfo proxyInfo = new ProxyInfo();
proxyInfo.setHost(proxy.getHost());
proxyInfo.setType(proxy.getProtocol());
proxyInfo.setPort(proxy.getPort());
proxyInfo.setNonProxyHosts(proxy.getNonProxyHosts());
proxyInfo.setUserName(proxy.getUsername());
proxyInfo.setPassword(proxy.getPassword());
return proxyInfo;
}
}
}
}
}
return null;
}
public void getArtifact(Artifact artifact, ArtifactRepository repository)
throws TransferFailedException, ResourceDoesNotExistException {
getArtifact(artifact, repository, null, false);
}
public void getArtifact(Artifact artifact, List<ArtifactRepository> remoteRepositories)
throws TransferFailedException, ResourceDoesNotExistException {
getArtifact(artifact, remoteRepositories, null, false);
}
@Deprecated
public ArtifactRepository getMirrorRepository(ArtifactRepository repository) {
Mirror mirror = mirrorSelector.getMirror(
repository, legacySupport.getSession().getSettings().getMirrors());
if (mirror != null) {
String id = mirror.getId();
if (id == null) {
// TODO this should be illegal in settings.xml
id = repository.getId();
}
log.debug("Using mirror: " + mirror.getUrl() + " (id: " + id + ")");
repository = artifactRepositoryFactory.createArtifactRepository(
id, mirror.getUrl(), repository.getLayout(), repository.getSnapshots(), repository.getReleases());
}
return repository;
}
}
|
MavenSession session = legacySupport.getSession();
if (session != null && id != null) {
MavenExecutionRequest request = session.getRequest();
if (request != null) {
List<Server> servers = request.getServers();
if (servers != null) {
for (Server server : servers) {
if (id.equalsIgnoreCase(server.getId())) {
SettingsDecryptionResult result =
settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(server));
server = result.getServer();
AuthenticationInfo authInfo = new AuthenticationInfo();
authInfo.setUserName(server.getUsername());
authInfo.setPassword(server.getPassword());
authInfo.setPrivateKey(server.getPrivateKey());
authInfo.setPassphrase(server.getPassphrase());
return authInfo;
}
}
}
}
}
// empty one to prevent NPE
return new AuthenticationInfo();
| 765
| 255
| 1,020
|
<methods>public non-sealed void <init>() ,public void getArtifact(org.apache.maven.artifact.Artifact, org.apache.maven.artifact.repository.ArtifactRepository, org.apache.maven.wagon.events.TransferListener, boolean) throws org.apache.maven.wagon.TransferFailedException, org.apache.maven.wagon.ResourceDoesNotExistException,public void getArtifact(org.apache.maven.artifact.Artifact, List<org.apache.maven.artifact.repository.ArtifactRepository>, org.apache.maven.wagon.events.TransferListener, boolean) throws org.apache.maven.wagon.TransferFailedException, org.apache.maven.wagon.ResourceDoesNotExistException,public void getArtifactMetadata(org.apache.maven.artifact.metadata.ArtifactMetadata, org.apache.maven.artifact.repository.ArtifactRepository, java.io.File, java.lang.String) throws org.apache.maven.wagon.TransferFailedException, org.apache.maven.wagon.ResourceDoesNotExistException,public void getArtifactMetadataFromDeploymentRepository(org.apache.maven.artifact.metadata.ArtifactMetadata, org.apache.maven.artifact.repository.ArtifactRepository, java.io.File, java.lang.String) throws org.apache.maven.wagon.TransferFailedException, org.apache.maven.wagon.ResourceDoesNotExistException,public void getRemoteFile(org.apache.maven.artifact.repository.ArtifactRepository, java.io.File, java.lang.String, org.apache.maven.wagon.events.TransferListener, java.lang.String, boolean) throws org.apache.maven.wagon.TransferFailedException, org.apache.maven.wagon.ResourceDoesNotExistException,public org.apache.maven.wagon.Wagon getWagon(org.apache.maven.wagon.repository.Repository) throws org.apache.maven.wagon.UnsupportedProtocolException,public org.apache.maven.wagon.Wagon getWagon(java.lang.String) throws org.apache.maven.wagon.UnsupportedProtocolException,public void putArtifact(java.io.File, org.apache.maven.artifact.Artifact, org.apache.maven.artifact.repository.ArtifactRepository, org.apache.maven.wagon.events.TransferListener) throws org.apache.maven.wagon.TransferFailedException,public void putArtifactMetadata(java.io.File, org.apache.maven.artifact.metadata.ArtifactMetadata, org.apache.maven.artifact.repository.ArtifactRepository) throws org.apache.maven.wagon.TransferFailedException,public void putRemoteFile(org.apache.maven.artifact.repository.ArtifactRepository, java.io.File, java.lang.String, org.apache.maven.wagon.events.TransferListener) throws org.apache.maven.wagon.TransferFailedException<variables>private static final java.lang.String[] CHECKSUM_ALGORITHMS,private static final java.lang.String[] CHECKSUM_IDS,private org.codehaus.plexus.PlexusContainer container,private org.apache.maven.plugin.LegacySupport legacySupport,private org.codehaus.plexus.logging.Logger logger,private org.apache.maven.repository.legacy.UpdateCheckManager updateCheckManager
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepository.java
|
DefaultArtifactRepository
|
setMirroredRepositories
|
class DefaultArtifactRepository extends Repository implements ArtifactRepository {
private ArtifactRepositoryLayout layout;
private ArtifactRepositoryPolicy snapshots;
private ArtifactRepositoryPolicy releases;
private boolean blacklisted;
private Authentication authentication;
private Proxy proxy;
private List<ArtifactRepository> mirroredRepositories = Collections.emptyList();
private boolean blocked;
/**
* Create a local repository or a test repository.
*
* @param id the unique identifier of the repository
* @param url the URL of the repository
* @param layout the layout of the repository
*/
public DefaultArtifactRepository(String id, String url, ArtifactRepositoryLayout layout) {
this(id, url, layout, null, null);
}
/**
* Create a remote deployment repository.
*
* @param id the unique identifier of the repository
* @param url the URL of the repository
* @param layout the layout of the repository
* @param uniqueVersion whether to assign each snapshot a unique version
*/
public DefaultArtifactRepository(String id, String url, ArtifactRepositoryLayout layout, boolean uniqueVersion) {
super(id, url);
this.layout = layout;
}
/**
* Create a remote download repository.
*
* @param id the unique identifier of the repository
* @param url the URL of the repository
* @param layout the layout of the repository
* @param snapshots the policies to use for snapshots
* @param releases the policies to use for releases
*/
public DefaultArtifactRepository(
String id,
String url,
ArtifactRepositoryLayout layout,
ArtifactRepositoryPolicy snapshots,
ArtifactRepositoryPolicy releases) {
super(id, url);
this.layout = layout;
if (snapshots == null) {
snapshots = new ArtifactRepositoryPolicy(
true,
ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE);
}
this.snapshots = snapshots;
if (releases == null) {
releases = new ArtifactRepositoryPolicy(
true,
ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE);
}
this.releases = releases;
}
public String pathOf(Artifact artifact) {
return layout.pathOf(artifact);
}
public String pathOfRemoteRepositoryMetadata(ArtifactMetadata artifactMetadata) {
return layout.pathOfRemoteRepositoryMetadata(artifactMetadata);
}
public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
return layout.pathOfLocalRepositoryMetadata(metadata, repository);
}
public void setLayout(ArtifactRepositoryLayout layout) {
this.layout = layout;
}
public ArtifactRepositoryLayout getLayout() {
return layout;
}
public void setSnapshotUpdatePolicy(ArtifactRepositoryPolicy snapshots) {
this.snapshots = snapshots;
}
public ArtifactRepositoryPolicy getSnapshots() {
return snapshots;
}
public void setReleaseUpdatePolicy(ArtifactRepositoryPolicy releases) {
this.releases = releases;
}
public ArtifactRepositoryPolicy getReleases() {
return releases;
}
public String getKey() {
return getId();
}
public boolean isBlacklisted() {
return blacklisted;
}
public void setBlacklisted(boolean blacklisted) {
this.blacklisted = blacklisted;
}
public String toString() {
StringBuilder sb = new StringBuilder(256);
sb.append(" id: ").append(getId()).append('\n');
sb.append(" url: ").append(getUrl()).append('\n');
sb.append(" layout: ").append(layout != null ? layout : "none").append('\n');
if (snapshots != null) {
sb.append("snapshots: [enabled => ").append(snapshots.isEnabled());
sb.append(", update => ").append(snapshots.getUpdatePolicy()).append("]\n");
}
if (releases != null) {
sb.append(" releases: [enabled => ").append(releases.isEnabled());
sb.append(", update => ").append(releases.getUpdatePolicy()).append("]\n");
}
return sb.toString();
}
public Artifact find(Artifact artifact) {
File artifactFile = new File(getBasedir(), pathOf(artifact));
// We need to set the file here or the resolver will fail with an NPE, not fully equipped to deal
// with multiple local repository implementations yet.
artifact.setFile(artifactFile);
if (artifactFile.exists()) {
artifact.setResolved(true);
}
return artifact;
}
public List<String> findVersions(Artifact artifact) {
return Collections.emptyList();
}
public boolean isProjectAware() {
return false;
}
public Authentication getAuthentication() {
return authentication;
}
public void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
public Proxy getProxy() {
return proxy;
}
public void setProxy(Proxy proxy) {
this.proxy = proxy;
}
public boolean isUniqueVersion() {
return true;
}
public List<ArtifactRepository> getMirroredRepositories() {
return mirroredRepositories;
}
public void setMirroredRepositories(List<ArtifactRepository> mirroredRepositories) {<FILL_FUNCTION_BODY>}
public boolean isBlocked() {
return blocked;
}
public void setBlocked(boolean blocked) {
this.blocked = blocked;
}
}
|
if (mirroredRepositories != null) {
this.mirroredRepositories = Collections.unmodifiableList(mirroredRepositories);
} else {
this.mirroredRepositories = Collections.emptyList();
}
| 1,539
| 73
| 1,612
|
<methods>public void <init>() ,public void <init>(java.lang.String, java.lang.String) ,public boolean equals(java.lang.Object) ,public java.lang.String getBasedir() ,public java.lang.String getHost() ,public java.lang.String getId() ,public java.lang.String getName() ,public java.lang.String getParameter(java.lang.String) ,public java.lang.String getPassword() ,public org.apache.maven.wagon.repository.RepositoryPermissions getPermissions() ,public int getPort() ,public java.lang.String getProtocol() ,public java.lang.String getUrl() ,public java.lang.String getUsername() ,public int hashCode() ,public void setBasedir(java.lang.String) ,public void setId(java.lang.String) ,public void setName(java.lang.String) ,public void setParameters(java.util.Properties) ,public void setPermissions(org.apache.maven.wagon.repository.RepositoryPermissions) ,public void setPort(int) ,public void setProtocol(java.lang.String) ,public void setUrl(java.lang.String) ,public java.lang.String toString() <variables>private java.lang.String basedir,private java.lang.String host,private java.lang.String id,private java.lang.String name,private java.util.Properties parameters,private java.lang.String password,private org.apache.maven.wagon.repository.RepositoryPermissions permissions,private int port,private java.lang.String protocol,private static final long serialVersionUID,private java.lang.String url,private java.lang.String username
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/repository/DefaultArtifactRepositoryFactory.java
|
DefaultArtifactRepositoryFactory
|
injectSession
|
class DefaultArtifactRepositoryFactory implements ArtifactRepositoryFactory {
@Inject
private org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory factory;
@Inject
private LegacySupport legacySupport;
@Inject
private PlexusContainer container;
public ArtifactRepositoryLayout getLayout(String layoutId) throws UnknownRepositoryLayoutException {
return factory.getLayout(layoutId);
}
public ArtifactRepository createDeploymentArtifactRepository(
String id, String url, String layoutId, boolean uniqueVersion) throws UnknownRepositoryLayoutException {
return injectSession(factory.createDeploymentArtifactRepository(id, url, layoutId, uniqueVersion), false);
}
public ArtifactRepository createDeploymentArtifactRepository(
String id, String url, ArtifactRepositoryLayout repositoryLayout, boolean uniqueVersion) {
return injectSession(
factory.createDeploymentArtifactRepository(id, url, repositoryLayout, uniqueVersion), false);
}
public ArtifactRepository createArtifactRepository(
String id,
String url,
String layoutId,
ArtifactRepositoryPolicy snapshots,
ArtifactRepositoryPolicy releases)
throws UnknownRepositoryLayoutException {
return injectSession(factory.createArtifactRepository(id, url, layoutId, snapshots, releases), true);
}
public ArtifactRepository createArtifactRepository(
String id,
String url,
ArtifactRepositoryLayout repositoryLayout,
ArtifactRepositoryPolicy snapshots,
ArtifactRepositoryPolicy releases) {
return injectSession(factory.createArtifactRepository(id, url, repositoryLayout, snapshots, releases), true);
}
public void setGlobalUpdatePolicy(String updatePolicy) {
factory.setGlobalUpdatePolicy(updatePolicy);
}
public void setGlobalChecksumPolicy(String checksumPolicy) {
factory.setGlobalChecksumPolicy(checksumPolicy);
}
private ArtifactRepository injectSession(ArtifactRepository repository, boolean mirrors) {<FILL_FUNCTION_BODY>}
private boolean isLocalRepository(ArtifactRepository repository) {
// unfortunately, the API doesn't allow to tell a remote repo and the local repo apart...
return "local".equals(repository.getId());
}
}
|
RepositorySystemSession session = legacySupport.getRepositorySession();
if (session != null && repository != null && !isLocalRepository(repository)) {
List<ArtifactRepository> repositories = Arrays.asList(repository);
RepositorySystem repositorySystem;
try {
repositorySystem = container.lookup(RepositorySystem.class);
} catch (ComponentLookupException e) {
throw new IllegalStateException("Unable to lookup " + RepositorySystem.class.getName());
}
if (mirrors) {
repositorySystem.injectMirror(session, repositories);
}
repositorySystem.injectProxy(session, repositories);
repositorySystem.injectAuthentication(session, repositories);
}
return repository;
| 553
| 192
| 745
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/repository/LegacyLocalRepositoryManager.java
|
ArtifactMetadataAdapter
|
insertRepositoryKey
|
class ArtifactMetadataAdapter implements ArtifactMetadata {
private final Metadata metadata;
ArtifactMetadataAdapter(Metadata metadata) {
this.metadata = metadata;
}
public boolean storedInArtifactVersionDirectory() {
return !metadata.getVersion().isEmpty();
}
public boolean storedInGroupDirectory() {
return metadata.getArtifactId().isEmpty();
}
public String getGroupId() {
return nullify(metadata.getGroupId());
}
public String getArtifactId() {
return nullify(metadata.getArtifactId());
}
public String getBaseVersion() {
return nullify(metadata.getVersion());
}
private String nullify(String str) {
return (str == null || str.isEmpty()) ? null : str;
}
public Object getKey() {
return metadata.toString();
}
public String getRemoteFilename() {
return metadata.getType();
}
public String getLocalFilename(ArtifactRepository repository) {
return insertRepositoryKey(getRemoteFilename(), repository.getKey());
}
private String insertRepositoryKey(String filename, String repositoryKey) {<FILL_FUNCTION_BODY>}
public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata) {
// not used
}
public void merge(ArtifactMetadata metadata) {
// not used
}
public void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository)
throws RepositoryMetadataStoreException {
// not used
}
public String extendedToString() {
return metadata.toString();
}
}
|
String result;
int idx = filename.indexOf('.');
if (idx < 0) {
result = filename + '-' + repositoryKey;
} else {
result = filename.substring(0, idx) + '-' + repositoryKey + filename.substring(idx);
}
return result;
| 426
| 79
| 505
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/repository/layout/FlatRepositoryLayout.java
|
FlatRepositoryLayout
|
pathOf
|
class FlatRepositoryLayout implements ArtifactRepositoryLayout {
private static final char ARTIFACT_SEPARATOR = '-';
private static final char GROUP_SEPARATOR = '.';
public String getId() {
return "flat";
}
public String pathOf(Artifact artifact) {<FILL_FUNCTION_BODY>}
public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
return pathOfRepositoryMetadata(metadata.getLocalFilename(repository));
}
private String pathOfRepositoryMetadata(String filename) {
StringBuilder path = new StringBuilder(128);
path.append(filename);
return path.toString();
}
public String pathOfRemoteRepositoryMetadata(ArtifactMetadata metadata) {
return pathOfRepositoryMetadata(metadata.getRemoteFilename());
}
@Override
public String toString() {
return getId();
}
}
|
ArtifactHandler artifactHandler = artifact.getArtifactHandler();
StringBuilder path = new StringBuilder(128);
path.append(artifact.getArtifactId()).append(ARTIFACT_SEPARATOR).append(artifact.getVersion());
if (artifact.hasClassifier()) {
path.append(ARTIFACT_SEPARATOR).append(artifact.getClassifier());
}
if (artifactHandler.getExtension() != null
&& !artifactHandler.getExtension().isEmpty()) {
path.append(GROUP_SEPARATOR).append(artifactHandler.getExtension());
}
return path.toString();
| 236
| 161
| 397
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java
|
AbstractRepositoryMetadata
|
storeInLocalRepository
|
class AbstractRepositoryMetadata implements RepositoryMetadata {
private static final String LS = System.lineSeparator();
private Metadata metadata;
protected AbstractRepositoryMetadata(Metadata metadata) {
this.metadata = metadata;
}
public String getRemoteFilename() {
return "maven-metadata.xml";
}
public String getLocalFilename(ArtifactRepository repository) {
return "maven-metadata-" + repository.getKey() + ".xml";
}
public void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository)
throws RepositoryMetadataStoreException {<FILL_FUNCTION_BODY>}
protected void updateRepositoryMetadata(ArtifactRepository localRepository, ArtifactRepository remoteRepository)
throws IOException, XMLStreamException {
Metadata metadata = null;
File metadataFile = new File(
localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata(this, remoteRepository));
if (metadataFile.length() == 0) {
if (!metadataFile.delete()) {
// sleep for 10ms just in case this is windows holding a file lock
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// ignore
}
metadataFile.delete(); // if this fails, forget about it, we'll try to overwrite it anyway so no need
// to delete on exit
}
} else if (metadataFile.exists()) {
try (InputStream input = Files.newInputStream(metadataFile.toPath())) {
metadata = new Metadata(new MetadataStaxReader().read(input, false));
}
}
boolean changed;
// If file could not be found or was not valid, start from scratch
if (metadata == null) {
metadata = this.metadata;
changed = true;
} else {
changed = metadata.merge(this.metadata);
}
// beware meta-versions!
String version = metadata.getVersion();
if (Artifact.LATEST_VERSION.equals(version) || Artifact.RELEASE_VERSION.equals(version)) {
// meta-versions are not valid <version/> values...don't write them.
metadata.setVersion(null);
}
if (changed || !metadataFile.exists()) {
metadataFile.getParentFile().mkdirs();
try (OutputStream output = Files.newOutputStream(metadataFile.toPath())) {
MetadataStaxWriter mappingWriter = new MetadataStaxWriter();
mappingWriter.write(output, metadata.getDelegate());
}
} else {
metadataFile.setLastModified(System.currentTimeMillis());
}
}
public String toString() {
return "repository metadata for: '" + getKey() + "'";
}
protected static Metadata createMetadata(Artifact artifact, Versioning versioning) {
Metadata metadata = new Metadata();
metadata.setGroupId(artifact.getGroupId());
metadata.setArtifactId(artifact.getArtifactId());
metadata.setVersion(artifact.getVersion());
metadata.setVersioning(versioning);
return metadata;
}
protected static Versioning createVersioning(Snapshot snapshot) {
Versioning versioning = new Versioning();
versioning.setSnapshot(snapshot);
return versioning;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public Metadata getMetadata() {
return metadata;
}
public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata) {
// TODO not sure that it should assume this, maybe the calls to addMetadata should pre-merge, then artifact
// replaces?
AbstractRepositoryMetadata repoMetadata = (AbstractRepositoryMetadata) metadata;
this.metadata.merge(repoMetadata.getMetadata());
}
public void merge(ArtifactMetadata metadata) {
// TODO not sure that it should assume this, maybe the calls to addMetadata should pre-merge, then artifact
// replaces?
AbstractRepositoryMetadata repoMetadata = (AbstractRepositoryMetadata) metadata;
this.metadata.merge(repoMetadata.getMetadata());
}
public String extendedToString() {
StringBuilder buffer = new StringBuilder(256);
buffer.append(LS).append("Repository Metadata").append(LS).append("--------------------------");
buffer.append(LS).append("GroupId: ").append(getGroupId());
buffer.append(LS).append("ArtifactId: ").append(getArtifactId());
buffer.append(LS).append("Metadata Type: ").append(getClass().getName());
return buffer.toString();
}
public int getNature() {
return RELEASE;
}
public ArtifactRepositoryPolicy getPolicy(ArtifactRepository repository) {
int nature = getNature();
if ((nature & RepositoryMetadata.RELEASE_OR_SNAPSHOT) == RepositoryMetadata.RELEASE_OR_SNAPSHOT) {
ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy(repository.getReleases());
policy.merge(repository.getSnapshots());
return policy;
} else if ((nature & RepositoryMetadata.SNAPSHOT) != 0) {
return repository.getSnapshots();
} else {
return repository.getReleases();
}
}
}
|
try {
updateRepositoryMetadata(localRepository, remoteRepository);
} catch (IOException | XMLStreamException e) {
throw new RepositoryMetadataStoreException("Error updating group repository metadata", e);
}
| 1,329
| 53
| 1,382
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/GroupRepositoryMetadata.java
|
GroupRepositoryMetadata
|
addPluginMapping
|
class GroupRepositoryMetadata extends AbstractRepositoryMetadata {
private final String groupId;
public GroupRepositoryMetadata(String groupId) {
super(new Metadata());
this.groupId = groupId;
}
public boolean storedInGroupDirectory() {
return true;
}
public boolean storedInArtifactVersionDirectory() {
return false;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return null;
}
public String getBaseVersion() {
return null;
}
public void addPluginMapping(String goalPrefix, String artifactId) {
addPluginMapping(goalPrefix, artifactId, artifactId);
}
public void addPluginMapping(String goalPrefix, String artifactId, String name) {<FILL_FUNCTION_BODY>}
public Object getKey() {
return groupId;
}
public boolean isSnapshot() {
return false;
}
public ArtifactRepository getRepository() {
return null;
}
public void setRepository(ArtifactRepository remoteRepository) {
// intentionally blank
}
}
|
List<Plugin> plugins = getMetadata().getPlugins();
boolean found = false;
for (Iterator<Plugin> i = plugins.iterator(); i.hasNext() && !found; ) {
Plugin plugin = i.next();
if (plugin.getPrefix().equals(goalPrefix)) {
found = true;
}
}
if (!found) {
Plugin plugin = new Plugin();
plugin.setPrefix(goalPrefix);
plugin.setArtifactId(artifactId);
plugin.setName(name);
getMetadata().addPlugin(plugin);
}
| 297
| 151
| 448
|
<methods>public java.lang.String extendedToString() ,public java.lang.String getLocalFilename(org.apache.maven.artifact.repository.ArtifactRepository) ,public org.apache.maven.artifact.repository.metadata.Metadata getMetadata() ,public int getNature() ,public org.apache.maven.artifact.repository.ArtifactRepositoryPolicy getPolicy(org.apache.maven.artifact.repository.ArtifactRepository) ,public java.lang.String getRemoteFilename() ,public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata) ,public void merge(org.apache.maven.artifact.metadata.ArtifactMetadata) ,public void setMetadata(org.apache.maven.artifact.repository.metadata.Metadata) ,public void storeInLocalRepository(org.apache.maven.artifact.repository.ArtifactRepository, org.apache.maven.artifact.repository.ArtifactRepository) throws org.apache.maven.artifact.repository.metadata.RepositoryMetadataStoreException,public java.lang.String toString() <variables>private static final java.lang.String LS,private org.apache.maven.artifact.repository.metadata.Metadata metadata
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataBridge.java
|
MetadataBridge
|
merge
|
class MetadataBridge extends AbstractMetadata implements MergeableMetadata {
private ArtifactMetadata metadata;
private boolean merged;
public MetadataBridge(ArtifactMetadata metadata) {
this.metadata = metadata;
}
public void merge(File current, File result) throws RepositoryException {<FILL_FUNCTION_BODY>}
public boolean isMerged() {
return merged;
}
public String getGroupId() {
return emptify(metadata.getGroupId());
}
public String getArtifactId() {
return metadata.storedInGroupDirectory() ? "" : emptify(metadata.getArtifactId());
}
public String getVersion() {
return metadata.storedInArtifactVersionDirectory() ? emptify(metadata.getBaseVersion()) : "";
}
public String getType() {
return metadata.getRemoteFilename();
}
private String emptify(String string) {
return (string != null) ? string : "";
}
public File getFile() {
return null;
}
public MetadataBridge setFile(File file) {
return this;
}
@Override
public Path getPath() {
return null;
}
public Nature getNature() {
if (metadata instanceof RepositoryMetadata) {
switch (((RepositoryMetadata) metadata).getNature()) {
case RepositoryMetadata.RELEASE_OR_SNAPSHOT:
return Nature.RELEASE_OR_SNAPSHOT;
case RepositoryMetadata.SNAPSHOT:
return Nature.SNAPSHOT;
default:
return Nature.RELEASE;
}
} else {
return Nature.RELEASE;
}
}
public Map<String, String> getProperties() {
return Collections.emptyMap();
}
@Override
public Metadata setProperties(Map<String, String> properties) {
return this;
}
@SuppressWarnings("deprecation")
static class MetadataRepository extends DefaultArtifactRepository {
private File metadataFile;
MetadataRepository(File metadataFile) {
super("local", "", null);
this.metadataFile = metadataFile;
}
@Override
public String getBasedir() {
return metadataFile.getParent();
}
@Override
public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
return metadataFile.getName();
}
}
}
|
try {
if (current.exists()) {
Files.createDirectories(result.toPath().getParent());
Files.copy(current.toPath(), result.toPath());
}
ArtifactRepository localRepo = new MetadataRepository(result);
metadata.storeInLocalRepository(localRepo, localRepo);
merged = true;
} catch (Exception e) {
throw new RepositoryException(e.getMessage(), e);
}
| 638
| 116
| 754
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/MetadataUtils.java
|
MetadataUtils
|
cloneMetadata
|
class MetadataUtils {
public static Metadata cloneMetadata(Metadata src) {<FILL_FUNCTION_BODY>}
}
|
if (src == null) {
return null;
}
return src.clone();
| 34
| 27
| 61
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ArtifactResolutionRequest.java
|
ArtifactResolutionRequest
|
getMirrors
|
class ArtifactResolutionRequest implements RepositoryRequest {
private static final String LS = System.lineSeparator();
private Artifact artifact;
// Needs to go away
// These are really overrides now, projects defining dependencies for a plugin that override what is
// specified in the plugin itself.
private Set<Artifact> artifactDependencies;
private ArtifactRepository localRepository;
private List<ArtifactRepository> remoteRepositories;
private ArtifactFilter collectionFilter;
private ArtifactFilter resolutionFilter;
// Needs to go away
private List<ResolutionListener> listeners = new ArrayList<>();
// This is like a filter but overrides all transitive versions
private Map<String, Artifact> managedVersionMap;
private boolean resolveRoot = true;
private boolean resolveTransitively = false;
private boolean offline;
private boolean forceUpdate;
private List<Server> servers;
private List<Mirror> mirrors;
private List<Proxy> proxies;
public ArtifactResolutionRequest() {
// nothing here
}
public ArtifactResolutionRequest(RepositoryRequest request) {
setLocalRepository(request.getLocalRepository());
setRemoteRepositories(request.getRemoteRepositories());
setOffline(request.isOffline());
setForceUpdate(request.isForceUpdate());
}
public Artifact getArtifact() {
return artifact;
}
public ArtifactResolutionRequest setArtifact(Artifact artifact) {
this.artifact = artifact;
return this;
}
public ArtifactResolutionRequest setArtifactDependencies(Set<Artifact> artifactDependencies) {
this.artifactDependencies = artifactDependencies;
return this;
}
public Set<Artifact> getArtifactDependencies() {
return artifactDependencies;
}
public ArtifactRepository getLocalRepository() {
return localRepository;
}
public ArtifactResolutionRequest setLocalRepository(ArtifactRepository localRepository) {
this.localRepository = localRepository;
return this;
}
public List<ArtifactRepository> getRemoteRepositories() {
return remoteRepositories;
}
public ArtifactResolutionRequest setRemoteRepositories(List<ArtifactRepository> remoteRepositories) {
this.remoteRepositories = remoteRepositories;
return this;
}
/**
* Gets the artifact filter that controls traversal of the dependency graph.
*
* @return The filter used to determine which of the artifacts in the dependency graph should be traversed or
* {@code null} to collect all transitive dependencies.
*/
public ArtifactFilter getCollectionFilter() {
return collectionFilter;
}
public ArtifactResolutionRequest setCollectionFilter(ArtifactFilter filter) {
this.collectionFilter = filter;
return this;
}
/**
* Gets the artifact filter that controls downloading of artifact files. This filter operates on those artifacts
* that have been included by the {@link #getCollectionFilter()}.
*
* @return The filter used to determine which of the artifacts should have their files resolved or {@code null} to
* resolve the files for all collected artifacts.
*/
public ArtifactFilter getResolutionFilter() {
return resolutionFilter;
}
public ArtifactResolutionRequest setResolutionFilter(ArtifactFilter filter) {
this.resolutionFilter = filter;
return this;
}
public List<ResolutionListener> getListeners() {
return listeners;
}
public ArtifactResolutionRequest setListeners(List<ResolutionListener> listeners) {
this.listeners = listeners;
return this;
}
public ArtifactResolutionRequest addListener(ResolutionListener listener) {
listeners.add(listener);
return this;
}
public Map<String, Artifact> getManagedVersionMap() {
return managedVersionMap;
}
public ArtifactResolutionRequest setManagedVersionMap(Map<String, Artifact> managedVersionMap) {
this.managedVersionMap = managedVersionMap;
return this;
}
public ArtifactResolutionRequest setResolveRoot(boolean resolveRoot) {
this.resolveRoot = resolveRoot;
return this;
}
public boolean isResolveRoot() {
return resolveRoot;
}
public ArtifactResolutionRequest setResolveTransitively(boolean resolveDependencies) {
this.resolveTransitively = resolveDependencies;
return this;
}
public boolean isResolveTransitively() {
return resolveTransitively;
}
public String toString() {
StringBuilder sb = new StringBuilder()
.append("REQUEST: ")
.append(LS)
.append("artifact: ")
.append(artifact)
.append(LS)
.append(artifactDependencies)
.append(LS)
.append("localRepository: ")
.append(localRepository)
.append(LS)
.append("remoteRepositories: ")
.append(remoteRepositories);
return sb.toString();
}
public boolean isOffline() {
return offline;
}
public ArtifactResolutionRequest setOffline(boolean offline) {
this.offline = offline;
return this;
}
public boolean isForceUpdate() {
return forceUpdate;
}
public ArtifactResolutionRequest setForceUpdate(boolean forceUpdate) {
this.forceUpdate = forceUpdate;
return this;
}
public ArtifactResolutionRequest setServers(List<Server> servers) {
this.servers = servers;
return this;
}
public List<Server> getServers() {
if (servers == null) {
servers = new ArrayList<>();
}
return servers;
}
public ArtifactResolutionRequest setMirrors(List<Mirror> mirrors) {
this.mirrors = mirrors;
return this;
}
public List<Mirror> getMirrors() {<FILL_FUNCTION_BODY>}
public ArtifactResolutionRequest setProxies(List<Proxy> proxies) {
this.proxies = proxies;
return this;
}
public List<Proxy> getProxies() {
if (proxies == null) {
proxies = new ArrayList<>();
}
return proxies;
}
//
// Used by Tycho and will break users and force them to upgrade to Maven 3.1 so we should really leave
// this here, possibly indefinitely.
//
public ArtifactResolutionRequest setCache(RepositoryCache cache) {
return this;
}
}
|
if (mirrors == null) {
mirrors = new ArrayList<>();
}
return mirrors;
| 1,744
| 32
| 1,776
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DebugResolutionListener.java
|
DebugResolutionListener
|
restrictRange
|
class DebugResolutionListener implements ResolutionListener, ResolutionListenerForDepMgmt {
private Logger logger;
private String indent = "";
private static Set<Artifact> ignoredArtifacts = new HashSet<>();
public DebugResolutionListener(Logger logger) {
this.logger = logger;
}
public void testArtifact(Artifact node) {}
public void startProcessChildren(Artifact artifact) {
indent += " ";
}
public void endProcessChildren(Artifact artifact) {
indent = indent.substring(2);
}
public void includeArtifact(Artifact artifact) {
logger.debug(indent + artifact + " (selected for " + artifact.getScope() + ")");
}
public void omitForNearer(Artifact omitted, Artifact kept) {
String omittedVersion = omitted.getVersion();
String keptVersion = kept.getVersion();
if (!Objects.equals(omittedVersion, keptVersion)) {
logger.debug(indent + omitted + " (removed - nearer found: " + keptVersion + ")");
}
}
public void omitForCycle(Artifact omitted) {
logger.debug(indent + omitted + " (removed - causes a cycle in the graph)");
}
public void updateScopeCurrentPom(Artifact artifact, String ignoredScope) {
logger.debug(indent + artifact + " (not setting artifactScope to: " + ignoredScope + "; local artifactScope "
+ artifact.getScope() + " wins)");
// TODO better way than static? this might hide messages in a reactor
if (!ignoredArtifacts.contains(artifact)) {
logger.warn("\n\tArtifact " + artifact + " retains local artifactScope '" + artifact.getScope()
+ "' overriding broader artifactScope '" + ignoredScope + "'\n"
+ "\tgiven by a dependency. If this is not intended, modify or remove the local artifactScope.\n");
ignoredArtifacts.add(artifact);
}
}
public void updateScope(Artifact artifact, String scope) {
logger.debug(indent + artifact + " (setting artifactScope to: " + scope + ")");
}
public void selectVersionFromRange(Artifact artifact) {
logger.debug(indent + artifact + " (setting version to: " + artifact.getVersion() + " from range: "
+ artifact.getVersionRange() + ")");
}
public void restrictRange(Artifact artifact, Artifact replacement, VersionRange newRange) {<FILL_FUNCTION_BODY>}
/**
* The logic used here used to be a copy of the logic used in the DefaultArtifactCollector, and this method was
* called right before the actual version/artifactScope changes were done. However, a different set of conditionals
* (and more information) is needed to be able to determine when and if the version and/or artifactScope changes.
* See the two added methods, manageArtifactVersion and manageArtifactScope.
*/
public void manageArtifact(Artifact artifact, Artifact replacement) {
String msg = indent + artifact;
msg += " (";
if (replacement.getVersion() != null) {
msg += "applying version: " + replacement.getVersion() + ";";
}
if (replacement.getScope() != null) {
msg += "applying artifactScope: " + replacement.getScope();
}
msg += ")";
logger.debug(msg);
}
public void manageArtifactVersion(Artifact artifact, Artifact replacement) {
// only show msg if a change is actually taking place
if (!replacement.getVersion().equals(artifact.getVersion())) {
String msg = indent + artifact + " (applying version: " + replacement.getVersion() + ")";
logger.debug(msg);
}
}
public void manageArtifactScope(Artifact artifact, Artifact replacement) {
// only show msg if a change is actually taking place
if (!replacement.getScope().equals(artifact.getScope())) {
String msg = indent + artifact + " (applying artifactScope: " + replacement.getScope() + ")";
logger.debug(msg);
}
}
public void manageArtifactSystemPath(Artifact artifact, Artifact replacement) {
// only show msg if a change is actually taking place
if (!replacement.getScope().equals(artifact.getScope())) {
String msg = indent + artifact + " (applying system path: " + replacement.getFile() + ")";
logger.debug(msg);
}
}
}
|
logger.debug(indent + artifact + " (range restricted from: " + artifact.getVersionRange() + " and: "
+ replacement.getVersionRange() + " to: " + newRange + " )");
| 1,141
| 53
| 1,194
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/resolver/DefaultResolutionErrorHandler.java
|
DefaultResolutionErrorHandler
|
throwErrors
|
class DefaultResolutionErrorHandler implements ResolutionErrorHandler {
public void throwErrors(ArtifactResolutionRequest request, ArtifactResolutionResult result)
throws ArtifactResolutionException {<FILL_FUNCTION_BODY>}
private static <T> List<T> toList(Collection<T> items) {
return (items != null) ? new ArrayList<>(items) : null;
}
}
|
// Metadata cannot be found
if (result.hasMetadataResolutionExceptions()) {
throw result.getMetadataResolutionException(0);
}
// Metadata cannot be retrieved
// Cyclic Dependency Error
if (result.hasCircularDependencyExceptions()) {
throw result.getCircularDependencyException(0);
}
// Version Range Violation
if (result.hasVersionRangeViolations()) {
throw result.getVersionRangeViolation(0);
}
// Transfer Error
if (result.hasErrorArtifactExceptions()) {
throw result.getErrorArtifactExceptions().get(0);
}
if (result.hasMissingArtifacts()) {
throw new MultipleArtifactsNotFoundException(
request.getArtifact(),
toList(result.getArtifacts()),
result.getMissingArtifacts(),
request.getRemoteRepositories());
}
// this should never happen since we checked all possible error sources before but better be sure
if (result.hasExceptions()) {
throw new ArtifactResolutionException(
"Unknown error during artifact resolution, " + request + ", " + result.getExceptions(),
request.getArtifact(),
request.getRemoteRepositories());
}
| 102
| 330
| 432
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/resolver/ResolutionNode.java
|
ResolutionNode
|
getTrail
|
class ResolutionNode {
private Artifact artifact;
private List<ResolutionNode> children;
private final List<Object> parents;
private final int depth;
private final ResolutionNode parent;
private final List<ArtifactRepository> remoteRepositories;
private boolean active = true;
private List<Artifact> trail;
public ResolutionNode(Artifact artifact, List<ArtifactRepository> remoteRepositories) {
this.artifact = artifact;
this.remoteRepositories = remoteRepositories;
depth = 0;
parents = Collections.emptyList();
parent = null;
}
public ResolutionNode(Artifact artifact, List<ArtifactRepository> remoteRepositories, ResolutionNode parent) {
this.artifact = artifact;
this.remoteRepositories = remoteRepositories;
depth = parent.depth + 1;
parents = new ArrayList<>();
parents.addAll(parent.parents);
parents.add(parent.getKey());
this.parent = parent;
}
public Artifact getArtifact() {
return artifact;
}
public Object getKey() {
return artifact.getDependencyConflictId();
}
public void addDependencies(
Set<Artifact> artifacts, List<ArtifactRepository> remoteRepositories, ArtifactFilter filter)
throws CyclicDependencyException, OverConstrainedVersionException {
if (artifacts != null && !artifacts.isEmpty()) {
children = new ArrayList<>(artifacts.size());
for (Artifact a : artifacts) {
if (parents.contains(a.getDependencyConflictId())) {
a.setDependencyTrail(getDependencyTrail());
throw new CyclicDependencyException("A dependency has introduced a cycle", a);
}
children.add(new ResolutionNode(a, remoteRepositories, this));
}
children = Collections.unmodifiableList(children);
} else {
children = Collections.emptyList();
}
trail = null;
}
/**
* @return {@link List} < {@link String} > with artifact ids
* @throws OverConstrainedVersionException if version specification is over constrained
*/
public List<String> getDependencyTrail() throws OverConstrainedVersionException {
List<Artifact> trial = getTrail();
List<String> ret = new ArrayList<>(trial.size());
for (Artifact artifact : trial) {
ret.add(artifact.getId());
}
return ret;
}
private List<Artifact> getTrail() throws OverConstrainedVersionException {<FILL_FUNCTION_BODY>}
public boolean isResolved() {
return children != null;
}
/**
* Test whether the node is direct or transitive dependency.
*
* @return whether the node is direct or transitive dependency
*/
public boolean isChildOfRootNode() {
return parent != null && parent.parent == null;
}
public Iterator<ResolutionNode> getChildrenIterator() {
return children.iterator();
}
public int getDepth() {
return depth;
}
public List<ArtifactRepository> getRemoteRepositories() {
return remoteRepositories;
}
public boolean isActive() {
return active;
}
public void enable() {
active = true;
// TODO if it was null, we really need to go find them now... or is this taken care of by the ordering?
if (children != null) {
for (ResolutionNode node : children) {
node.enable();
}
}
}
public void disable() {
active = false;
if (children != null) {
for (ResolutionNode node : children) {
node.disable();
}
}
}
public boolean filterTrail(ArtifactFilter filter) throws OverConstrainedVersionException {
boolean success = true;
if (filter != null) {
for (Artifact artifact : getTrail()) {
if (!filter.include(artifact)) {
success = false;
}
}
}
return success;
}
@Override
public String toString() {
return artifact.toString() + " (" + depth + "; " + (active ? "enabled" : "disabled") + ")";
}
public void setArtifact(Artifact artifact) {
this.artifact = artifact;
}
}
|
if (trail == null) {
List<Artifact> ids = new LinkedList<>();
ResolutionNode node = this;
while (node != null) {
Artifact artifact = node.getArtifact();
if (artifact.getVersion() == null) {
// set the recommended version
ArtifactVersion selected = artifact.getSelectedVersion();
// MNG-2123: null is a valid response to getSelectedVersion, don't
// assume it won't ever be.
if (selected != null) {
artifact.selectVersion(selected.toString());
} else {
throw new OverConstrainedVersionException(
"Unable to get a selected Version for " + artifact.getArtifactId(), artifact);
}
}
ids.add(0, artifact);
node = node.parent;
}
trail = ids;
}
return trail;
| 1,153
| 229
| 1,382
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/InversionArtifactFilter.java
|
InversionArtifactFilter
|
equals
|
class InversionArtifactFilter implements ArtifactFilter {
private final ArtifactFilter toInvert;
public InversionArtifactFilter(ArtifactFilter toInvert) {
this.toInvert = toInvert;
}
public boolean include(Artifact artifact) {
return !toInvert.include(artifact);
}
@Override
public int hashCode() {
int hash = 17;
hash = hash * 31 + toInvert.hashCode();
return hash;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (!(obj instanceof InversionArtifactFilter)) {
return false;
}
InversionArtifactFilter other = (InversionArtifactFilter) obj;
return toInvert.equals(other.toInvert);
| 158
| 78
| 236
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/OrArtifactFilter.java
|
OrArtifactFilter
|
include
|
class OrArtifactFilter implements ArtifactFilter {
private Set<ArtifactFilter> filters;
public OrArtifactFilter() {
this.filters = new LinkedHashSet<>();
}
public OrArtifactFilter(Collection<ArtifactFilter> filters) {
this.filters = new LinkedHashSet<>(filters);
}
public boolean include(Artifact artifact) {<FILL_FUNCTION_BODY>}
public void add(ArtifactFilter artifactFilter) {
filters.add(artifactFilter);
}
@Override
public int hashCode() {
int hash = 17;
hash = hash * 31 + filters.hashCode();
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof OrArtifactFilter)) {
return false;
}
OrArtifactFilter other = (OrArtifactFilter) obj;
return filters.equals(other.filters);
}
}
|
for (ArtifactFilter filter : filters) {
if (filter.include(artifact)) {
return true;
}
}
return false;
| 269
| 43
| 312
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/resolver/filter/TypeArtifactFilter.java
|
TypeArtifactFilter
|
equals
|
class TypeArtifactFilter implements ArtifactFilter {
private String type = "jar";
public TypeArtifactFilter(String type) {
this.type = type;
}
public boolean include(Artifact artifact) {
return type.equals(artifact.getType());
}
@Override
public int hashCode() {
int hash = 17;
hash = hash * 31 + type.hashCode();
return hash;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (!(obj instanceof TypeArtifactFilter)) {
return false;
}
TypeArtifactFilter other = (TypeArtifactFilter) obj;
return type.equals(other.type);
| 144
| 71
| 215
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/artifact/versioning/ManagedVersionMap.java
|
ManagedVersionMap
|
toString
|
class ManagedVersionMap extends HashMap<String, Artifact> {
public ManagedVersionMap(Map<String, Artifact> map) {
super();
if (map != null) {
putAll(map);
}
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder("ManagedVersionMap (" + size() + " entries)\n");
Iterator<String> iter = keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
buffer.append(key).append('=').append(get(key));
if (iter.hasNext()) {
buffer.append('\n');
}
}
return buffer.toString();
| 84
| 110
| 194
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends org.apache.maven.artifact.Artifact>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public org.apache.maven.artifact.Artifact compute(java.lang.String, BiFunction<? super java.lang.String,? super org.apache.maven.artifact.Artifact,? extends org.apache.maven.artifact.Artifact>) ,public org.apache.maven.artifact.Artifact computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends org.apache.maven.artifact.Artifact>) ,public org.apache.maven.artifact.Artifact computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super org.apache.maven.artifact.Artifact,? extends org.apache.maven.artifact.Artifact>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,org.apache.maven.artifact.Artifact>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super org.apache.maven.artifact.Artifact>) ,public org.apache.maven.artifact.Artifact get(java.lang.Object) ,public org.apache.maven.artifact.Artifact getOrDefault(java.lang.Object, org.apache.maven.artifact.Artifact) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public org.apache.maven.artifact.Artifact merge(java.lang.String, org.apache.maven.artifact.Artifact, BiFunction<? super org.apache.maven.artifact.Artifact,? super org.apache.maven.artifact.Artifact,? extends org.apache.maven.artifact.Artifact>) ,public org.apache.maven.artifact.Artifact put(java.lang.String, org.apache.maven.artifact.Artifact) ,public void putAll(Map<? extends java.lang.String,? extends org.apache.maven.artifact.Artifact>) ,public org.apache.maven.artifact.Artifact putIfAbsent(java.lang.String, org.apache.maven.artifact.Artifact) ,public org.apache.maven.artifact.Artifact remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public org.apache.maven.artifact.Artifact replace(java.lang.String, org.apache.maven.artifact.Artifact) ,public boolean replace(java.lang.String, org.apache.maven.artifact.Artifact, org.apache.maven.artifact.Artifact) ,public void replaceAll(BiFunction<? super java.lang.String,? super org.apache.maven.artifact.Artifact,? extends org.apache.maven.artifact.Artifact>) ,public int size() ,public Collection<org.apache.maven.artifact.Artifact> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<java.lang.String,org.apache.maven.artifact.Artifact>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<java.lang.String,org.apache.maven.artifact.Artifact>[] table,int threshold
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/execution/DefaultRuntimeInformation.java
|
DefaultRuntimeInformation
|
initialize
|
class DefaultRuntimeInformation implements RuntimeInformation, Initializable {
@Inject
private org.apache.maven.rtinfo.RuntimeInformation rtInfo;
private ArtifactVersion applicationVersion;
public ArtifactVersion getApplicationVersion() {
return applicationVersion;
}
public void initialize() throws InitializationException {<FILL_FUNCTION_BODY>}
}
|
String mavenVersion = rtInfo.getMavenVersion();
if (mavenVersion == null || mavenVersion.isEmpty()) {
throw new InitializationException("Unable to read Maven version from maven-core");
}
applicationVersion = new DefaultArtifactVersion(mavenVersion);
| 93
| 75
| 168
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/plugin/internal/DefaultPluginManager.java
|
DefaultPluginManager
|
getPluginComponent
|
class DefaultPluginManager implements PluginManager {
private final PlexusContainer container;
private final MavenPluginManager pluginManager;
private final PluginVersionResolver pluginVersionResolver;
private final PluginPrefixResolver pluginPrefixResolver;
private final LegacySupport legacySupport;
@Inject
public DefaultPluginManager(
PlexusContainer container,
MavenPluginManager pluginManager,
PluginVersionResolver pluginVersionResolver,
PluginPrefixResolver pluginPrefixResolver,
LegacySupport legacySupport) {
this.container = container;
this.pluginManager = pluginManager;
this.pluginVersionResolver = pluginVersionResolver;
this.pluginPrefixResolver = pluginPrefixResolver;
this.legacySupport = legacySupport;
}
public void executeMojo(MavenProject project, MojoExecution execution, MavenSession session)
throws MojoExecutionException, ArtifactResolutionException, MojoFailureException, ArtifactNotFoundException,
InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException {
throw new UnsupportedOperationException();
}
public Object getPluginComponent(Plugin plugin, String role, String roleHint)
throws PluginManagerException, ComponentLookupException {<FILL_FUNCTION_BODY>}
public Map<String, Object> getPluginComponents(Plugin plugin, String role)
throws ComponentLookupException, PluginManagerException {
MavenSession session = legacySupport.getSession();
PluginDescriptor pluginDescriptor;
try {
pluginDescriptor = pluginManager.getPluginDescriptor(
plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession());
pluginManager.setupPluginRealm(pluginDescriptor, session, null, null, null);
} catch (Exception e) {
throw new PluginManagerException(plugin, e.getMessage(), e);
}
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(pluginDescriptor.getClassRealm());
return container.lookupMap(role);
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
public Plugin getPluginDefinitionForPrefix(String prefix, MavenSession session, MavenProject project) {
PluginPrefixRequest request = new DefaultPluginPrefixRequest(prefix, session);
request.setPom(project.getModel());
try {
PluginPrefixResult result = pluginPrefixResolver.resolve(request);
Plugin plugin = new Plugin();
plugin.setGroupId(result.getGroupId());
plugin.setArtifactId(result.getArtifactId());
return plugin;
} catch (NoPluginFoundForPrefixException e) {
return null;
}
}
public PluginDescriptor getPluginDescriptorForPrefix(String prefix) {
MavenSession session = legacySupport.getSession();
PluginPrefixRequest request = new DefaultPluginPrefixRequest(prefix, session);
try {
PluginPrefixResult result = pluginPrefixResolver.resolve(request);
Plugin plugin = new Plugin();
plugin.setGroupId(result.getGroupId());
plugin.setArtifactId(result.getArtifactId());
return loadPluginDescriptor(plugin, session.getCurrentProject(), session);
} catch (Exception e) {
return null;
}
}
public PluginDescriptor loadPluginDescriptor(Plugin plugin, MavenProject project, MavenSession session)
throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException,
InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException,
PluginNotFoundException, PluginVersionNotFoundException {
return verifyPlugin(plugin, project, session.getSettings(), session.getLocalRepository());
}
public PluginDescriptor loadPluginFully(Plugin plugin, MavenProject project, MavenSession session)
throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException,
InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException,
PluginNotFoundException, PluginVersionNotFoundException {
PluginDescriptor pluginDescriptor = loadPluginDescriptor(plugin, project, session);
try {
pluginManager.setupPluginRealm(pluginDescriptor, session, null, null, null);
} catch (PluginResolutionException e) {
throw new PluginManagerException(plugin, e.getMessage(), e);
}
return pluginDescriptor;
}
public PluginDescriptor verifyPlugin(
Plugin plugin, MavenProject project, Settings settings, ArtifactRepository localRepository)
throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException,
InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException,
PluginNotFoundException, PluginVersionNotFoundException {
MavenSession session = legacySupport.getSession();
if (plugin.getVersion() == null) {
PluginVersionRequest versionRequest = new DefaultPluginVersionRequest(
plugin, session.getRepositorySession(), project.getRemotePluginRepositories());
plugin.setVersion(pluginVersionResolver.resolve(versionRequest).getVersion());
}
try {
return pluginManager.getPluginDescriptor(
plugin, project.getRemotePluginRepositories(), session.getRepositorySession());
} catch (PluginResolutionException e) {
throw new PluginNotFoundException(plugin, project.getPluginArtifactRepositories());
} catch (PluginDescriptorParsingException | InvalidPluginDescriptorException e) {
throw new PluginManagerException(plugin, e.getMessage(), e);
}
}
}
|
MavenSession session = legacySupport.getSession();
PluginDescriptor pluginDescriptor;
try {
pluginDescriptor = pluginManager.getPluginDescriptor(
plugin, session.getCurrentProject().getRemotePluginRepositories(), session.getRepositorySession());
pluginManager.setupPluginRealm(pluginDescriptor, session, null, null, null);
} catch (Exception e) {
throw new PluginManagerException(plugin, e.getMessage(), e);
}
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(pluginDescriptor.getClassRealm());
return container.lookup(role, roleHint);
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
| 1,370
| 198
| 1,568
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/profiles/DefaultProfileManager.java
|
DefaultProfileManager
|
addProfile
|
class DefaultProfileManager implements ProfileManager {
@Inject
private Logger logger;
@Inject
private ProfileSelector profileSelector;
private List<String> activatedIds = new ArrayList<>();
private List<String> deactivatedIds = new ArrayList<>();
private List<String> defaultIds = new ArrayList<>();
private Map<String, Profile> profilesById = new LinkedHashMap<>();
private Properties requestProperties;
/**
* @deprecated without passing in the system properties, the SystemPropertiesProfileActivator will not work
* correctly in embedded environments.
*/
@Deprecated
public DefaultProfileManager(PlexusContainer container) {
this(container, null);
}
/**
* the properties passed to the profile manager are the props that
* are passed to maven, possibly containing profile activator properties
*
*/
public DefaultProfileManager(PlexusContainer container, Properties props) {
try {
this.profileSelector = container.lookup(ProfileSelector.class);
this.logger = ((MutablePlexusContainer) container).getLogger();
} catch (ComponentLookupException e) {
throw new IllegalStateException(e);
}
this.requestProperties = props;
}
public Properties getRequestProperties() {
return requestProperties;
}
public Map<String, Profile> getProfilesById() {
return profilesById;
}
/* (non-Javadoc)
* @see org.apache.maven.profiles.ProfileManager#addProfile(org.apache.maven.model.Profile)
*/
public void addProfile(Profile profile) {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see org.apache.maven.profiles.ProfileManager#explicitlyActivate(java.lang.String)
*/
public void explicitlyActivate(String profileId) {
if (!activatedIds.contains(profileId)) {
logger.debug("Profile with id: '" + profileId + "' has been explicitly activated.");
activatedIds.add(profileId);
}
}
/* (non-Javadoc)
* @see org.apache.maven.profiles.ProfileManager#explicitlyActivate(java.util.List)
*/
public void explicitlyActivate(List<String> profileIds) {
for (String profileId1 : profileIds) {
explicitlyActivate(profileId1);
}
}
/* (non-Javadoc)
* @see org.apache.maven.profiles.ProfileManager#explicitlyDeactivate(java.lang.String)
*/
public void explicitlyDeactivate(String profileId) {
if (!deactivatedIds.contains(profileId)) {
logger.debug("Profile with id: '" + profileId + "' has been explicitly deactivated.");
deactivatedIds.add(profileId);
}
}
/* (non-Javadoc)
* @see org.apache.maven.profiles.ProfileManager#explicitlyDeactivate(java.util.List)
*/
public void explicitlyDeactivate(List<String> profileIds) {
for (String profileId1 : profileIds) {
explicitlyDeactivate(profileId1);
}
}
/* (non-Javadoc)
* @see org.apache.maven.profiles.ProfileManager#getActiveProfiles()
*/
public List getActiveProfiles() throws ProfileActivationException {
DefaultProfileActivationContext context = new DefaultProfileActivationContext();
context.setActiveProfileIds(activatedIds);
context.setInactiveProfileIds(deactivatedIds);
context.setSystemProperties(System.getProperties());
context.setUserProperties(requestProperties);
final List<ProfileActivationException> errors = new ArrayList<>();
List<Profile> profiles = profileSelector.getActiveProfiles(profilesById.values(), context, req -> {
if (!ModelProblem.Severity.WARNING.equals(req.getSeverity())) {
errors.add(new ProfileActivationException(req.getMessage(), req.getException()));
}
});
if (!errors.isEmpty()) {
throw errors.get(0);
}
return profiles;
}
/* (non-Javadoc)
* @see org.apache.maven.profiles.ProfileManager#addProfiles(java.util.List)
*/
public void addProfiles(List<Profile> profiles) {
for (Profile profile1 : profiles) {
addProfile(profile1);
}
}
public void activateAsDefault(String profileId) {
if (!defaultIds.contains(profileId)) {
defaultIds.add(profileId);
}
}
public List<String> getExplicitlyActivatedIds() {
return activatedIds;
}
public List<String> getExplicitlyDeactivatedIds() {
return deactivatedIds;
}
public List getIdsActivatedByDefault() {
return defaultIds;
}
}
|
String profileId = profile.getId();
Profile existing = profilesById.get(profileId);
if (existing != null) {
logger.warn("Overriding profile: '" + profileId + "' (source: " + existing.getSource()
+ ") with new instance from source: " + profile.getSource());
}
profilesById.put(profile.getId(), profile);
Activation activation = profile.getActivation();
if (activation != null && activation.isActiveByDefault()) {
activateAsDefault(profileId);
}
| 1,273
| 143
| 1,416
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/profiles/ProfilesConversionUtils.java
|
ProfilesConversionUtils
|
convertFromProfileXmlRepository
|
class ProfilesConversionUtils {
private ProfilesConversionUtils() {}
public static Profile convertFromProfileXmlProfile(org.apache.maven.profiles.Profile profileXmlProfile) {
Profile profile = new Profile();
profile.setId(profileXmlProfile.getId());
profile.setSource("profiles.xml");
org.apache.maven.profiles.Activation profileActivation = profileXmlProfile.getActivation();
if (profileActivation != null) {
Activation activation = new Activation();
activation.setActiveByDefault(profileActivation.isActiveByDefault());
activation.setJdk(profileActivation.getJdk());
org.apache.maven.profiles.ActivationProperty profileProp = profileActivation.getProperty();
if (profileProp != null) {
ActivationProperty prop = new ActivationProperty();
prop.setName(profileProp.getName());
prop.setValue(profileProp.getValue());
activation.setProperty(prop);
}
ActivationOS profileOs = profileActivation.getOs();
if (profileOs != null) {
org.apache.maven.model.ActivationOS os = new org.apache.maven.model.ActivationOS();
os.setArch(profileOs.getArch());
os.setFamily(profileOs.getFamily());
os.setName(profileOs.getName());
os.setVersion(profileOs.getVersion());
activation.setOs(os);
}
org.apache.maven.profiles.ActivationFile profileFile = profileActivation.getFile();
if (profileFile != null) {
ActivationFile file = new ActivationFile();
file.setExists(profileFile.getExists());
file.setMissing(profileFile.getMissing());
activation.setFile(file);
}
profile.setActivation(activation);
}
profile.setProperties(profileXmlProfile.getProperties());
List repos = profileXmlProfile.getRepositories();
if (repos != null) {
for (Object repo : repos) {
profile.addRepository(convertFromProfileXmlRepository((org.apache.maven.profiles.Repository) repo));
}
}
List pluginRepos = profileXmlProfile.getPluginRepositories();
if (pluginRepos != null) {
for (Object pluginRepo : pluginRepos) {
profile.addPluginRepository(
convertFromProfileXmlRepository((org.apache.maven.profiles.Repository) pluginRepo));
}
}
return profile;
}
private static Repository convertFromProfileXmlRepository(org.apache.maven.profiles.Repository profileXmlRepo) {<FILL_FUNCTION_BODY>}
private static org.apache.maven.model.RepositoryPolicy convertRepositoryPolicy(RepositoryPolicy profileXmlRepo) {
org.apache.maven.model.RepositoryPolicy policy = new org.apache.maven.model.RepositoryPolicy();
policy.setEnabled(profileXmlRepo.isEnabled());
policy.setUpdatePolicy(profileXmlRepo.getUpdatePolicy());
policy.setChecksumPolicy(profileXmlRepo.getChecksumPolicy());
return policy;
}
}
|
Repository repo = new Repository();
repo.setId(profileXmlRepo.getId());
repo.setLayout(profileXmlRepo.getLayout());
repo.setName(profileXmlRepo.getName());
repo.setUrl(profileXmlRepo.getUrl());
if (profileXmlRepo.getSnapshots() != null) {
repo.setSnapshots(convertRepositoryPolicy(profileXmlRepo.getSnapshots()));
}
if (profileXmlRepo.getReleases() != null) {
repo.setReleases(convertRepositoryPolicy(profileXmlRepo.getReleases()));
}
return repo;
| 811
| 166
| 977
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/profiles/activation/FileProfileActivator.java
|
FileProfileActivator
|
isActive
|
class FileProfileActivator extends DetectedProfileActivator implements LogEnabled {
private Logger logger;
protected boolean canDetectActivation(Profile profile) {
return profile.getActivation() != null && profile.getActivation().getFile() != null;
}
public boolean isActive(Profile profile) {<FILL_FUNCTION_BODY>}
public void enableLogging(Logger logger) {
this.logger = logger;
}
}
|
Activation activation = profile.getActivation();
ActivationFile actFile = activation.getFile();
if (actFile != null) {
// check if the file exists, if it does then the profile will be active
String fileString = actFile.getExists();
RegexBasedInterpolator interpolator = new RegexBasedInterpolator();
try {
interpolator.addValueSource(new EnvarBasedValueSource());
} catch (IOException e) {
// ignored
}
interpolator.addValueSource(new MapBasedValueSource(System.getProperties()));
try {
if (fileString != null && !fileString.isEmpty()) {
fileString = interpolator.interpolate(fileString, "").replace("\\", "/");
File file = new File(fileString);
return file.exists();
}
// check if the file is missing, if it is then the profile will be active
fileString = actFile.getMissing();
if (fileString != null && !fileString.isEmpty()) {
fileString = interpolator.interpolate(fileString, "").replace("\\", "/");
File file = new File(fileString);
return !file.exists();
}
} catch (InterpolationException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to interpolate missing file location for profile activator: " + fileString, e);
} else {
logger.warn("Failed to interpolate missing file location for profile activator: " + fileString
+ ", enable verbose output (-X) for more details");
}
}
}
return false;
| 117
| 412
| 529
|
<methods>public non-sealed void <init>() ,public boolean canDetermineActivation(Profile) <variables>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/profiles/activation/JdkPrefixProfileActivator.java
|
JdkPrefixProfileActivator
|
isActive
|
class JdkPrefixProfileActivator extends DetectedProfileActivator {
private static final String JDK_VERSION = System.getProperty("java.version");
public boolean isActive(Profile profile) throws ProfileActivationException {<FILL_FUNCTION_BODY>}
private boolean matchJdkVersionRange(String jdk) throws InvalidVersionSpecificationException {
VersionRange jdkVersionRange = VersionRange.createFromVersionSpec(convertJdkToMavenVersion(jdk));
DefaultArtifactVersion jdkVersion = new DefaultArtifactVersion(convertJdkToMavenVersion(getJdkVersion()));
return jdkVersionRange.containsVersion(jdkVersion);
}
private String convertJdkToMavenVersion(String jdk) {
return jdk.replace("_", "-");
}
protected String getJdkVersion() {
return JDK_VERSION;
}
protected boolean canDetectActivation(Profile profile) {
return profile.getActivation() != null
&& profile.getActivation().getJdk() != null
&& !profile.getActivation().getJdk().isEmpty();
}
}
|
Activation activation = profile.getActivation();
String jdk = activation.getJdk();
// null case is covered by canDetermineActivation(), so we can do a straight startsWith() here.
if (jdk.startsWith("[") || jdk.startsWith("(")) {
try {
return matchJdkVersionRange(jdk);
} catch (InvalidVersionSpecificationException e) {
throw new ProfileActivationException(
"Invalid JDK version in profile '" + profile.getId() + "': " + e.getMessage());
}
}
boolean reverse = false;
if (jdk.startsWith("!")) {
reverse = true;
jdk = jdk.substring(1);
}
if (getJdkVersion().startsWith(jdk)) {
return !reverse;
} else {
return reverse;
}
| 278
| 226
| 504
|
<methods>public non-sealed void <init>() ,public boolean canDetermineActivation(Profile) <variables>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/profiles/activation/OperatingSystemProfileActivator.java
|
OperatingSystemProfileActivator
|
determineArchMatch
|
class OperatingSystemProfileActivator implements ProfileActivator {
public boolean canDetermineActivation(Profile profile) {
Activation activation = profile.getActivation();
return activation != null && activation.getOs() != null;
}
public boolean isActive(Profile profile) {
Activation activation = profile.getActivation();
ActivationOS os = activation.getOs();
boolean result = ensureAtLeastOneNonNull(os);
if (result && os.getFamily() != null) {
result = determineFamilyMatch(os.getFamily());
}
if (result && os.getName() != null) {
result = determineNameMatch(os.getName());
}
if (result && os.getArch() != null) {
result = determineArchMatch(os.getArch());
}
if (result && os.getVersion() != null) {
result = determineVersionMatch(os.getVersion());
}
return result;
}
private boolean ensureAtLeastOneNonNull(ActivationOS os) {
return os.getArch() != null || os.getFamily() != null || os.getName() != null || os.getVersion() != null;
}
private boolean determineVersionMatch(String version) {
String test = version;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = Os.OS_VERSION.equals(test);
if (reverse) {
return !result;
} else {
return result;
}
}
private boolean determineArchMatch(String arch) {<FILL_FUNCTION_BODY>}
private boolean determineNameMatch(String name) {
String test = name;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = Os.OS_NAME.equals(test);
if (reverse) {
return !result;
} else {
return result;
}
}
private boolean determineFamilyMatch(String family) {
String test = family;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = Os.isFamily(test);
if (reverse) {
return !result;
} else {
return result;
}
}
}
|
String test = arch;
boolean reverse = false;
if (test.startsWith("!")) {
reverse = true;
test = test.substring(1);
}
boolean result = Os.OS_ARCH.equals(test);
if (reverse) {
return !result;
} else {
return result;
}
| 656
| 95
| 751
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/profiles/activation/SystemPropertyProfileActivator.java
|
SystemPropertyProfileActivator
|
isActive
|
class SystemPropertyProfileActivator extends DetectedProfileActivator implements Contextualizable {
private Properties properties;
public void contextualize(Context context) throws ContextException {
properties = (Properties) context.get("SystemProperties");
}
protected boolean canDetectActivation(Profile profile) {
return profile.getActivation() != null && profile.getActivation().getProperty() != null;
}
public boolean isActive(Profile profile) throws ProfileActivationException {<FILL_FUNCTION_BODY>}
}
|
Activation activation = profile.getActivation();
ActivationProperty property = activation.getProperty();
if (property != null) {
String name = property.getName();
boolean reverseName = false;
if (name == null) {
throw new ProfileActivationException(
"The property name is required to activate the profile '" + profile.getId() + "'");
}
if (name.startsWith("!")) {
reverseName = true;
name = name.substring(1);
}
String sysValue = properties.getProperty(name);
String propValue = property.getValue();
if (propValue != null && !propValue.isEmpty()) {
boolean reverseValue = false;
if (propValue.startsWith("!")) {
reverseValue = true;
propValue = propValue.substring(1);
}
// we have a value, so it has to match the system value...
boolean result = propValue.equals(sysValue);
if (reverseValue) {
return !result;
} else {
return result;
}
} else {
boolean result = sysValue != null && !sysValue.isEmpty();
if (reverseName) {
return !result;
} else {
return result;
}
}
}
return false;
| 132
| 344
| 476
|
<methods>public non-sealed void <init>() ,public boolean canDetermineActivation(Profile) <variables>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/DefaultProjectBuilderConfiguration.java
|
DefaultProjectBuilderConfiguration
|
getUserProperties
|
class DefaultProjectBuilderConfiguration implements ProjectBuilderConfiguration {
private ProfileManager globalProfileManager;
private ArtifactRepository localRepository;
private Properties userProperties;
private Properties executionProperties = System.getProperties();
private Date buildStartTime;
public DefaultProjectBuilderConfiguration() {}
public ProjectBuilderConfiguration setGlobalProfileManager(ProfileManager globalProfileManager) {
this.globalProfileManager = globalProfileManager;
return this;
}
public ProfileManager getGlobalProfileManager() {
return globalProfileManager;
}
public ProjectBuilderConfiguration setLocalRepository(ArtifactRepository localRepository) {
this.localRepository = localRepository;
return this;
}
public ArtifactRepository getLocalRepository() {
return localRepository;
}
public ProjectBuilderConfiguration setUserProperties(Properties userProperties) {
this.userProperties = userProperties;
return this;
}
public Properties getUserProperties() {<FILL_FUNCTION_BODY>}
public Properties getExecutionProperties() {
return executionProperties;
}
public ProjectBuilderConfiguration setExecutionProperties(Properties executionProperties) {
this.executionProperties = executionProperties;
return this;
}
public Date getBuildStartTime() {
return buildStartTime;
}
public ProjectBuilderConfiguration setBuildStartTime(Date buildStartTime) {
this.buildStartTime = buildStartTime;
return this;
}
}
|
if (userProperties == null) {
userProperties = new Properties();
}
return userProperties;
| 359
| 31
| 390
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/ProjectUtils.java
|
ProjectUtils
|
buildArtifactRepository
|
class ProjectUtils {
private ProjectUtils() {}
public static List<ArtifactRepository> buildArtifactRepositories(
List<Repository> repositories, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c)
throws InvalidRepositoryException {
List<ArtifactRepository> remoteRepositories = new ArrayList<>();
for (Repository r : repositories) {
remoteRepositories.add(buildArtifactRepository(r, artifactRepositoryFactory, c));
}
return remoteRepositories;
}
public static ArtifactRepository buildDeploymentArtifactRepository(
DeploymentRepository repo, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c)
throws InvalidRepositoryException {
return buildArtifactRepository(repo, artifactRepositoryFactory, c);
}
public static ArtifactRepository buildArtifactRepository(
Repository repo, ArtifactRepositoryFactory artifactRepositoryFactory, PlexusContainer c)
throws InvalidRepositoryException {<FILL_FUNCTION_BODY>}
private static RepositorySystem rs(PlexusContainer c) {
try {
return c.lookup(RepositorySystem.class);
} catch (ComponentLookupException e) {
throw new IllegalStateException(e);
}
}
private static RepositorySystemSession rss(PlexusContainer c) {
try {
LegacySupport legacySupport = c.lookup(LegacySupport.class);
return legacySupport.getRepositorySession();
} catch (ComponentLookupException e) {
throw new IllegalStateException(e);
}
}
}
|
RepositorySystem repositorySystem = rs(c);
RepositorySystemSession session = rss(c);
ArtifactRepository repository = repositorySystem.buildArtifactRepository(repo);
if (session != null) {
repositorySystem.injectMirror(session, Arrays.asList(repository));
repositorySystem.injectProxy(session, Arrays.asList(repository));
repositorySystem.injectAuthentication(session, Arrays.asList(repository));
}
return repository;
| 392
| 126
| 518
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/artifact/DefaultMavenMetadataCache.java
|
CacheKey
|
repositoriesEquals
|
class CacheKey {
private final Artifact artifact;
private final long pomHash;
private final boolean resolveManagedVersions;
private final List<ArtifactRepository> repositories = new ArrayList<>();
private final int hashCode;
public CacheKey(
Artifact artifact,
boolean resolveManagedVersions,
ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories) {
File file = artifact.getFile();
this.artifact = ArtifactUtils.copyArtifact(artifact);
if ("pom".equals(artifact.getType()) && file != null) {
pomHash = file.getPath().hashCode() + file.lastModified();
} else {
pomHash = 0;
}
this.resolveManagedVersions = resolveManagedVersions;
this.repositories.add(localRepository);
this.repositories.addAll(remoteRepositories);
int hash = 17;
hash = hash * 31 + artifactHashCode(artifact);
hash = hash * 31 + (resolveManagedVersions ? 1 : 2);
hash = hash * 31 + repositoriesHashCode(repositories);
this.hashCode = hash;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof CacheKey)) {
return false;
}
CacheKey other = (CacheKey) o;
return pomHash == other.pomHash
&& artifactEquals(artifact, other.artifact)
&& resolveManagedVersions == other.resolveManagedVersions
&& repositoriesEquals(repositories, other.repositories);
}
}
private static int artifactHashCode(Artifact a) {
int result = 17;
result = 31 * result + a.getGroupId().hashCode();
result = 31 * result + a.getArtifactId().hashCode();
result = 31 * result + a.getType().hashCode();
if (a.getVersion() != null) {
result = 31 * result + a.getVersion().hashCode();
}
result = 31 * result + (a.getClassifier() != null ? a.getClassifier().hashCode() : 0);
result = 31 * result + (a.getScope() != null ? a.getScope().hashCode() : 0);
result = 31 * result
+ (a.getDependencyFilter() != null ? a.getDependencyFilter().hashCode() : 0);
result = 31 * result + (a.isOptional() ? 1 : 0);
return result;
}
private static boolean artifactEquals(Artifact a1, Artifact a2) {
if (a1 == a2) {
return true;
}
return Objects.equals(a1.getGroupId(), a2.getGroupId())
&& Objects.equals(a1.getArtifactId(), a2.getArtifactId())
&& Objects.equals(a1.getType(), a2.getType())
&& Objects.equals(a1.getVersion(), a2.getVersion())
&& Objects.equals(a1.getClassifier(), a2.getClassifier())
&& Objects.equals(a1.getScope(), a2.getScope())
&& Objects.equals(a1.getDependencyFilter(), a2.getDependencyFilter())
&& a1.isOptional() == a2.isOptional();
}
private static int repositoryHashCode(ArtifactRepository repository) {
int result = 17;
result = 31 * result + (repository.getId() != null ? repository.getId().hashCode() : 0);
return result;
}
private static int repositoriesHashCode(List<ArtifactRepository> repositories) {
int result = 17;
for (ArtifactRepository repository : repositories) {
result = 31 * result + repositoryHashCode(repository);
}
return result;
}
private static boolean repositoryEquals(ArtifactRepository r1, ArtifactRepository r2) {
if (r1 == r2) {
return true;
}
return Objects.equals(r1.getId(), r2.getId())
&& Objects.equals(r1.getUrl(), r2.getUrl())
&& repositoryPolicyEquals(r1.getReleases(), r2.getReleases())
&& repositoryPolicyEquals(r1.getSnapshots(), r2.getSnapshots());
}
private static boolean repositoryPolicyEquals(ArtifactRepositoryPolicy p1, ArtifactRepositoryPolicy p2) {
if (p1 == p2) {
return true;
}
return p1.isEnabled() == p2.isEnabled() && Objects.equals(p1.getUpdatePolicy(), p2.getUpdatePolicy());
}
private static boolean repositoriesEquals(List<ArtifactRepository> r1, List<ArtifactRepository> r2) {<FILL_FUNCTION_BODY>
|
if (r1.size() != r2.size()) {
return false;
}
for (Iterator<ArtifactRepository> it1 = r1.iterator(), it2 = r2.iterator(); it1.hasNext(); ) {
if (!repositoryEquals(it1.next(), it2.next())) {
return false;
}
}
return true;
| 1,292
| 98
| 1,390
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/artifact/ProjectArtifactMetadata.java
|
ProjectArtifactMetadata
|
storeInLocalRepository
|
class ProjectArtifactMetadata extends AbstractArtifactMetadata {
private final File file;
public ProjectArtifactMetadata(Artifact artifact) {
this(artifact, null);
}
public ProjectArtifactMetadata(Artifact artifact, File file) {
super(artifact);
this.file = file;
}
public File getFile() {
return file;
}
public String getRemoteFilename() {
return getFilename();
}
public String getLocalFilename(ArtifactRepository repository) {
return getFilename();
}
private String getFilename() {
return getArtifactId() + "-" + artifact.getVersion() + ".pom";
}
public void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository)
throws RepositoryMetadataStoreException {<FILL_FUNCTION_BODY>}
public String toString() {
return "project information for " + artifact.getArtifactId() + " " + artifact.getVersion();
}
public boolean storedInArtifactVersionDirectory() {
return true;
}
public String getBaseVersion() {
return artifact.getBaseVersion();
}
public Object getKey() {
return "project " + artifact.getGroupId() + ":" + artifact.getArtifactId();
}
public void merge(ArtifactMetadata metadata) {
ProjectArtifactMetadata m = (ProjectArtifactMetadata) metadata;
if (!m.file.equals(file)) {
throw new IllegalStateException("Cannot add two different pieces of metadata for: " + getKey());
}
}
public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata) {
this.merge((ArtifactMetadata) metadata);
}
}
|
File destination = new File(
localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata(this, remoteRepository));
// ----------------------------------------------------------------------------
// I'm fully aware that the file could just be moved using File.rename but
// there are bugs in various JVM that have problems doing this across
// different filesystem. So we'll incur the small hit to actually copy
// here and be safe. jvz.
// ----------------------------------------------------------------------------
try {
Files.createDirectories(destination.toPath().getParent());
Files.copy(file.toPath(), destination.toPath());
} catch (IOException e) {
throw new RepositoryMetadataStoreException("Error copying POM to the local repository.", e);
}
| 449
| 182
| 631
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/interpolation/BuildTimestampValueSource.java
|
BuildTimestampValueSource
|
getValue
|
class BuildTimestampValueSource extends AbstractValueSource {
private final Date startTime;
private final String format;
private String formattedDate;
public BuildTimestampValueSource(Date startTime, String format) {
super(false);
this.startTime = startTime;
this.format = format;
}
public Object getValue(String expression) {<FILL_FUNCTION_BODY>}
}
|
if ("build.timestamp".equals(expression) || "maven.build.timestamp".equals(expression)) {
if (formattedDate == null && startTime != null) {
formattedDate = new SimpleDateFormat(format).format(startTime);
}
return formattedDate;
}
return null;
| 106
| 81
| 187
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/interpolation/PathTranslatingPostProcessor.java
|
PathTranslatingPostProcessor
|
execute
|
class PathTranslatingPostProcessor implements InterpolationPostProcessor {
private final List<String> unprefixedPathKeys;
private final File projectDir;
private final PathTranslator pathTranslator;
private final List<String> expressionPrefixes;
public PathTranslatingPostProcessor(
List<String> expressionPrefixes,
List<String> unprefixedPathKeys,
File projectDir,
PathTranslator pathTranslator) {
this.expressionPrefixes = expressionPrefixes;
this.unprefixedPathKeys = unprefixedPathKeys;
this.projectDir = projectDir;
this.pathTranslator = pathTranslator;
}
public Object execute(String expression, Object value) {<FILL_FUNCTION_BODY>}
}
|
expression = ValueSourceUtils.trimPrefix(expression, expressionPrefixes, true);
if (projectDir != null && value != null && unprefixedPathKeys.contains(expression)) {
return pathTranslator.alignToBaseDirectory(String.valueOf(value), projectDir);
}
return value;
| 197
| 81
| 278
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/interpolation/StringSearchModelInterpolator.java
|
InterpolateObjectAction
|
traverseObjectWithParents
|
class InterpolateObjectAction implements PrivilegedAction<ModelInterpolationException> {
private final boolean debugEnabled;
private final LinkedList<Object> interpolationTargets;
private final StringSearchModelInterpolator modelInterpolator;
private final Logger logger;
private final List<ValueSource> valueSources;
private final List<InterpolationPostProcessor> postProcessors;
InterpolateObjectAction(
Object target,
List<ValueSource> valueSources,
List<InterpolationPostProcessor> postProcessors,
boolean debugEnabled,
StringSearchModelInterpolator modelInterpolator,
Logger logger) {
this.valueSources = valueSources;
this.postProcessors = postProcessors;
this.debugEnabled = debugEnabled;
this.interpolationTargets = new LinkedList<>();
interpolationTargets.add(target);
this.modelInterpolator = modelInterpolator;
this.logger = logger;
}
public ModelInterpolationException run() {
while (!interpolationTargets.isEmpty()) {
Object obj = interpolationTargets.removeFirst();
try {
traverseObjectWithParents(obj.getClass(), obj);
} catch (ModelInterpolationException e) {
return e;
}
}
return null;
}
@SuppressWarnings({"unchecked", "checkstyle:methodlength"})
private void traverseObjectWithParents(Class<?> cls, Object target) throws ModelInterpolationException {<FILL_FUNCTION_BODY>}
private boolean isQualifiedForInterpolation(Class<?> cls) {
return !cls.getPackage().getName().startsWith("java")
&& !cls.getPackage().getName().startsWith("sun.nio.fs");
}
private boolean isQualifiedForInterpolation(Field field, Class<?> fieldType) {
if (!PRIMITIVE_BY_CLASS.containsKey(fieldType)) {
PRIMITIVE_BY_CLASS.put(fieldType, fieldType.isPrimitive());
}
if (PRIMITIVE_BY_CLASS.get(fieldType)) {
return false;
}
// if ( fieldType.isPrimitive() )
// {
// return false;
// }
return !"parent".equals(field.getName());
}
private void evaluateArray(Object target) throws ModelInterpolationException {
int len = Array.getLength(target);
for (int i = 0; i < len; i++) {
Object value = Array.get(target, i);
if (value != null) {
if (String.class == value.getClass()) {
String interpolated = modelInterpolator.interpolateInternal(
(String) value, valueSources, postProcessors, debugEnabled);
if (!interpolated.equals(value)) {
Array.set(target, i, interpolated);
}
} else {
interpolationTargets.add(value);
}
}
}
}
}
|
if (cls == null) {
return;
}
if (cls.isArray()) {
evaluateArray(target);
} else if (isQualifiedForInterpolation(cls)) {
Field[] fields = FIELDS_BY_CLASS.computeIfAbsent(cls, k -> cls.getDeclaredFields());
for (Field field : fields) {
Class<?> type = field.getType();
if (isQualifiedForInterpolation(field, type)) {
boolean isAccessible = field.isAccessible();
field.setAccessible(true);
try {
try {
if (String.class == type) {
String value = (String) field.get(target);
if (value != null) {
String interpolated = modelInterpolator.interpolateInternal(
value, valueSources, postProcessors, debugEnabled);
if (!interpolated.equals(value)) {
field.set(target, interpolated);
}
}
} else if (Collection.class.isAssignableFrom(type)) {
Collection<Object> c = (Collection<Object>) field.get(target);
if (c != null && !c.isEmpty()) {
List<Object> originalValues = new ArrayList<>(c);
try {
c.clear();
} catch (UnsupportedOperationException e) {
if (debugEnabled && logger != null) {
logger.debug("Skipping interpolation of field: " + field + " in: "
+ cls.getName()
+ "; it is an unmodifiable collection.");
}
continue;
}
for (Object value : originalValues) {
if (value != null) {
if (String.class == value.getClass()) {
String interpolated = modelInterpolator.interpolateInternal(
(String) value, valueSources, postProcessors, debugEnabled);
if (!interpolated.equals(value)) {
c.add(interpolated);
} else {
c.add(value);
}
} else {
c.add(value);
if (value.getClass().isArray()) {
evaluateArray(value);
} else {
interpolationTargets.add(value);
}
}
} else {
// add the null back in...not sure what else to do...
c.add(value);
}
}
}
} else if (Map.class.isAssignableFrom(type)) {
Map<Object, Object> m = (Map<Object, Object>) field.get(target);
if (m != null && !m.isEmpty()) {
for (Map.Entry<Object, Object> entry : m.entrySet()) {
Object value = entry.getValue();
if (value != null) {
if (String.class == value.getClass()) {
String interpolated = modelInterpolator.interpolateInternal(
(String) value, valueSources, postProcessors, debugEnabled);
if (!interpolated.equals(value)) {
try {
entry.setValue(interpolated);
} catch (UnsupportedOperationException e) {
if (debugEnabled && logger != null) {
logger.debug("Skipping interpolation of field: " + field
+ " (key: " + entry.getKey() + ") in: "
+ cls.getName()
+ "; it is an unmodifiable collection.");
}
}
}
} else {
if (value.getClass().isArray()) {
evaluateArray(value);
} else {
interpolationTargets.add(value);
}
}
}
}
}
} else {
Object value = field.get(target);
if (value != null) {
if (field.getType().isArray()) {
evaluateArray(value);
} else {
interpolationTargets.add(value);
}
}
}
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new ModelInterpolationException(
"Failed to interpolate field: " + field + " on class: " + cls.getName(), e);
}
} finally {
field.setAccessible(isAccessible);
}
}
}
traverseObjectWithParents(cls.getSuperclass(), target);
}
| 790
| 1,141
| 1,931
|
<methods>public void initialize() throws org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException,public Model interpolate(Model, Map<java.lang.String,?>) throws org.apache.maven.project.interpolation.ModelInterpolationException,public Model interpolate(Model, Map<java.lang.String,?>, boolean) throws org.apache.maven.project.interpolation.ModelInterpolationException,public Model interpolate(Model, java.io.File, org.apache.maven.project.ProjectBuilderConfiguration, boolean) throws org.apache.maven.project.interpolation.ModelInterpolationException,public java.lang.String interpolate(java.lang.String, Model, java.io.File, org.apache.maven.project.ProjectBuilderConfiguration, boolean) throws org.apache.maven.project.interpolation.ModelInterpolationException<variables>private static final List<java.lang.String> PROJECT_PREFIXES,private static final non-sealed List<java.lang.String> TRANSLATED_PATH_EXPRESSIONS,private Interpolator interpolator,private org.apache.maven.project.path.PathTranslator pathTranslator,private RecursionInterceptor recursionInterceptor
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/path/DefaultPathTranslator.java
|
DefaultPathTranslator
|
unalignFromBaseDirectory
|
class DefaultPathTranslator implements PathTranslator {
private static final String[] BASEDIR_EXPRESSIONS = {"${basedir}", "${pom.basedir}", "${project.basedir}"};
public void alignToBaseDirectory(Model model, File basedir) {
if (basedir == null) {
return;
}
Build build = model.getBuild();
if (build != null) {
build.setDirectory(alignToBaseDirectory(build.getDirectory(), basedir));
build.setSourceDirectory(alignToBaseDirectory(build.getSourceDirectory(), basedir));
build.setTestSourceDirectory(alignToBaseDirectory(build.getTestSourceDirectory(), basedir));
for (Resource resource : build.getResources()) {
resource.setDirectory(alignToBaseDirectory(resource.getDirectory(), basedir));
}
for (Resource resource : build.getTestResources()) {
resource.setDirectory(alignToBaseDirectory(resource.getDirectory(), basedir));
}
if (build.getFilters() != null) {
List<String> filters = new ArrayList<>();
for (String filter : build.getFilters()) {
filters.add(alignToBaseDirectory(filter, basedir));
}
build.setFilters(filters);
}
build.setOutputDirectory(alignToBaseDirectory(build.getOutputDirectory(), basedir));
build.setTestOutputDirectory(alignToBaseDirectory(build.getTestOutputDirectory(), basedir));
}
Reporting reporting = model.getReporting();
if (reporting != null) {
reporting.setOutputDirectory(alignToBaseDirectory(reporting.getOutputDirectory(), basedir));
}
}
public String alignToBaseDirectory(String path, File basedir) {
if (basedir == null) {
return path;
}
if (path == null) {
return null;
}
String s = stripBasedirToken(path);
File file = new File(s);
if (file.isAbsolute()) {
// path was already absolute, just normalize file separator and we're done
s = file.getPath();
} else if (file.getPath().startsWith(File.separator)) {
// drive-relative Windows path, don't align with project directory but with drive root
s = file.getAbsolutePath();
} else {
// an ordinary relative path, align with project directory
s = new File(new File(basedir, s).toURI().normalize()).getAbsolutePath();
}
return s;
}
private String stripBasedirToken(String s) {
if (s != null) {
String basedirExpr = null;
for (String expression : BASEDIR_EXPRESSIONS) {
if (s.startsWith(expression)) {
basedirExpr = expression;
break;
}
}
if (basedirExpr != null) {
if (s.length() > basedirExpr.length()) {
// Take out basedir expression and the leading slash
s = chopLeadingFileSeparator(s.substring(basedirExpr.length()));
} else {
s = ".";
}
}
}
return s;
}
/**
* Removes the leading directory separator from the specified filesystem path (if any). For platform-independent
* behavior, this method accepts both the forward slash and the backward slash as separator.
*
* @param path The filesystem path, may be <code>null</code>.
* @return The altered filesystem path or <code>null</code> if the input path was <code>null</code>.
*/
private String chopLeadingFileSeparator(String path) {
if (path != null) {
if (path.startsWith("/") || path.startsWith("\\")) {
path = path.substring(1);
}
}
return path;
}
public void unalignFromBaseDirectory(Model model, File basedir) {<FILL_FUNCTION_BODY>}
public String unalignFromBaseDirectory(String path, File basedir) {
if (basedir == null) {
return path;
}
if (path == null) {
return null;
}
path = path.trim();
String base = basedir.getAbsolutePath();
if (path.startsWith(base)) {
path = chopLeadingFileSeparator(path.substring(base.length()));
}
if (path.isEmpty()) {
path = ".";
}
if (!new File(path).isAbsolute()) {
path = path.replace('\\', '/');
}
return path;
}
}
|
if (basedir == null) {
return;
}
Build build = model.getBuild();
if (build != null) {
build.setDirectory(unalignFromBaseDirectory(build.getDirectory(), basedir));
build.setSourceDirectory(unalignFromBaseDirectory(build.getSourceDirectory(), basedir));
build.setTestSourceDirectory(unalignFromBaseDirectory(build.getTestSourceDirectory(), basedir));
for (Resource resource : build.getResources()) {
resource.setDirectory(unalignFromBaseDirectory(resource.getDirectory(), basedir));
}
for (Resource resource : build.getTestResources()) {
resource.setDirectory(unalignFromBaseDirectory(resource.getDirectory(), basedir));
}
if (build.getFilters() != null) {
List<String> filters = new ArrayList<>();
for (String filter : build.getFilters()) {
filters.add(unalignFromBaseDirectory(filter, basedir));
}
build.setFilters(filters);
}
build.setOutputDirectory(unalignFromBaseDirectory(build.getOutputDirectory(), basedir));
build.setTestOutputDirectory(unalignFromBaseDirectory(build.getTestOutputDirectory(), basedir));
}
Reporting reporting = model.getReporting();
if (reporting != null) {
reporting.setOutputDirectory(unalignFromBaseDirectory(reporting.getOutputDirectory(), basedir));
}
| 1,219
| 371
| 1,590
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/validation/DefaultModelValidator.java
|
DefaultModelValidator
|
validate
|
class DefaultModelValidator implements ModelValidator {
@Inject
private org.apache.maven.model.validation.ModelValidator modelValidator;
public ModelValidationResult validate(Model model) {<FILL_FUNCTION_BODY>}
private static class SimpleModelProblemCollector implements ModelProblemCollector {
ModelValidationResult result;
SimpleModelProblemCollector(ModelValidationResult result) {
this.result = result;
}
public void add(ModelProblemCollectorRequest req) {
if (!ModelProblem.Severity.WARNING.equals(req.getSeverity())) {
result.addMessage(req.getMessage());
}
}
}
}
|
ModelValidationResult result = new ModelValidationResult();
ModelBuildingRequest request =
new DefaultModelBuildingRequest().setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0);
SimpleModelProblemCollector problems = new SimpleModelProblemCollector(result);
modelValidator.validateEffectiveModel(model, request, problems);
return result;
| 174
| 97
| 271
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/project/validation/ModelValidationResult.java
|
ModelValidationResult
|
render
|
class ModelValidationResult {
/** */
private static final String LS = System.lineSeparator();
/** */
private List<String> messages;
public ModelValidationResult() {
messages = new ArrayList<>();
}
public int getMessageCount() {
return messages.size();
}
public String getMessage(int i) {
return messages.get(i);
}
public List<String> getMessages() {
return Collections.unmodifiableList(messages);
}
public void addMessage(String message) {
messages.add(message);
}
public String toString() {
return render("");
}
public String render(String indentation) {<FILL_FUNCTION_BODY>}
}
|
if (messages.size() == 0) {
return indentation + "There were no validation errors.";
}
StringBuilder message = new StringBuilder();
// if ( messages.size() == 1 )
// {
// message.append( "There was 1 validation error: " );
// }
// else
// {
// message.append( "There was " + messages.size() + " validation errors: " + LS );
// }
//
for (int i = 0; i < messages.size(); i++) {
message.append(indentation)
.append('[')
.append(i)
.append("] ")
.append(messages.get(i))
.append(LS);
}
return message.toString();
| 200
| 210
| 410
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/ArtifactTransferEvent.java
|
ArtifactTransferEvent
|
toString
|
class ArtifactTransferEvent extends EventObject {
/**
* A transfer was attempted, but has not yet commenced.
*/
public static final int TRANSFER_INITIATED = 0;
/**
* A transfer was started.
*/
public static final int TRANSFER_STARTED = 1;
/**
* A transfer is completed.
*/
public static final int TRANSFER_COMPLETED = 2;
/**
* A transfer is in progress.
*/
public static final int TRANSFER_PROGRESS = 3;
/**
* An error occurred during transfer
*/
public static final int TRANSFER_ERROR = 4;
/**
* Indicates GET transfer (from the repository)
*/
public static final int REQUEST_GET = 5;
/**
* Indicates PUT transfer (to the repository)
*/
public static final int REQUEST_PUT = 6;
private int eventType;
private int requestType;
private Exception exception;
private File localFile;
private ArtifactTransferResource artifact;
private long transferredBytes;
private byte[] dataBuffer;
private int dataOffset;
private int dataLength;
public ArtifactTransferEvent(
String wagon, final int eventType, final int requestType, ArtifactTransferResource artifact) {
super(wagon);
setEventType(eventType);
setRequestType(requestType);
this.artifact = artifact;
}
public ArtifactTransferEvent(
String wagon, final Exception exception, final int requestType, ArtifactTransferResource artifact) {
this(wagon, TRANSFER_ERROR, requestType, artifact);
this.exception = exception;
}
public ArtifactTransferResource getResource() {
return artifact;
}
/**
* @return Returns the exception.
*/
public Exception getException() {
return exception;
}
/**
* Returns the request type.
*
* @return Returns the request type. The Request type is one of
* <code>TransferEvent.REQUEST_GET</code> or <code>TransferEvent.REQUEST_PUT</code>
*/
public int getRequestType() {
return requestType;
}
/**
* Sets the request type
*
* @param requestType The requestType to set.
* The Request type value should be either
* <code>TransferEvent.REQUEST_GET</code> or <code>TransferEvent.REQUEST_PUT</code>.
* @throws IllegalArgumentException when
*/
public void setRequestType(final int requestType) {
switch (requestType) {
case REQUEST_PUT:
break;
case REQUEST_GET:
break;
default:
throw new IllegalArgumentException("Illegal request type: " + requestType);
}
this.requestType = requestType;
}
/**
* @return Returns the eventType.
*/
public int getEventType() {
return eventType;
}
/**
* @param eventType The eventType to set.
*/
public void setEventType(final int eventType) {
switch (eventType) {
case TRANSFER_INITIATED:
break;
case TRANSFER_STARTED:
break;
case TRANSFER_COMPLETED:
break;
case TRANSFER_PROGRESS:
break;
case TRANSFER_ERROR:
break;
default:
throw new IllegalArgumentException("Illegal event type: " + eventType);
}
this.eventType = eventType;
}
/**
* @return Returns the local file.
*/
public File getLocalFile() {
return localFile;
}
/**
* @param localFile The local file to set.
*/
public void setLocalFile(File localFile) {
this.localFile = localFile;
}
public long getTransferredBytes() {
return transferredBytes;
}
public void setTransferredBytes(long transferredBytes) {
this.transferredBytes = transferredBytes;
}
public byte[] getDataBuffer() {
return dataBuffer;
}
public void setDataBuffer(byte[] dataBuffer) {
this.dataBuffer = dataBuffer;
}
public int getDataOffset() {
return dataOffset;
}
public void setDataOffset(int dataOffset) {
this.dataOffset = dataOffset;
}
public int getDataLength() {
return dataLength;
}
public void setDataLength(int dataLength) {
this.dataLength = dataLength;
}
public String toString() {<FILL_FUNCTION_BODY>}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + eventType;
result = prime * result + ((exception == null) ? 0 : exception.hashCode());
result = prime * result + ((localFile == null) ? 0 : localFile.hashCode());
result = prime * result + requestType;
return result;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false;
}
final ArtifactTransferEvent other = (ArtifactTransferEvent) obj;
if (eventType != other.eventType) {
return false;
}
if (exception == null) {
if (other.exception != null) {
return false;
}
} else if (!exception.getClass().equals(other.exception.getClass())) {
return false;
}
if (requestType != other.requestType) {
return false;
} else {
return source.equals(other.source);
}
}
}
|
StringBuilder sb = new StringBuilder(64);
sb.append("TransferEvent[");
switch (this.getRequestType()) {
case REQUEST_GET:
sb.append("GET");
break;
case REQUEST_PUT:
sb.append("PUT");
break;
default:
sb.append(this.getRequestType());
break;
}
sb.append('|');
switch (this.getEventType()) {
case TRANSFER_COMPLETED:
sb.append("COMPLETED");
break;
case TRANSFER_ERROR:
sb.append("ERROR");
break;
case TRANSFER_INITIATED:
sb.append("INITIATED");
break;
case TRANSFER_PROGRESS:
sb.append("PROGRESS");
break;
case TRANSFER_STARTED:
sb.append("STARTED");
break;
default:
sb.append(this.getEventType());
break;
}
sb.append('|');
sb.append(this.getLocalFile()).append('|');
sb.append(']');
return sb.toString();
| 1,534
| 308
| 1,842
|
<methods>public void <init>(java.lang.Object) ,public java.lang.Object getSource() ,public java.lang.String toString() <variables>private static final long serialVersionUID,protected transient java.lang.Object source
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/DefaultMirrorSelector.java
|
DefaultMirrorSelector
|
matchesLayout
|
class DefaultMirrorSelector implements MirrorSelector {
private static final String WILDCARD = "*";
private static final String EXTERNAL_WILDCARD = "external:*";
private static final String EXTERNAL_HTTP_WILDCARD = "external:http:*";
public Mirror getMirror(ArtifactRepository repository, List<Mirror> mirrors) {
String repoId = repository.getId();
if (repoId != null && mirrors != null) {
for (Mirror mirror : mirrors) {
if (repoId.equals(mirror.getMirrorOf()) && matchesLayout(repository, mirror)) {
return mirror;
}
}
for (Mirror mirror : mirrors) {
if (matchPattern(repository, mirror.getMirrorOf()) && matchesLayout(repository, mirror)) {
return mirror;
}
}
}
return null;
}
/**
* This method checks if the pattern matches the originalRepository. Valid patterns:
* <ul>
* <li>{@code *} = everything,</li>
* <li>{@code external:*} = everything not on the localhost and not file based,</li>
* <li>{@code external:http:*} = any repository not on the localhost using HTTP,</li>
* <li>{@code repo,repo1} = {@code repo} or {@code repo1},</li>
* <li>{@code *,!repo1} = everything except {@code repo1}.</li>
* </ul>
*
* @param originalRepository to compare for a match.
* @param pattern used for match.
* @return true if the repository is a match to this pattern.
*/
static boolean matchPattern(ArtifactRepository originalRepository, String pattern) {
boolean result = false;
String originalId = originalRepository.getId();
// simple checks first to short circuit processing below.
if (WILDCARD.equals(pattern) || pattern.equals(originalId)) {
result = true;
} else {
// process the list
String[] repos = pattern.split(",");
for (String repo : repos) {
repo = repo.trim();
// see if this is a negative match
if (repo.length() > 1 && repo.startsWith("!")) {
if (repo.substring(1).equals(originalId)) {
// explicitly exclude. Set result and stop processing.
result = false;
break;
}
}
// check for exact match
else if (repo.equals(originalId)) {
result = true;
break;
}
// check for external:*
else if (EXTERNAL_WILDCARD.equals(repo) && isExternalRepo(originalRepository)) {
result = true;
// don't stop processing in case a future segment explicitly excludes this repo
}
// check for external:http:*
else if (EXTERNAL_HTTP_WILDCARD.equals(repo) && isExternalHttpRepo(originalRepository)) {
result = true;
// don't stop processing in case a future segment explicitly excludes this repo
} else if (WILDCARD.equals(repo)) {
result = true;
// don't stop processing in case a future segment explicitly excludes this repo
}
}
}
return result;
}
/**
* Checks the URL to see if this repository refers to an external repository
*
* @param originalRepository
* @return true if external.
*/
static boolean isExternalRepo(ArtifactRepository originalRepository) {
try {
URL url = new URL(originalRepository.getUrl());
return !(isLocal(url.getHost()) || url.getProtocol().equals("file"));
} catch (MalformedURLException e) {
// bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
return false;
}
}
private static boolean isLocal(String host) {
return "localhost".equals(host) || "127.0.0.1".equals(host);
}
/**
* Checks the URL to see if this repository refers to a non-localhost repository using HTTP.
*
* @param originalRepository
* @return true if external.
*/
static boolean isExternalHttpRepo(ArtifactRepository originalRepository) {
try {
URL url = new URL(originalRepository.getUrl());
return ("http".equalsIgnoreCase(url.getProtocol())
|| "dav".equalsIgnoreCase(url.getProtocol())
|| "dav:http".equalsIgnoreCase(url.getProtocol())
|| "dav+http".equalsIgnoreCase(url.getProtocol()))
&& !isLocal(url.getHost());
} catch (MalformedURLException e) {
// bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
return false;
}
}
static boolean matchesLayout(ArtifactRepository repository, Mirror mirror) {
return matchesLayout(RepositoryUtils.getLayout(repository), mirror.getMirrorOfLayouts());
}
/**
* Checks whether the layouts configured for a mirror match with the layout of the repository.
*
* @param repoLayout The layout of the repository, may be {@code null}.
* @param mirrorLayout The layouts supported by the mirror, may be {@code null}.
* @return {@code true} if the layouts associated with the mirror match the layout of the original repository,
* {@code false} otherwise.
*/
static boolean matchesLayout(String repoLayout, String mirrorLayout) {<FILL_FUNCTION_BODY>}
}
|
boolean result = false;
// simple checks first to short circuit processing below.
if ((mirrorLayout == null || mirrorLayout.isEmpty()) || WILDCARD.equals(mirrorLayout)) {
result = true;
} else if (mirrorLayout.equals(repoLayout)) {
result = true;
} else {
// process the list
String[] layouts = mirrorLayout.split(",");
for (String layout : layouts) {
// see if this is a negative match
if (layout.length() > 1 && layout.startsWith("!")) {
if (layout.substring(1).equals(repoLayout)) {
// explicitly exclude. Set result and stop processing.
result = false;
break;
}
}
// check for exact match
else if (layout.equals(repoLayout)) {
result = true;
break;
} else if (WILDCARD.equals(layout)) {
result = true;
// don't stop processing in case a future segment explicitly excludes this repo
}
}
}
return result;
| 1,446
| 275
| 1,721
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/DelegatingLocalArtifactRepository.java
|
DelegatingLocalArtifactRepository
|
equals
|
class DelegatingLocalArtifactRepository extends MavenArtifactRepository {
private LocalArtifactRepository buildReactor;
private LocalArtifactRepository ideWorkspace;
private ArtifactRepository userLocalArtifactRepository;
public DelegatingLocalArtifactRepository(ArtifactRepository artifactRepository) {
this.userLocalArtifactRepository = artifactRepository;
}
public void setBuildReactor(LocalArtifactRepository localRepository) {
this.buildReactor = localRepository;
}
public void setIdeWorkspace(LocalArtifactRepository localRepository) {
this.ideWorkspace = localRepository;
}
/**
* @deprecated instead use {@link #getIdeWorkspace()}
*/
@Deprecated
public LocalArtifactRepository getIdeWorspace() {
return ideWorkspace;
}
public LocalArtifactRepository getIdeWorkspace() {
return getIdeWorspace();
}
@Override
public Artifact find(Artifact artifact) {
if (!artifact.isRelease() && buildReactor != null) {
artifact = buildReactor.find(artifact);
}
if (!artifact.isResolved() && ideWorkspace != null) {
artifact = ideWorkspace.find(artifact);
}
if (!artifact.isResolved()) {
artifact = userLocalArtifactRepository.find(artifact);
}
return artifact;
}
@Override
public List<String> findVersions(Artifact artifact) {
Collection<String> versions = new LinkedHashSet<>();
if (buildReactor != null) {
versions.addAll(buildReactor.findVersions(artifact));
}
if (ideWorkspace != null) {
versions.addAll(ideWorkspace.findVersions(artifact));
}
versions.addAll(userLocalArtifactRepository.findVersions(artifact));
return Collections.unmodifiableList(new ArrayList<>(versions));
}
public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
return userLocalArtifactRepository.pathOfLocalRepositoryMetadata(metadata, repository);
}
public String getId() {
return userLocalArtifactRepository.getId();
}
@Override
public String pathOf(Artifact artifact) {
return userLocalArtifactRepository.pathOf(artifact);
}
@Override
public String getBasedir() {
return (userLocalArtifactRepository != null) ? userLocalArtifactRepository.getBasedir() : null;
}
@Override
public ArtifactRepositoryLayout getLayout() {
return userLocalArtifactRepository.getLayout();
}
@Override
public ArtifactRepositoryPolicy getReleases() {
return userLocalArtifactRepository.getReleases();
}
@Override
public ArtifactRepositoryPolicy getSnapshots() {
return userLocalArtifactRepository.getSnapshots();
}
@Override
public String getKey() {
return userLocalArtifactRepository.getKey();
}
@Override
public String getUrl() {
return userLocalArtifactRepository.getUrl();
}
@Override
public int hashCode() {
int hash = 17;
hash = hash * 31 + (buildReactor == null ? 0 : buildReactor.hashCode());
hash = hash * 31 + (ideWorkspace == null ? 0 : ideWorkspace.hashCode());
hash = hash * 31 + (userLocalArtifactRepository == null ? 0 : userLocalArtifactRepository.hashCode());
return hash;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
DelegatingLocalArtifactRepository other = (DelegatingLocalArtifactRepository) obj;
return eq(buildReactor, other.buildReactor)
&& eq(ideWorkspace, other.ideWorkspace)
&& eq(userLocalArtifactRepository, other.userLocalArtifactRepository);
| 943
| 133
| 1,076
|
<methods>public void <init>() ,public void <init>(java.lang.String, java.lang.String, org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout, org.apache.maven.artifact.repository.ArtifactRepositoryPolicy, org.apache.maven.artifact.repository.ArtifactRepositoryPolicy) ,public boolean equals(java.lang.Object) ,public org.apache.maven.artifact.Artifact find(org.apache.maven.artifact.Artifact) ,public List<java.lang.String> findVersions(org.apache.maven.artifact.Artifact) ,public org.apache.maven.artifact.repository.Authentication getAuthentication() ,public java.lang.String getBasedir() ,public java.lang.String getId() ,public java.lang.String getKey() ,public org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout getLayout() ,public List<org.apache.maven.artifact.repository.ArtifactRepository> getMirroredRepositories() ,public java.lang.String getProtocol() ,public org.apache.maven.repository.Proxy getProxy() ,public org.apache.maven.artifact.repository.ArtifactRepositoryPolicy getReleases() ,public org.apache.maven.artifact.repository.ArtifactRepositoryPolicy getSnapshots() ,public java.lang.String getUrl() ,public int hashCode() ,public boolean isBlacklisted() ,public boolean isBlocked() ,public boolean isProjectAware() ,public boolean isUniqueVersion() ,public java.lang.String pathOf(org.apache.maven.artifact.Artifact) ,public java.lang.String pathOfLocalRepositoryMetadata(org.apache.maven.artifact.metadata.ArtifactMetadata, org.apache.maven.artifact.repository.ArtifactRepository) ,public java.lang.String pathOfRemoteRepositoryMetadata(org.apache.maven.artifact.metadata.ArtifactMetadata) ,public void setAuthentication(org.apache.maven.artifact.repository.Authentication) ,public void setBlacklisted(boolean) ,public void setBlocked(boolean) ,public void setId(java.lang.String) ,public void setLayout(org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout) ,public void setMirroredRepositories(List<org.apache.maven.artifact.repository.ArtifactRepository>) ,public void setProxy(org.apache.maven.repository.Proxy) ,public void setReleaseUpdatePolicy(org.apache.maven.artifact.repository.ArtifactRepositoryPolicy) ,public void setSnapshotUpdatePolicy(org.apache.maven.artifact.repository.ArtifactRepositoryPolicy) ,public void setUrl(java.lang.String) ,public java.lang.String toString() <variables>private static final java.lang.String LS,private org.apache.maven.artifact.repository.Authentication authentication,private java.lang.String basedir,private boolean blocked,private java.lang.String id,private org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout layout,private List<org.apache.maven.artifact.repository.ArtifactRepository> mirroredRepositories,private java.lang.String protocol,private org.apache.maven.repository.Proxy proxy,private org.apache.maven.artifact.repository.ArtifactRepositoryPolicy releases,private org.apache.maven.artifact.repository.ArtifactRepositoryPolicy snapshots,private java.lang.String url
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/MavenArtifactMetadata.java
|
MavenArtifactMetadata
|
toString
|
class MavenArtifactMetadata {
public static final String DEFAULT_TYPE = "jar";
String groupId;
String artifactId;
String version;
String classifier;
String type;
String scope;
transient Object datum;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactId() {
return artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getClassifier() {
return classifier;
}
public void setClassifier(String classifier) {
this.classifier = classifier;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object getDatum() {
return datum;
}
public void setDatum(Object datum) {
this.datum = datum;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getGroupId() + ":" + getArtifactId() + ":" + getVersion() + ":"
+ (getClassifier() == null ? "" : getClassifier()) + ":"
+ (getType() == null ? DEFAULT_TYPE : getType());
| 394
| 66
| 460
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraph.java
|
MetadataGraph
|
findNode
|
class MetadataGraph {
/** all graph nodes */
Collection<MetadataGraphNode> nodes;
/** entry point for tree-like structures */
MetadataGraphNode entry;
public MetadataGraph(MetadataGraphNode entry) {
this();
this.entry = entry;
}
public MetadataGraph() {
nodes = new ArrayList<>(64);
}
public void addNode(MetadataGraphNode node) {
nodes.add(node);
}
/**
* find a node by the GAV (metadata)
*
* @param md
*/
public MetadataGraphNode findNode(MavenArtifactMetadata md) {<FILL_FUNCTION_BODY>}
/**
* getter
*/
public MetadataGraphNode getEntry() {
return entry;
}
/**
* getter
*/
public Collection<MetadataGraphNode> getNodes() {
return nodes;
}
}
|
for (MetadataGraphNode mgn : nodes) {
if (mgn.metadata.equals(md)) {
return mgn;
}
}
MetadataGraphNode node = new MetadataGraphNode(md);
addNode(node);
return node;
| 246
| 71
| 317
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/MetadataGraphNode.java
|
MetadataGraphNode
|
equals
|
class MetadataGraphNode {
/** node payload */
MavenArtifactMetadata metadata;
/** nodes, incident to this (depend on me) */
List<MetadataGraphNode> inNodes;
/** nodes, exident to this (I depend on) */
List<MetadataGraphNode> exNodes;
public MetadataGraphNode() {
inNodes = new ArrayList<>(4);
exNodes = new ArrayList<>(8);
}
public MetadataGraphNode(MavenArtifactMetadata metadata) {
this();
this.metadata = metadata;
}
public MetadataGraphNode addIncident(MetadataGraphNode node) {
inNodes.add(node);
return this;
}
public MetadataGraphNode addExident(MetadataGraphNode node) {
exNodes.add(node);
return this;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
if (metadata == null) {
return super.hashCode();
}
return metadata.toString().hashCode();
}
}
|
if (obj == null) {
return false;
}
if (MetadataGraphNode.class.isAssignableFrom(obj.getClass())) {
MetadataGraphNode node2 = (MetadataGraphNode) obj;
if (node2.metadata == null) {
return metadata == null;
}
return metadata != null && metadata.toString().equals(node2.metadata.toString());
} else {
return super.equals(obj);
}
| 289
| 121
| 410
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionRequest.java
|
MetadataResolutionRequest
|
toString
|
class MetadataResolutionRequest {
private MavenArtifactMetadata mad;
private String scope;
// Needs to go away
private Set<Artifact> artifactDependencies;
private ArtifactRepository localRepository;
private List<ArtifactRepository> remoteRepositories;
// This is like a filter but overrides all transitive versions
private Map managedVersionMap;
/** result type - flat list; the default */
private boolean asList = true;
/** result type - dirty tree */
private boolean asDirtyTree = false;
/** result type - resolved tree */
private boolean asResolvedTree = false;
/** result type - graph */
private boolean asGraph = false;
public MetadataResolutionRequest() {}
public MetadataResolutionRequest(
MavenArtifactMetadata md, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories) {
this.mad = md;
this.localRepository = localRepository;
this.remoteRepositories = remoteRepositories;
}
public MavenArtifactMetadata getArtifactMetadata() {
return mad;
}
public MetadataResolutionRequest setArtifactMetadata(MavenArtifactMetadata md) {
this.mad = md;
return this;
}
public MetadataResolutionRequest setArtifactDependencies(Set<Artifact> artifactDependencies) {
this.artifactDependencies = artifactDependencies;
return this;
}
public Set<Artifact> getArtifactDependencies() {
return artifactDependencies;
}
public ArtifactRepository getLocalRepository() {
return localRepository;
}
public MetadataResolutionRequest setLocalRepository(ArtifactRepository localRepository) {
this.localRepository = localRepository;
return this;
}
/**
* @deprecated instead use {@link #getRemoteRepositories()}
*/
@Deprecated
public List<ArtifactRepository> getRemoteRepostories() {
return remoteRepositories;
}
public List<ArtifactRepository> getRemoteRepositories() {
return getRemoteRepostories();
}
/**
* @deprecated instead use {@link #setRemoteRepositories(List)}
*/
@Deprecated
public MetadataResolutionRequest setRemoteRepostories(List<ArtifactRepository> remoteRepositories) {
this.remoteRepositories = remoteRepositories;
return this;
}
public MetadataResolutionRequest setRemoteRepositories(List<ArtifactRepository> remoteRepositories) {
return setRemoteRepostories(remoteRepositories);
}
public Map getManagedVersionMap() {
return managedVersionMap;
}
public MetadataResolutionRequest setManagedVersionMap(Map managedVersionMap) {
this.managedVersionMap = managedVersionMap;
return this;
}
public String toString() {<FILL_FUNCTION_BODY>}
public boolean isAsList() {
return asList;
}
public MetadataResolutionRequest setAsList(boolean asList) {
this.asList = asList;
return this;
}
public boolean isAsDirtyTree() {
return asDirtyTree;
}
public MetadataResolutionRequest setAsDirtyTree(boolean asDirtyTree) {
this.asDirtyTree = asDirtyTree;
return this;
}
public boolean isAsResolvedTree() {
return asResolvedTree;
}
public MetadataResolutionRequest setAsResolvedTree(boolean asResolvedTree) {
this.asResolvedTree = asResolvedTree;
return this;
}
public boolean isAsGraph() {
return asGraph;
}
public MetadataResolutionRequest setAsGraph(boolean asGraph) {
this.asGraph = asGraph;
return this;
}
public MetadataResolutionRequest setScope(String scope) {
this.scope = scope;
return this;
}
public String getScope() {
return scope;
}
}
|
StringBuilder sb = new StringBuilder()
.append("REQUEST: ")
.append("\n")
.append("artifact: ")
.append(mad)
.append("\n")
.append(artifactDependencies)
.append("\n")
.append("localRepository: ")
.append(localRepository)
.append("\n")
.append("remoteRepositories: ")
.append(remoteRepositories)
.append("\n");
return sb.toString();
| 1,057
| 128
| 1,185
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionResult.java
|
MetadataResolutionResult
|
addArtifact
|
class MetadataResolutionResult {
private Artifact originatingArtifact;
private List<Artifact> missingArtifacts;
// Exceptions
private List<Exception> exceptions;
private List<Exception> versionRangeViolations;
private List<ArtifactResolutionException> metadataResolutionExceptions;
private List<CyclicDependencyException> circularDependencyExceptions;
private List<ArtifactResolutionException> errorArtifactExceptions;
// file system errors
private List<ArtifactRepository> repositories;
private Set<Artifact> requestedArtifacts;
private Set<Artifact> artifacts;
private MetadataGraph dirtyTree;
private MetadataGraph resolvedTree;
private MetadataGraph resolvedGraph;
public Artifact getOriginatingArtifact() {
return originatingArtifact;
}
public MetadataResolutionResult listOriginatingArtifact(final Artifact originatingArtifact) {
this.originatingArtifact = originatingArtifact;
return this;
}
public void addArtifact(Artifact artifact) {<FILL_FUNCTION_BODY>}
public Set<Artifact> getArtifacts() {
return artifacts;
}
public void addRequestedArtifact(Artifact artifact) {
if (requestedArtifacts == null) {
requestedArtifacts = new LinkedHashSet<>();
}
requestedArtifacts.add(artifact);
}
public Set<Artifact> getRequestedArtifacts() {
return requestedArtifacts;
}
public boolean hasMissingArtifacts() {
return missingArtifacts != null && !missingArtifacts.isEmpty();
}
public List<Artifact> getMissingArtifacts() {
return missingArtifacts == null ? Collections.emptyList() : Collections.unmodifiableList(missingArtifacts);
}
public MetadataResolutionResult addMissingArtifact(Artifact artifact) {
missingArtifacts = initList(missingArtifacts);
missingArtifacts.add(artifact);
return this;
}
public MetadataResolutionResult setUnresolvedArtifacts(final List<Artifact> unresolvedArtifacts) {
this.missingArtifacts = unresolvedArtifacts;
return this;
}
// ------------------------------------------------------------------------
// Exceptions
// ------------------------------------------------------------------------
public boolean hasExceptions() {
return exceptions != null && !exceptions.isEmpty();
}
public List<Exception> getExceptions() {
return exceptions == null ? Collections.emptyList() : Collections.unmodifiableList(exceptions);
}
// ------------------------------------------------------------------------
// Version Range Violations
// ------------------------------------------------------------------------
public boolean hasVersionRangeViolations() {
return versionRangeViolations != null;
}
/**
* TODO this needs to accept a {@link OverConstrainedVersionException} as returned by
* {@link #getVersionRangeViolation(int)} but it's not used like that in
* {@link org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector}
*/
public MetadataResolutionResult addVersionRangeViolation(Exception e) {
versionRangeViolations = initList(versionRangeViolations);
versionRangeViolations.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public OverConstrainedVersionException getVersionRangeViolation(int i) {
return (OverConstrainedVersionException) versionRangeViolations.get(i);
}
public List<Exception> getVersionRangeViolations() {
return versionRangeViolations == null
? Collections.emptyList()
: Collections.unmodifiableList(versionRangeViolations);
}
// ------------------------------------------------------------------------
// Metadata Resolution Exceptions: ArtifactResolutionExceptions
// ------------------------------------------------------------------------
public boolean hasMetadataResolutionExceptions() {
return metadataResolutionExceptions != null;
}
public MetadataResolutionResult addMetadataResolutionException(ArtifactResolutionException e) {
metadataResolutionExceptions = initList(metadataResolutionExceptions);
metadataResolutionExceptions.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public ArtifactResolutionException getMetadataResolutionException(int i) {
return metadataResolutionExceptions.get(i);
}
public List<ArtifactResolutionException> getMetadataResolutionExceptions() {
return metadataResolutionExceptions == null
? Collections.emptyList()
: Collections.unmodifiableList(metadataResolutionExceptions);
}
// ------------------------------------------------------------------------
// ErrorArtifactExceptions: ArtifactResolutionExceptions
// ------------------------------------------------------------------------
public boolean hasErrorArtifactExceptions() {
return errorArtifactExceptions != null;
}
public MetadataResolutionResult addError(Exception e) {
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public List<ArtifactResolutionException> getErrorArtifactExceptions() {
if (errorArtifactExceptions == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(errorArtifactExceptions);
}
// ------------------------------------------------------------------------
// Circular Dependency Exceptions
// ------------------------------------------------------------------------
public boolean hasCircularDependencyExceptions() {
return circularDependencyExceptions != null;
}
public MetadataResolutionResult addCircularDependencyException(CyclicDependencyException e) {
circularDependencyExceptions = initList(circularDependencyExceptions);
circularDependencyExceptions.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public CyclicDependencyException getCircularDependencyException(int i) {
return circularDependencyExceptions.get(i);
}
public List<CyclicDependencyException> getCircularDependencyExceptions() {
if (circularDependencyExceptions == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(circularDependencyExceptions);
}
// ------------------------------------------------------------------------
// Repositories
// ------------------------------------------------------------------------
public List<ArtifactRepository> getRepositories() {
if (repositories == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(repositories);
}
public MetadataResolutionResult setRepositories(final List<ArtifactRepository> repositories) {
this.repositories = repositories;
return this;
}
//
// Internal
//
private <T> List<T> initList(final List<T> l) {
if (l == null) {
return new ArrayList<>();
}
return l;
}
public String toString() {
if (artifacts == null) {
return "";
}
StringBuilder sb = new StringBuilder(256);
int i = 1;
sb.append("---------\n");
sb.append(artifacts.size()).append('\n');
for (Artifact a : artifacts) {
sb.append(i).append(' ').append(a).append('\n');
i++;
}
sb.append("---------\n");
return sb.toString();
}
public MetadataGraph getResolvedTree() {
return resolvedTree;
}
public void setResolvedTree(MetadataGraph resolvedTree) {
this.resolvedTree = resolvedTree;
}
}
|
if (artifacts == null) {
artifacts = new LinkedHashSet<>();
}
artifacts.add(artifact);
| 1,975
| 37
| 2,012
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/UserLocalArtifactRepository.java
|
UserLocalArtifactRepository
|
find
|
class UserLocalArtifactRepository extends LocalArtifactRepository {
private ArtifactRepository localRepository;
public UserLocalArtifactRepository(ArtifactRepository localRepository) {
this.localRepository = localRepository;
setLayout(localRepository.getLayout());
}
@Override
public Artifact find(Artifact artifact) {<FILL_FUNCTION_BODY>}
@Override
public String getId() {
return localRepository.getId();
}
@Override
public String pathOfLocalRepositoryMetadata(ArtifactMetadata metadata, ArtifactRepository repository) {
return localRepository.pathOfLocalRepositoryMetadata(metadata, repository);
}
@Override
public String pathOf(Artifact artifact) {
return localRepository.pathOf(artifact);
}
@Override
public boolean hasLocalMetadata() {
return true;
}
}
|
File artifactFile = new File(localRepository.getBasedir(), pathOf(artifact));
// We need to set the file here or the resolver will fail with an NPE, not fully equipped to deal
// with multiple local repository implementations yet.
artifact.setFile(artifactFile);
return artifact;
| 216
| 78
| 294
|
<methods>public non-sealed void <init>() ,public abstract org.apache.maven.artifact.Artifact find(org.apache.maven.artifact.Artifact) ,public abstract boolean hasLocalMetadata() <variables>public static final java.lang.String IDE_WORKSPACE
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/MavenArtifact.java
|
MavenArtifact
|
getName
|
class MavenArtifact implements ArtifactTransferResource {
private String repositoryUrl;
private Resource resource;
private long transferStartTime;
MavenArtifact(String repositoryUrl, Resource resource) {
if (repositoryUrl == null) {
this.repositoryUrl = "";
} else if (!repositoryUrl.endsWith("/") && !repositoryUrl.isEmpty()) {
this.repositoryUrl = repositoryUrl + '/';
} else {
this.repositoryUrl = repositoryUrl;
}
this.resource = resource;
this.transferStartTime = System.currentTimeMillis();
}
public String getRepositoryUrl() {
return repositoryUrl;
}
public String getName() {<FILL_FUNCTION_BODY>}
public String getUrl() {
return getRepositoryUrl() + getName();
}
public long getContentLength() {
return resource.getContentLength();
}
public long getTransferStartTime() {
return transferStartTime;
}
@Override
public String toString() {
return getUrl();
}
}
|
String name = resource.getName();
if (name == null) {
name = "";
} else if (name.startsWith("/")) {
name = name.substring(1);
}
return name;
| 281
| 61
| 342
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/TransferListenerAdapter.java
|
TransferListenerAdapter
|
newAdapter
|
class TransferListenerAdapter implements TransferListener {
private final ArtifactTransferListener listener;
private final Map<Resource, ArtifactTransferResource> artifacts;
private final Map<Resource, Long> transfers;
public static TransferListener newAdapter(ArtifactTransferListener listener) {<FILL_FUNCTION_BODY>}
private TransferListenerAdapter(ArtifactTransferListener listener) {
this.listener = listener;
this.artifacts = new IdentityHashMap<>();
this.transfers = new IdentityHashMap<>();
}
public void debug(String message) {}
public void transferCompleted(TransferEvent transferEvent) {
ArtifactTransferEvent event = wrap(transferEvent);
Long transferred;
synchronized (transfers) {
transferred = transfers.remove(transferEvent.getResource());
}
if (transferred != null) {
event.setTransferredBytes(transferred);
}
synchronized (artifacts) {
artifacts.remove(transferEvent.getResource());
}
listener.transferCompleted(event);
}
public void transferError(TransferEvent transferEvent) {
synchronized (transfers) {
transfers.remove(transferEvent.getResource());
}
synchronized (artifacts) {
artifacts.remove(transferEvent.getResource());
}
}
public void transferInitiated(TransferEvent transferEvent) {
listener.transferInitiated(wrap(transferEvent));
}
public void transferProgress(TransferEvent transferEvent, byte[] buffer, int length) {
Long transferred;
synchronized (transfers) {
transferred = transfers.get(transferEvent.getResource());
if (transferred == null) {
transferred = (long) length;
} else {
transferred = transferred + length;
}
transfers.put(transferEvent.getResource(), transferred);
}
ArtifactTransferEvent event = wrap(transferEvent);
event.setDataBuffer(buffer);
event.setDataOffset(0);
event.setDataLength(length);
event.setTransferredBytes(transferred);
listener.transferProgress(event);
}
public void transferStarted(TransferEvent transferEvent) {
listener.transferStarted(wrap(transferEvent));
}
private ArtifactTransferEvent wrap(TransferEvent event) {
if (event == null) {
return null;
} else {
String wagon = event.getWagon().getClass().getName();
ArtifactTransferResource artifact = wrap(event.getWagon().getRepository(), event.getResource());
ArtifactTransferEvent evt;
if (event.getException() != null) {
evt = new ArtifactTransferEvent(wagon, event.getException(), event.getRequestType(), artifact);
} else {
evt = new ArtifactTransferEvent(wagon, event.getEventType(), event.getRequestType(), artifact);
}
evt.setLocalFile(event.getLocalFile());
return evt;
}
}
private ArtifactTransferResource wrap(Repository repository, Resource resource) {
if (resource == null) {
return null;
} else {
synchronized (artifacts) {
ArtifactTransferResource artifact = artifacts.get(resource);
if (artifact == null) {
artifact = new MavenArtifact(repository.getUrl(), resource);
artifacts.put(resource, artifact);
}
return artifact;
}
}
}
}
|
if (listener == null) {
return null;
} else {
return new TransferListenerAdapter(listener);
}
| 927
| 37
| 964
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/metadata/AbstractArtifactMetadata.java
|
AbstractArtifactMetadata
|
extendedToString
|
class AbstractArtifactMetadata implements ArtifactMetadata {
private static final String LS = System.lineSeparator();
protected Artifact artifact;
protected AbstractArtifactMetadata(Artifact artifact) {
this.artifact = artifact;
}
public boolean storedInGroupDirectory() {
return false;
}
public String getGroupId() {
return artifact.getGroupId();
}
public String getArtifactId() {
return artifact.getArtifactId();
}
public String extendedToString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder(256);
buffer.append(LS).append("Artifact Metadata").append(LS).append("--------------------------");
buffer.append(LS).append("GroupId: ").append(getGroupId());
buffer.append(LS).append("ArtifactId: ").append(getArtifactId());
buffer.append(LS).append("Metadata Type: ").append(getClass().getName());
return buffer.toString();
| 147
| 116
| 263
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/repository/DefaultArtifactRepositoryFactory.java
|
DefaultArtifactRepositoryFactory
|
createArtifactRepository
|
class DefaultArtifactRepositoryFactory implements ArtifactRepositoryFactory {
// TODO use settings?
private String globalUpdatePolicy;
private String globalChecksumPolicy;
@Inject
private Map<String, ArtifactRepositoryLayout> repositoryLayouts;
public ArtifactRepositoryLayout getLayout(String layoutId) throws UnknownRepositoryLayoutException {
return repositoryLayouts.get(layoutId);
}
public ArtifactRepository createDeploymentArtifactRepository(
String id, String url, String layoutId, boolean uniqueVersion) throws UnknownRepositoryLayoutException {
ArtifactRepositoryLayout layout = repositoryLayouts.get(layoutId);
checkLayout(id, layoutId, layout);
return createDeploymentArtifactRepository(id, url, layout, uniqueVersion);
}
private void checkLayout(String repositoryId, String layoutId, ArtifactRepositoryLayout layout)
throws UnknownRepositoryLayoutException {
if (layout == null) {
throw new UnknownRepositoryLayoutException(repositoryId, layoutId);
}
}
public ArtifactRepository createDeploymentArtifactRepository(
String id, String url, ArtifactRepositoryLayout repositoryLayout, boolean uniqueVersion) {
return createArtifactRepository(id, url, repositoryLayout, null, null);
}
public ArtifactRepository createArtifactRepository(
String id,
String url,
String layoutId,
ArtifactRepositoryPolicy snapshots,
ArtifactRepositoryPolicy releases)
throws UnknownRepositoryLayoutException {
ArtifactRepositoryLayout layout = repositoryLayouts.get(layoutId);
checkLayout(id, layoutId, layout);
return createArtifactRepository(id, url, layout, snapshots, releases);
}
public ArtifactRepository createArtifactRepository(
String id,
String url,
ArtifactRepositoryLayout repositoryLayout,
ArtifactRepositoryPolicy snapshots,
ArtifactRepositoryPolicy releases) {<FILL_FUNCTION_BODY>}
public void setGlobalUpdatePolicy(String updatePolicy) {
globalUpdatePolicy = updatePolicy;
}
public void setGlobalChecksumPolicy(String checksumPolicy) {
globalChecksumPolicy = checksumPolicy;
}
}
|
if (snapshots == null) {
snapshots = new ArtifactRepositoryPolicy();
}
if (releases == null) {
releases = new ArtifactRepositoryPolicy();
}
if (globalUpdatePolicy != null) {
snapshots.setUpdatePolicy(globalUpdatePolicy);
releases.setUpdatePolicy(globalUpdatePolicy);
}
if (globalChecksumPolicy != null) {
snapshots.setChecksumPolicy(globalChecksumPolicy);
releases.setChecksumPolicy(globalChecksumPolicy);
}
ArtifactRepository repository;
if (repositoryLayout instanceof ArtifactRepositoryLayout2) {
repository = ((ArtifactRepositoryLayout2) repositoryLayout)
.newMavenArtifactRepository(id, url, snapshots, releases);
} else {
repository = new MavenArtifactRepository(id, url, repositoryLayout, snapshots, releases);
}
return repository;
| 531
| 235
| 766
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/DefaultConflictResolverFactory.java
|
DefaultConflictResolverFactory
|
getConflictResolver
|
class DefaultConflictResolverFactory implements ConflictResolverFactory, Contextualizable {
// fields -----------------------------------------------------------------
/**
* The plexus container used to obtain instances from.
*/
@Inject
private PlexusContainer container;
// ConflictResolverFactory methods ----------------------------------------
/*
* @see org.apache.maven.artifact.resolver.conflict.ConflictResolverFactory#getConflictResolver(java.lang.String)
*/
public ConflictResolver getConflictResolver(String type) throws ConflictResolverNotFoundException {<FILL_FUNCTION_BODY>}
// Contextualizable methods -----------------------------------------------
/*
* @see org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable#contextualize(org.codehaus.plexus.context.Context)
*/
public void contextualize(Context context) throws ContextException {
container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY);
}
}
|
try {
return (ConflictResolver) container.lookup(ConflictResolver.ROLE, type);
} catch (ComponentLookupException exception) {
throw new ConflictResolverNotFoundException("Cannot find conflict resolver of type: " + type);
}
| 258
| 66
| 324
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/NewestConflictResolver.java
|
NewestConflictResolver
|
resolveConflict
|
class NewestConflictResolver implements ConflictResolver {
// ConflictResolver methods -----------------------------------------------
/*
* @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode,
* org.apache.maven.artifact.resolver.ResolutionNode)
*/
public ResolutionNode resolveConflict(ResolutionNode node1, ResolutionNode node2) {<FILL_FUNCTION_BODY>}
}
|
try {
ArtifactVersion version1 = node1.getArtifact().getSelectedVersion();
ArtifactVersion version2 = node2.getArtifact().getSelectedVersion();
return version1.compareTo(version2) > 0 ? node1 : node2;
} catch (OverConstrainedVersionException exception) {
// TODO log message or throw exception?
return null;
}
| 129
| 99
| 228
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/OldestConflictResolver.java
|
OldestConflictResolver
|
resolveConflict
|
class OldestConflictResolver implements ConflictResolver {
// ConflictResolver methods -----------------------------------------------
/*
* @see org.apache.maven.artifact.resolver.conflict.ConflictResolver#resolveConflict(org.apache.maven.artifact.resolver.ResolutionNode,
* org.apache.maven.artifact.resolver.ResolutionNode)
*/
public ResolutionNode resolveConflict(ResolutionNode node1, ResolutionNode node2) {<FILL_FUNCTION_BODY>}
}
|
try {
ArtifactVersion version1 = node1.getArtifact().getSelectedVersion();
ArtifactVersion version2 = node2.getArtifact().getSelectedVersion();
return version1.compareTo(version2) <= 0 ? node1 : node2;
} catch (OverConstrainedVersionException exception) {
// TODO log message or throw exception?
return null;
}
| 129
| 99
| 228
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/AbstractVersionTransformation.java
|
AbstractVersionTransformation
|
resolveVersion
|
class AbstractVersionTransformation extends AbstractLogEnabled implements ArtifactTransformation {
@Inject
protected RepositoryMetadataManager repositoryMetadataManager;
@Inject
protected WagonManager wagonManager;
public void transformForResolve(
Artifact artifact, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository)
throws ArtifactResolutionException, ArtifactNotFoundException {
RepositoryRequest request = new DefaultRepositoryRequest();
request.setLocalRepository(localRepository);
request.setRemoteRepositories(remoteRepositories);
transformForResolve(artifact, request);
}
protected String resolveVersion(
Artifact artifact, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories)
throws RepositoryMetadataResolutionException {
RepositoryRequest request = new DefaultRepositoryRequest();
request.setLocalRepository(localRepository);
request.setRemoteRepositories(remoteRepositories);
return resolveVersion(artifact, request);
}
protected String resolveVersion(Artifact artifact, RepositoryRequest request)
throws RepositoryMetadataResolutionException {<FILL_FUNCTION_BODY>}
protected abstract String constructVersion(Versioning versioning, String baseVersion);
}
|
RepositoryMetadata metadata;
// Don't use snapshot metadata for LATEST (which isSnapshot returns true for)
if (!artifact.isSnapshot() || Artifact.LATEST_VERSION.equals(artifact.getBaseVersion())) {
metadata = new ArtifactRepositoryMetadata(artifact);
} else {
metadata = new SnapshotArtifactRepositoryMetadata(artifact);
}
repositoryMetadataManager.resolve(metadata, request);
artifact.addMetadata(metadata);
Metadata repoMetadata = metadata.getMetadata();
String version = null;
if (repoMetadata != null && repoMetadata.getVersioning() != null) {
version = constructVersion(repoMetadata.getVersioning(), artifact.getBaseVersion());
}
if (version == null) {
// use the local copy, or if it doesn't exist - go to the remote repo for it
version = artifact.getBaseVersion();
}
// TODO also do this logging for other metadata?
// TODO figure out way to avoid duplicated message
if (getLogger().isDebugEnabled()) {
if (!version.equals(artifact.getBaseVersion())) {
String message = artifact.getArtifactId() + ": resolved to version " + version;
if (artifact.getRepository() != null) {
message += " from repository " + artifact.getRepository().getId();
} else {
message += " from local repository";
}
getLogger().debug(message);
} else {
// Locally installed file is newer, don't use the resolved version
getLogger().debug(artifact.getArtifactId() + ": using locally installed snapshot");
}
}
return version;
| 304
| 412
| 716
|
<methods>public void <init>() ,public void enableLogging(org.codehaus.plexus.logging.Logger) <variables>private org.codehaus.plexus.logging.Logger logger
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/DefaultArtifactTransformationManager.java
|
DefaultArtifactTransformationManager
|
transformForResolve
|
class DefaultArtifactTransformationManager implements ArtifactTransformationManager {
private List<ArtifactTransformation> artifactTransformations;
@Inject
public DefaultArtifactTransformationManager(Map<String, ArtifactTransformation> artifactTransformations) {
this.artifactTransformations = Stream.of("release", "latest", "snapshot")
.map(artifactTransformations::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
public void transformForResolve(Artifact artifact, RepositoryRequest request)
throws ArtifactResolutionException, ArtifactNotFoundException {<FILL_FUNCTION_BODY>}
public void transformForResolve(
Artifact artifact, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository)
throws ArtifactResolutionException, ArtifactNotFoundException {
for (ArtifactTransformation transform : artifactTransformations) {
transform.transformForResolve(artifact, remoteRepositories, localRepository);
}
}
public void transformForInstall(Artifact artifact, ArtifactRepository localRepository)
throws ArtifactInstallationException {
for (ArtifactTransformation transform : artifactTransformations) {
transform.transformForInstall(artifact, localRepository);
}
}
public void transformForDeployment(
Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository)
throws ArtifactDeploymentException {
for (ArtifactTransformation transform : artifactTransformations) {
transform.transformForDeployment(artifact, remoteRepository, localRepository);
}
}
public List<ArtifactTransformation> getArtifactTransformations() {
return artifactTransformations;
}
}
|
for (ArtifactTransformation transform : artifactTransformations) {
transform.transformForResolve(artifact, request);
}
| 417
| 34
| 451
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/ReleaseArtifactTransformation.java
|
ReleaseArtifactTransformation
|
transformForResolve
|
class ReleaseArtifactTransformation extends AbstractVersionTransformation {
public void transformForResolve(Artifact artifact, RepositoryRequest request)
throws ArtifactResolutionException, ArtifactNotFoundException {<FILL_FUNCTION_BODY>}
public void transformForInstall(Artifact artifact, ArtifactRepository localRepository) {
ArtifactMetadata metadata = createMetadata(artifact);
artifact.addMetadata(metadata);
}
public void transformForDeployment(
Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository) {
ArtifactMetadata metadata = createMetadata(artifact);
artifact.addMetadata(metadata);
}
private ArtifactMetadata createMetadata(Artifact artifact) {
Versioning versioning = new Versioning();
// TODO Should this be changed for MNG-6754 too?
versioning.updateTimestamp();
versioning.addVersion(artifact.getVersion());
if (artifact.isRelease()) {
versioning.setRelease(artifact.getVersion());
}
return new ArtifactRepositoryMetadata(artifact, versioning);
}
protected String constructVersion(Versioning versioning, String baseVersion) {
return versioning.getRelease();
}
}
|
if (Artifact.RELEASE_VERSION.equals(artifact.getVersion())) {
try {
String version = resolveVersion(artifact, request);
if (Artifact.RELEASE_VERSION.equals(version)) {
throw new ArtifactNotFoundException("Unable to determine the release version", artifact);
}
artifact.setBaseVersion(version);
artifact.updateVersion(version, request.getLocalRepository());
} catch (RepositoryMetadataResolutionException e) {
throw new ArtifactResolutionException(e.getMessage(), artifact, e);
}
}
| 299
| 142
| 441
|
<methods>public non-sealed void <init>() ,public void transformForResolve(org.apache.maven.artifact.Artifact, List<org.apache.maven.artifact.repository.ArtifactRepository>, org.apache.maven.artifact.repository.ArtifactRepository) throws org.apache.maven.artifact.resolver.ArtifactResolutionException, org.apache.maven.artifact.resolver.ArtifactNotFoundException<variables>protected org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager repositoryMetadataManager,protected org.apache.maven.repository.legacy.WagonManager wagonManager
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/transform/SnapshotTransformation.java
|
SnapshotTransformation
|
getDeploymentTimestamp
|
class SnapshotTransformation extends AbstractVersionTransformation {
private static final String DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT = "yyyyMMdd.HHmmss";
private static final TimeZone DEFAULT_SNAPSHOT_TIME_ZONE = TimeZone.getTimeZone("Etc/UTC");
private String deploymentTimestamp;
public void transformForResolve(Artifact artifact, RepositoryRequest request) throws ArtifactResolutionException {
// Only select snapshots that are unresolved (eg 1.0-SNAPSHOT, not 1.0-20050607.123456)
if (artifact.isSnapshot() && artifact.getBaseVersion().equals(artifact.getVersion())) {
try {
String version = resolveVersion(artifact, request);
artifact.updateVersion(version, request.getLocalRepository());
} catch (RepositoryMetadataResolutionException e) {
throw new ArtifactResolutionException(e.getMessage(), artifact, e);
}
}
}
public void transformForInstall(Artifact artifact, ArtifactRepository localRepository) {
if (artifact.isSnapshot()) {
Snapshot snapshot = new Snapshot();
snapshot.setLocalCopy(true);
RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata(artifact, snapshot);
artifact.addMetadata(metadata);
}
}
public void transformForDeployment(
Artifact artifact, ArtifactRepository remoteRepository, ArtifactRepository localRepository)
throws ArtifactDeploymentException {
if (artifact.isSnapshot()) {
Snapshot snapshot = new Snapshot();
// TODO Should this be changed for MNG-6754 too?
snapshot.setTimestamp(getDeploymentTimestamp());
// we update the build number anyway so that it doesn't get lost. It requires the timestamp to take effect
try {
int buildNumber = resolveLatestSnapshotBuildNumber(artifact, localRepository, remoteRepository);
snapshot.setBuildNumber(buildNumber + 1);
} catch (RepositoryMetadataResolutionException e) {
throw new ArtifactDeploymentException(
"Error retrieving previous build number for artifact '" + artifact.getDependencyConflictId()
+ "': " + e.getMessage(),
e);
}
RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata(artifact, snapshot);
artifact.setResolvedVersion(
constructVersion(metadata.getMetadata().getVersioning(), artifact.getBaseVersion()));
artifact.addMetadata(metadata);
}
}
public String getDeploymentTimestamp() {<FILL_FUNCTION_BODY>}
protected String constructVersion(Versioning versioning, String baseVersion) {
String version = null;
Snapshot snapshot = versioning.getSnapshot();
if (snapshot != null) {
if (snapshot.getTimestamp() != null && snapshot.getBuildNumber() > 0) {
String newVersion = snapshot.getTimestamp() + "-" + snapshot.getBuildNumber();
version = baseVersion.replace(Artifact.SNAPSHOT_VERSION, newVersion);
} else {
version = baseVersion;
}
}
return version;
}
private int resolveLatestSnapshotBuildNumber(
Artifact artifact, ArtifactRepository localRepository, ArtifactRepository remoteRepository)
throws RepositoryMetadataResolutionException {
RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata(artifact);
getLogger().info("Retrieving previous build number from " + remoteRepository.getId());
repositoryMetadataManager.resolveAlways(metadata, localRepository, remoteRepository);
int buildNumber = 0;
Metadata repoMetadata = metadata.getMetadata();
if ((repoMetadata != null)
&& (repoMetadata.getVersioning() != null
&& repoMetadata.getVersioning().getSnapshot() != null)) {
buildNumber = repoMetadata.getVersioning().getSnapshot().getBuildNumber();
}
return buildNumber;
}
public static DateFormat getUtcDateFormatter() {
DateFormat utcDateFormatter = new SimpleDateFormat(DEFAULT_SNAPSHOT_TIMESTAMP_FORMAT);
utcDateFormatter.setCalendar(new GregorianCalendar());
utcDateFormatter.setTimeZone(DEFAULT_SNAPSHOT_TIME_ZONE);
return utcDateFormatter;
}
}
|
if (deploymentTimestamp == null) {
deploymentTimestamp = getUtcDateFormatter().format(new Date());
}
return deploymentTimestamp;
| 1,067
| 40
| 1,107
|
<methods>public non-sealed void <init>() ,public void transformForResolve(org.apache.maven.artifact.Artifact, List<org.apache.maven.artifact.repository.ArtifactRepository>, org.apache.maven.artifact.repository.ArtifactRepository) throws org.apache.maven.artifact.resolver.ArtifactResolutionException, org.apache.maven.artifact.resolver.ArtifactNotFoundException<variables>protected org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager repositoryMetadataManager,protected org.apache.maven.repository.legacy.WagonManager wagonManager
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/metadata/ClasspathContainer.java
|
ClasspathContainer
|
getClasspathAsTree
|
class ClasspathContainer implements Iterable<ArtifactMetadata> {
private List<ArtifactMetadata> classpath;
private ArtifactScopeEnum scope;
// -------------------------------------------------------------------------------------------
public ClasspathContainer(ArtifactScopeEnum scope) {
this.scope = ArtifactScopeEnum.checkScope(scope);
}
// -------------------------------------------------------------------------------------------
public ClasspathContainer(List<ArtifactMetadata> classpath, ArtifactScopeEnum scope) {
this(scope);
this.classpath = classpath;
}
// -------------------------------------------------------------------------------------------
public Iterator<ArtifactMetadata> iterator() {
return classpath == null ? null : classpath.iterator();
}
// -------------------------------------------------------------------------------------------
public ClasspathContainer add(ArtifactMetadata md) {
if (classpath == null) {
classpath = new ArrayList<>(16);
}
classpath.add(md);
return this;
}
// -------------------------------------------------------------------------------------------
public List<ArtifactMetadata> getClasspath() {
return classpath;
}
// -------------------------------------------------------------------------------------------
public MetadataTreeNode getClasspathAsTree() throws MetadataResolutionException {<FILL_FUNCTION_BODY>}
public void setClasspath(List<ArtifactMetadata> classpath) {
this.classpath = classpath;
}
public ArtifactScopeEnum getScope() {
return scope;
}
public void setScope(ArtifactScopeEnum scope) {
this.scope = scope;
}
// -------------------------------------------------------------------------------------------
@Override
public String toString() {
StringBuilder sb = new StringBuilder(256);
sb.append("[scope=").append(scope.getScope());
if (classpath != null) {
for (ArtifactMetadata md : classpath) {
sb.append(": ")
.append(md.toString())
.append('{')
.append(md.getArtifactUri())
.append('}');
}
}
sb.append(']');
return sb.toString();
}
// -------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------
}
|
if (classpath == null || classpath.size() < 1) {
return null;
}
MetadataTreeNode tree = null;
MetadataTreeNode parent = null;
for (ArtifactMetadata md : classpath) {
MetadataTreeNode node = new MetadataTreeNode(md, parent, md.isResolved(), md.getArtifactScope());
if (tree == null) {
tree = node;
}
if (parent != null) {
parent.setNChildren(1);
parent.addChild(0, node);
}
parent = node;
}
return tree;
| 531
| 163
| 694
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultClasspathTransformation.java
|
ClasspathGraphVisitor
|
visit
|
class ClasspathGraphVisitor {
MetadataGraph graph;
ClasspathContainer cpc;
List<MetadataGraphVertex> visited;
// -----------------------------------------------------------------------
protected ClasspathGraphVisitor(MetadataGraph cleanGraph, ClasspathContainer cpc) {
this.cpc = cpc;
this.graph = cleanGraph;
visited = new ArrayList<>(cleanGraph.getVertices().size());
}
// -----------------------------------------------------------------------
protected void visit(MetadataGraphVertex node) // , String version, String artifactUri )
{<FILL_FUNCTION_BODY>}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
}
|
ArtifactMetadata md = node.getMd();
if (visited.contains(node)) {
return;
}
cpc.add(md);
//
// TreeSet<MetadataGraphEdge> deps = new TreeSet<MetadataGraphEdge>(
// new Comparator<MetadataGraphEdge>()
// {
// public int compare( MetadataGraphEdge e1
// , MetadataGraphEdge e2
// )
// {
// if( e1.getDepth() == e2.getDepth() )
// {
// if( e2.getPomOrder() == e1.getPomOrder() )
// return
// e1.getTarget().toString().compareTo(e2.getTarget().toString() );
//
// return e2.getPomOrder() - e1.getPomOrder();
// }
//
// return e2.getDepth() - e1.getDepth();
// }
// }
// );
List<MetadataGraphEdge> exits = graph.getExcidentEdges(node);
if (exits != null && exits.size() > 0) {
MetadataGraphEdge[] sortedExits = exits.toArray(new MetadataGraphEdge[0]);
Arrays.sort(sortedExits, (e1, e2) -> {
if (e1.getDepth() == e2.getDepth()) {
if (e2.getPomOrder() == e1.getPomOrder()) {
return e1.getTarget()
.toString()
.compareTo(e2.getTarget().toString());
}
return e2.getPomOrder() - e1.getPomOrder();
}
return e2.getDepth() - e1.getDepth();
});
for (MetadataGraphEdge e : sortedExits) {
MetadataGraphVertex targetNode = e.getTarget();
targetNode.getMd().setArtifactScope(e.getScope());
targetNode.getMd().setWhy(e.getSource().getMd().toString());
visit(targetNode);
}
}
| 156
| 556
| 712
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolutionPolicy.java
|
DefaultGraphConflictResolutionPolicy
|
apply
|
class DefaultGraphConflictResolutionPolicy implements GraphConflictResolutionPolicy {
/**
* artifact, closer to the entry point, is selected
*/
@Configuration(name = "closer-first", value = "true")
private boolean closerFirst = true;
/**
* newer artifact is selected
*/
@Configuration(name = "newer-first", value = "true")
private boolean newerFirst = true;
public MetadataGraphEdge apply(MetadataGraphEdge e1, MetadataGraphEdge e2) {<FILL_FUNCTION_BODY>}
}
|
int depth1 = e1.getDepth();
int depth2 = e2.getDepth();
if (depth1 == depth2) {
ArtifactVersion v1 = new DefaultArtifactVersion(e1.getVersion());
ArtifactVersion v2 = new DefaultArtifactVersion(e2.getVersion());
if (newerFirst) {
return v1.compareTo(v2) > 0 ? e1 : e2;
}
return v1.compareTo(v2) > 0 ? e2 : e1;
}
if (closerFirst) {
return depth1 < depth2 ? e1 : e2;
}
return depth1 < depth2 ? e2 : e1;
| 142
| 182
| 324
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultGraphConflictResolver.java
|
DefaultGraphConflictResolver
|
visit
|
class DefaultGraphConflictResolver implements GraphConflictResolver {
/**
* artifact, closer to the entry point, is selected
*/
@Inject
protected GraphConflictResolutionPolicy policy;
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
public MetadataGraph resolveConflicts(MetadataGraph graph, ArtifactScopeEnum scope)
throws GraphConflictResolutionException {
if (policy == null) {
throw new GraphConflictResolutionException("no GraphConflictResolutionPolicy injected");
}
if (graph == null) {
return null;
}
final MetadataGraphVertex entry = graph.getEntry();
if (entry == null) {
return null;
}
if (graph.isEmpty()) {
throw new GraphConflictResolutionException("graph with an entry, but not vertices do not exist");
}
if (graph.isEmptyEdges()) {
return null; // no edges - nothing to worry about
}
final TreeSet<MetadataGraphVertex> vertices = graph.getVertices();
try {
// edge case - single vertex graph
if (vertices.size() == 1) {
return new MetadataGraph(entry);
}
final ArtifactScopeEnum requestedScope = ArtifactScopeEnum.checkScope(scope);
MetadataGraph res = new MetadataGraph(vertices.size());
res.setVersionedVertices(false);
res.setScopedVertices(false);
MetadataGraphVertex resEntry = res.addVertex(entry.getMd());
res.setEntry(resEntry);
res.setScope(requestedScope);
for (MetadataGraphVertex v : vertices) {
final List<MetadataGraphEdge> ins = graph.getIncidentEdges(v);
final MetadataGraphEdge edge = cleanEdges(v, ins, requestedScope);
if (edge == null) { // no edges - don't need this vertex anymore
if (entry.equals(v)) { // unless it's an entry point.
// currently processing the entry point - it should not have any entry incident edges
res.getEntry().getMd().setWhy("This is a graph entry point. No links.");
} else {
// System.out.println("--->"+v.getMd().toDomainString()
// +" has been terminated on this entry set\n-------------------\n"
// +ins
// +"\n-------------------\n"
// );
}
} else {
// System.out.println("+++>"+v.getMd().toDomainString()+" still has "+edge.toString() );
// fill in domain md with actual version data
ArtifactMetadata md = v.getMd();
ArtifactMetadata newMd = new ArtifactMetadata(
md.getGroupId(),
md.getArtifactId(),
edge.getVersion(),
md.getType(),
md.getScopeAsEnum(),
md.getClassifier(),
edge.getArtifactUri(),
edge.getSource() == null
? ""
: edge.getSource().getMd().toString(),
edge.isResolved(),
edge.getTarget() == null
? null
: edge.getTarget().getMd().getError());
MetadataGraphVertex newV = res.addVertex(newMd);
MetadataGraphVertex sourceV = res.addVertex(edge.getSource().getMd());
res.addEdge(sourceV, newV, edge);
}
}
// System.err.println("Original graph("+graph.getVertices().size()+"):\n"+graph.toString());
// System.err.println("Cleaned("+requestedScope+") graph("+res.getVertices().size()+"):\n"+res.toString());
// System.err.println("Linked("+requestedScope+")
// subgraph("+linkedRes.getVertices().size()+"):\n"+linkedRes.toString());
return findLinkedSubgraph(res);
} catch (MetadataResolutionException e) {
throw new GraphConflictResolutionException(e);
}
}
// -------------------------------------------------------------------------------------
private MetadataGraph findLinkedSubgraph(MetadataGraph g) {
if (g.getVertices().size() == 1) {
return g;
}
List<MetadataGraphVertex> visited = new ArrayList<>(g.getVertices().size());
visit(g.getEntry(), visited, g);
List<MetadataGraphVertex> dropList = new ArrayList<>(g.getVertices().size());
// collect drop list
for (MetadataGraphVertex v : g.getVertices()) {
if (!visited.contains(v)) {
dropList.add(v);
}
}
if (dropList.size() < 1) {
return g;
}
// now - drop vertices
TreeSet<MetadataGraphVertex> vertices = g.getVertices();
for (MetadataGraphVertex v : dropList) {
vertices.remove(v);
}
return g;
}
// -------------------------------------------------------------------------------------
private void visit(MetadataGraphVertex from, List<MetadataGraphVertex> visited, MetadataGraph graph) {<FILL_FUNCTION_BODY>}
// -------------------------------------------------------------------------------------
private MetadataGraphEdge cleanEdges(
MetadataGraphVertex v, List<MetadataGraphEdge> edges, ArtifactScopeEnum scope) {
if (edges == null || edges.isEmpty()) {
return null;
}
if (edges.size() == 1) {
MetadataGraphEdge e = edges.get(0);
if (scope.encloses(e.getScope())) {
return e;
}
return null;
}
MetadataGraphEdge res = null;
for (MetadataGraphEdge e : edges) {
if (!scope.encloses(e.getScope())) {
continue;
}
if (res == null) {
res = e;
} else {
res = policy.apply(e, res);
}
}
return res;
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
}
|
if (visited.contains(from)) {
return;
}
visited.add(from);
List<MetadataGraphEdge> exitList = graph.getExcidentEdges(from);
// String s = "|---> "+from.getMd().toString()+" - "+(exitList == null ? -1 : exitList.size()) + " exit links";
if (exitList != null && exitList.size() > 0) {
for (MetadataGraphEdge e : graph.getExcidentEdges(from)) {
visit(e.getTarget(), visited, graph);
}
}
| 1,549
| 155
| 1,704
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphEdge.java
|
MetadataGraphEdge
|
objectsEqual
|
class MetadataGraphEdge {
String version;
ArtifactScopeEnum scope;
int depth = -1;
int pomOrder = -1;
boolean resolved = true;
String artifactUri;
/**
* capturing where this link came from
* and where it is linked to.
*
* In the first implementation only source used for explanatory function
*/
MetadataGraphVertex source;
MetadataGraphVertex target;
// ----------------------------------------------------------------------------
public MetadataGraphEdge(
String version, boolean resolved, ArtifactScopeEnum scope, String artifactUri, int depth, int pomOrder) {
super();
this.version = version;
this.scope = scope;
this.artifactUri = artifactUri;
this.depth = depth;
this.resolved = resolved;
this.pomOrder = pomOrder;
}
// ----------------------------------------------------------------------------
/**
* helper for equals
*/
private static boolean objectsEqual(Object o1, Object o2) {<FILL_FUNCTION_BODY>}
// ----------------------------------------------------------------------------
/**
* used to eliminate exact duplicates in the edge list
*/
@Override
@SuppressWarnings("checkstyle:equalshashcode")
public boolean equals(Object o) {
if (o instanceof MetadataGraphEdge) {
MetadataGraphEdge e = (MetadataGraphEdge) o;
return objectsEqual(version, e.version)
&& ArtifactScopeEnum.checkScope(scope)
.getScope()
.equals(ArtifactScopeEnum.checkScope(e.scope).getScope())
&& depth == e.depth;
}
return false;
}
// ----------------------------------------------------------------------------
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public ArtifactScopeEnum getScope() {
return scope;
}
public void setScope(ArtifactScopeEnum scope) {
this.scope = scope;
}
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
public boolean isResolved() {
return resolved;
}
public void setResolved(boolean resolved) {
this.resolved = resolved;
}
public int getPomOrder() {
return pomOrder;
}
public void setPomOrder(int pomOrder) {
this.pomOrder = pomOrder;
}
public String getArtifactUri() {
return artifactUri;
}
public void setArtifactUri(String artifactUri) {
this.artifactUri = artifactUri;
}
public MetadataGraphVertex getSource() {
return source;
}
public void setSource(MetadataGraphVertex source) {
this.source = source;
}
public MetadataGraphVertex getTarget() {
return target;
}
public void setTarget(MetadataGraphVertex target) {
this.target = target;
}
@Override
public String toString() {
return "[ " + "FROM:("
+ (source == null ? "no source" : (source.md == null ? "no source MD" : source.md.toString())) + ") "
+ "TO:(" + (target == null ? "no target" : (target.md == null ? "no target MD" : target.md.toString()))
+ ") " + "version=" + version + ", scope=" + (scope == null ? "null" : scope.getScope()) + ", depth="
+ depth + "]";
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
}
|
if (o1 == null && o2 == null) {
return true;
}
if (o1 == null || o2 == null) {
return false; // as they are not both null
}
return o1.equals(o2);
| 933
| 67
| 1,000
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataGraphVertex.java
|
MetadataGraphVertex
|
compareTo
|
class MetadataGraphVertex implements Comparable<MetadataGraphVertex> {
ArtifactMetadata md;
// indications to use these in comparison
private boolean compareVersion = false;
private boolean compareScope = false;
public MetadataGraphVertex(ArtifactMetadata md) {
super();
this.md = md;
}
public MetadataGraphVertex(ArtifactMetadata md, boolean compareVersion, boolean compareScope) {
this(md);
this.compareVersion = compareVersion;
this.compareScope = compareScope;
}
public ArtifactMetadata getMd() {
return md;
}
public void setMd(ArtifactMetadata md) {
this.md = md;
}
// ---------------------------------------------------------------------
public boolean isCompareVersion() {
return compareVersion;
}
public void setCompareVersion(boolean compareVersion) {
this.compareVersion = compareVersion;
}
public boolean isCompareScope() {
return compareScope;
}
public void setCompareScope(boolean compareScope) {
this.compareScope = compareScope;
}
// ---------------------------------------------------------------------
@Override
public String toString() {
return "[" + (md == null ? "no metadata" : md.toString()) + "]";
}
// ---------------------------------------------------------------------
private static int compareStrings(String s1, String s2) {
if (s1 == null && s2 == null) {
return 0;
}
if (s1 == null /* && s2 != null */) {
return -1;
}
if (
/* s1 != null && */ s2 == null) {
return 1;
}
return s1.compareTo(s2);
}
// ---------------------------------------------------------------------
public int compareTo(MetadataGraphVertex vertex) {<FILL_FUNCTION_BODY>}
// ---------------------------------------------------------------------
@Override
public boolean equals(Object vo) {
if (!(vo instanceof MetadataGraphVertex)) {
return false;
}
return compareTo((MetadataGraphVertex) vo) == 0;
}
// ---------------------------------------------------------------------
@Override
public int hashCode() {
if (md == null) {
return super.hashCode();
}
StringBuilder hashString = new StringBuilder(128);
hashString.append(md.groupId).append('|');
hashString.append(md.artifactId).append('|');
if (compareVersion) {
hashString.append(md.version).append('|');
}
if (compareScope) {
hashString.append(md.getArtifactScope()).append('|');
}
return hashString.toString().hashCode();
// BASE64Encoder b64 = new BASE64Encoder();
// return b64.encode( hashString.toString().getBytes() ).hashCode();
}
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
}
|
if (vertex == null || vertex.getMd() == null) {
return 1;
}
ArtifactMetadata vmd = vertex.getMd();
if (vmd == null) {
if (md == null) {
return 0;
} else {
return 1;
}
}
int g = compareStrings(md.groupId, vmd.groupId);
if (g == 0) {
int a = compareStrings(md.artifactId, vmd.artifactId);
if (a == 0) {
if (compareVersion) {
int v = compareStrings(md.version, vmd.version);
if (v == 0) {
if (compareScope) {
String s1 = ArtifactScopeEnum.checkScope(md.artifactScope)
.getScope();
String s2 = ArtifactScopeEnum.checkScope(vmd.artifactScope)
.getScope();
return s1.compareTo(s2);
} else {
return 0;
}
} else {
return v;
}
} else {
return 0;
}
} else {
return a;
}
}
return g;
| 747
| 313
| 1,060
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataResolutionResult.java
|
MetadataResolutionResult
|
getGraph
|
class MetadataResolutionResult {
MetadataTreeNode treeRoot;
/**
* these components are initialized on demand by
* explicit call of the initTreeProcessing()
*/
ClasspathTransformation classpathTransformation;
GraphConflictResolver conflictResolver;
// ----------------------------------------------------------------------------
public MetadataResolutionResult() {}
// ----------------------------------------------------------------------------
public MetadataResolutionResult(MetadataTreeNode root) {
this.treeRoot = root;
}
// ----------------------------------------------------------------------------
public MetadataTreeNode getTree() {
return treeRoot;
}
// ----------------------------------------------------------------------------
public void setTree(MetadataTreeNode root) {
this.treeRoot = root;
}
public void initTreeProcessing(PlexusContainer plexus) throws ComponentLookupException {
classpathTransformation = plexus.lookup(ClasspathTransformation.class);
conflictResolver = plexus.lookup(GraphConflictResolver.class);
}
// ----------------------------------------------------------------------------
public MetadataGraph getGraph() throws MetadataResolutionException {
return treeRoot == null ? null : new MetadataGraph(treeRoot);
}
// ----------------------------------------------------------------------------
public MetadataGraph getGraph(ArtifactScopeEnum scope)
throws MetadataResolutionException, GraphConflictResolutionException {
if (treeRoot == null) {
return null;
}
if (conflictResolver == null) {
return null;
}
return conflictResolver.resolveConflicts(getGraph(), scope);
}
// ----------------------------------------------------------------------------
public MetadataGraph getGraph(MetadataResolutionRequestTypeEnum requestType)
throws MetadataResolutionException, GraphConflictResolutionException {<FILL_FUNCTION_BODY>}
// ----------------------------------------------------------------------------
public ClasspathContainer getClasspath(ArtifactScopeEnum scope)
throws MetadataGraphTransformationException, MetadataResolutionException {
if (classpathTransformation == null) {
return null;
}
MetadataGraph dirtyGraph = getGraph();
if (dirtyGraph == null) {
return null;
}
return classpathTransformation.transform(dirtyGraph, scope, false);
}
// ----------------------------------------------------------------------------
public MetadataTreeNode getClasspathTree(ArtifactScopeEnum scope)
throws MetadataGraphTransformationException, MetadataResolutionException {
ClasspathContainer cpc = getClasspath(scope);
if (cpc == null) {
return null;
}
return cpc.getClasspathAsTree();
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
}
|
if (requestType == null) {
return null;
}
if (treeRoot == null) {
return null;
}
if (conflictResolver == null) {
return null;
}
if (requestType.equals(MetadataResolutionRequestTypeEnum.classpathCompile)) {
return conflictResolver.resolveConflicts(getGraph(), ArtifactScopeEnum.compile);
} else if (requestType.equals(MetadataResolutionRequestTypeEnum.classpathRuntime)) {
return conflictResolver.resolveConflicts(getGraph(), ArtifactScopeEnum.runtime);
} else if (requestType.equals(MetadataResolutionRequestTypeEnum.classpathTest)) {
return conflictResolver.resolveConflicts(getGraph(), ArtifactScopeEnum.test);
} else if (requestType.equals(MetadataResolutionRequestTypeEnum.graph)) {
return getGraph();
} else if (requestType.equals(MetadataResolutionRequestTypeEnum.versionedGraph)) {
return new MetadataGraph(getTree(), true, false);
} else if (requestType.equals(MetadataResolutionRequestTypeEnum.scopedGraph)) {
return new MetadataGraph(getTree(), true, true);
}
return null;
| 634
| 303
| 937
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataTreeNode.java
|
MetadataTreeNode
|
addChild
|
class MetadataTreeNode {
ArtifactMetadata md; // this node
MetadataTreeNode parent; // papa
/** default # of children. Used for tree creation optimization only */
int nChildren = 8;
MetadataTreeNode[] children; // of cause
public int getNChildren() {
return nChildren;
}
public void setNChildren(int children) {
nChildren = children;
}
// ------------------------------------------------------------------------
public MetadataTreeNode() {}
// ------------------------------------------------------------------------
public MetadataTreeNode(ArtifactMetadata md, MetadataTreeNode parent, boolean resolved, ArtifactScopeEnum scope) {
if (md != null) {
md.setArtifactScope(ArtifactScopeEnum.checkScope(scope));
md.setResolved(resolved);
}
this.md = md;
this.parent = parent;
}
// ------------------------------------------------------------------------
public MetadataTreeNode(Artifact af, MetadataTreeNode parent, boolean resolved, ArtifactScopeEnum scope) {
this(new ArtifactMetadata(af), parent, resolved, scope);
}
// ------------------------------------------------------------------------
public void addChild(int index, MetadataTreeNode kid) {<FILL_FUNCTION_BODY>}
// ------------------------------------------------------------------
@Override
public String toString() {
return md == null ? "no metadata" : md.toString();
}
// ------------------------------------------------------------------
public String graphHash() throws MetadataResolutionException {
if (md == null) {
throw new MetadataResolutionException(
"treenode without metadata, parent: " + (parent == null ? "null" : parent.toString()));
}
return md.groupId + ":" + md.artifactId;
}
// ------------------------------------------------------------------------
public boolean hasChildren() {
return children != null;
}
// ------------------------------------------------------------------------
public ArtifactMetadata getMd() {
return md;
}
public void setMd(ArtifactMetadata md) {
this.md = md;
}
public MetadataTreeNode getParent() {
return parent;
}
public void setParent(MetadataTreeNode parent) {
this.parent = parent;
}
public MetadataTreeNode[] getChildren() {
return children;
}
public void setChildren(MetadataTreeNode[] children) {
this.children = children;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
}
|
if (kid == null) {
return;
}
if (children == null) {
children = new MetadataTreeNode[nChildren];
}
children[index % nChildren] = kid;
| 609
| 59
| 668
|
<no_super_class>
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/settings/DefaultMavenSettingsBuilder.java
|
DefaultMavenSettingsBuilder
|
getFile
|
class DefaultMavenSettingsBuilder extends AbstractLogEnabled implements MavenSettingsBuilder {
private final SettingsBuilder settingsBuilder;
@Inject
public DefaultMavenSettingsBuilder(SettingsBuilder settingsBuilder) {
this.settingsBuilder = settingsBuilder;
}
public Settings buildSettings() throws IOException, XmlPullParserException {
File userSettingsFile = getFile(
"${user.home}/.m2/settings.xml", "user.home", MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION);
return buildSettings(userSettingsFile);
}
public Settings buildSettings(boolean useCachedSettings) throws IOException, XmlPullParserException {
return buildSettings();
}
public Settings buildSettings(File userSettingsFile) throws IOException, XmlPullParserException {
File globalSettingsFile = getFile(
"${maven.conf}/settings.xml", "maven.conf", MavenSettingsBuilder.ALT_GLOBAL_SETTINGS_XML_LOCATION);
SettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
request.setUserSettingsFile(userSettingsFile);
request.setGlobalSettingsFile(globalSettingsFile);
request.setSystemProperties(SystemProperties.getSystemProperties());
return build(request);
}
public Settings buildSettings(File userSettingsFile, boolean useCachedSettings)
throws IOException, XmlPullParserException {
return buildSettings(userSettingsFile);
}
private Settings build(SettingsBuildingRequest request) throws IOException, XmlPullParserException {
try {
return settingsBuilder.build(request).getEffectiveSettings();
} catch (SettingsBuildingException e) {
throw new IOException(e.getMessage(), e);
}
}
/** @since 2.1 */
public Settings buildSettings(MavenExecutionRequest request) throws IOException, XmlPullParserException {
SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
settingsRequest.setUserSettingsFile(request.getUserSettingsFile());
settingsRequest.setProjectSettingsFile(request.getProjectSettingsFile());
settingsRequest.setGlobalSettingsFile(request.getGlobalSettingsFile());
settingsRequest.setUserProperties(request.getUserProperties());
settingsRequest.setSystemProperties(request.getSystemProperties());
return build(settingsRequest);
}
private File getFile(String pathPattern, String basedirSysProp, String altLocationSysProp) {<FILL_FUNCTION_BODY>}
}
|
// -------------------------------------------------------------------------------------
// Alright, here's the justification for all the regexp wizardry below...
//
// Continuum and other server-like apps may need to locate the user-level and
// global-level settings somewhere other than ${user.home} and ${maven.home},
// respectively. Using a simple replacement of these patterns will allow them
// to specify the absolute path to these files in a customized components.xml
// file. Ideally, we'd do full pattern-evaluation against the sysprops, but this
// is a first step. There are several replacements below, in order to normalize
// the path character before we operate on the string as a regex input, and
// in order to avoid surprises with the File construction...
// -------------------------------------------------------------------------------------
String path = System.getProperty(altLocationSysProp);
if (path == null || path.isEmpty()) {
// TODO This replacing shouldn't be necessary as user.home should be in the
// context of the container and thus the value would be interpolated by Plexus
String basedir = System.getProperty(basedirSysProp);
if (basedir == null) {
basedir = System.getProperty("user.dir");
}
basedir = basedir.replace("\\", "/");
basedir = basedir.replace("$", "\\$");
// basedirSysProp is non regexp and basedir too
path = pathPattern.replace("${" + basedirSysProp + "}", basedir);
path = path.replace("\\", "/");
// ---------------------------------------------------------------------------------
// I'm not sure if this last regexp was really intended to disallow the usage of
// network paths as user.home directory. Unfortunately it did. I removed it and
// have not detected any problems yet.
// ---------------------------------------------------------------------------------
// path = path.replaceAll( "//", "/" );
}
return new File(path).getAbsoluteFile();
| 610
| 485
| 1,095
|
<methods>public void <init>() ,public void enableLogging(org.codehaus.plexus.logging.Logger) <variables>private org.codehaus.plexus.logging.Logger logger
|
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java
|
DefaultToolchainsBuilder
|
build
|
class DefaultToolchainsBuilder implements ToolchainsBuilder {
private final Logger logger = LoggerFactory.getLogger(getClass());
public PersistedToolchains build(File userToolchainsFile) throws MisconfiguredToolchainException {<FILL_FUNCTION_BODY>}
}
|
PersistedToolchains toolchains = null;
if (userToolchainsFile != null && userToolchainsFile.isFile()) {
try (InputStream in = Files.newInputStream(userToolchainsFile.toPath())) {
toolchains = new PersistedToolchains(new MavenToolchainsStaxReader().read(in));
} catch (Exception e) {
throw new MisconfiguredToolchainException(
"Cannot read toolchains file at " + userToolchainsFile.getAbsolutePath(), e);
}
} else if (userToolchainsFile != null) {
logger.debug("Toolchains configuration was not found at {}", userToolchainsFile);
}
return toolchains;
| 72
| 188
| 260
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.